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

1.594   ! djm         1: /* $OpenBSD: ssh.c,v 1.593 2023/07/26 23:06:00 djm Exp $ */
1.1       deraadt     2: /*
1.32      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Ssh client program.  This program can be used to log into a remote machine.
                      7:  * The software supports strong authentication, encryption, and forwarding
                      8:  * of X11, TCP/IP, and authentication connections.
                      9:  *
1.64      deraadt    10:  * As far as I am concerned, the code I have written for this software
                     11:  * can be used freely for any purpose.  Any derived versions of this
                     12:  * software must be clearly marked as such, and if the derived work is
                     13:  * incompatible with the protocol description in the RFC file, it must be
                     14:  * called by a name other than "ssh" or "Secure Shell".
                     15:  *
                     16:  * Copyright (c) 1999 Niels Provos.  All rights reserved.
1.202     markus     17:  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
1.64      deraadt    18:  *
1.529     dtucker    19:  * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
1.64      deraadt    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.509     naddy      63: #include <stdarg.h>
1.288     stevesk    64: #include <unistd.h>
1.414     deraadt    65: #include <limits.h>
1.445     djm        66: #include <locale.h>
1.49      markus     67:
1.402     markus     68: #ifdef WITH_OPENSSL
1.49      markus     69: #include <openssl/evp.h>
1.72      markus     70: #include <openssl/err.h>
1.402     markus     71: #endif
1.1       deraadt    72:
1.293     deraadt    73: #include "xmalloc.h"
1.84      markus     74: #include "ssh.h"
                     75: #include "ssh2.h"
1.341     djm        76: #include "canohost.h"
1.84      markus     77: #include "compat.h"
                     78: #include "cipher.h"
1.1       deraadt    79: #include "packet.h"
1.482     markus     80: #include "sshbuf.h"
1.123     markus     81: #include "channels.h"
1.483     markus     82: #include "sshkey.h"
1.58      markus     83: #include "authfd.h"
1.49      markus     84: #include "authfile.h"
1.83      markus     85: #include "pathnames.h"
1.214     djm        86: #include "dispatch.h"
1.81      markus     87: #include "clientloop.h"
1.84      markus     88: #include "log.h"
1.406     millert    89: #include "misc.h"
1.84      markus     90: #include "readconf.h"
                     91: #include "sshconnect.h"
1.95      markus     92: #include "kex.h"
                     93: #include "mac.h"
1.213     deraadt    94: #include "sshpty.h"
1.212     djm        95: #include "match.h"
1.214     djm        96: #include "msg.h"
1.278     stevesk    97: #include "version.h"
1.412     djm        98: #include "ssherr.h"
1.420     djm        99: #include "myproposal.h"
1.49      markus    100:
1.333     markus    101: #ifdef ENABLE_PKCS11
                    102: #include "ssh-pkcs11.h"
1.137     jakob     103: #endif
1.498     djm       104:
1.49      markus    105: extern char *__progname;
1.1       deraadt   106:
1.316     djm       107: /* Flag indicating whether debug mode is on.  May be set on the command line. */
1.1       deraadt   108: int debug_flag = 0;
                    109:
1.359     djm       110: /* Flag indicating whether a tty should be requested */
1.1       deraadt   111: int tty_flag = 0;
                    112:
1.33      markus    113: /*
1.344     djm       114:  * Flag indicating that the current process should be backgrounded and
1.531     djm       115:  * a new mux-client launched in the foreground for ControlPersist.
1.344     djm       116:  */
1.593     djm       117: static int need_controlpersist_detach = 0;
1.344     djm       118:
1.531     djm       119: /* Copies of flags for ControlPersist foreground mux-client */
1.593     djm       120: static int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
                    121: static int ofork_after_authentication;
1.344     djm       122:
                    123: /*
1.33      markus    124:  * General data structure for command line options and options configurable
                    125:  * in configuration files.  See readconf.h.
                    126:  */
1.1       deraadt   127: Options options;
                    128:
1.139     markus    129: /* optional user configfile */
                    130: char *config = NULL;
                    131:
1.33      markus    132: /*
                    133:  * Name of the host we are connecting to.  This is the name given on the
1.503     jmc       134:  * command line, or the Hostname specified for the user-supplied name in a
1.33      markus    135:  * configuration file.
                    136:  */
1.1       deraadt   137: char *host;
                    138:
1.510     djm       139: /*
                    140:  * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
                    141:  * not NULL, forward the socket at this path instead.
                    142:  */
                    143: char *forward_agent_sock_path = NULL;
                    144:
1.22      provos    145: /* socket address the host resolves to */
1.37      markus    146: struct sockaddr_storage hostaddr;
1.1       deraadt   147:
1.112     markus    148: /* Private host keys. */
1.173     markus    149: Sensitive sensitive_data;
1.1       deraadt   150:
1.45      markus    151: /* command to be executed */
1.482     markus    152: struct sshbuf *command;
1.45      markus    153:
1.170     markus    154: /* # of replies received for global requests */
1.523     djm       155: static int forward_confirms_pending = -1;
1.170     markus    156:
1.313     djm       157: /* mux.c */
                    158: extern int muxserver_sock;
                    159: extern u_int muxclient_command;
                    160:
1.1       deraadt   161: /* Prints a help message to the user.  This function never returns. */
                    162:
1.126     itojun    163: static void
1.93      itojun    164: usage(void)
1.1       deraadt   165: {
1.208     markus    166:        fprintf(stderr,
1.592     jmc       167: "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address]\n"
                    168: "           [-c cipher_spec] [-D [bind_address:]port] [-E log_file]\n"
                    169: "           [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file]\n"
                    170: "           [-J destination] [-L address] [-l login_name] [-m mac_spec]\n"
                    171: "           [-O ctl_cmd] [-o option] [-P tag] [-p port] [-Q query_option]\n"
                    172: "           [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
                    173: "           destination [command [argument ...]]\n"
1.208     markus    174:        );
1.257     dtucker   175:        exit(255);
1.1       deraadt   176: }
                    177:
1.544     djm       178: static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
                    179: static void load_public_identity_files(const struct ssh_conn_info *);
1.352     djm       180: static void main_sigchld_handler(int);
1.312     djm       181:
1.361     djm       182: /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
                    183: static void
                    184: tilde_expand_paths(char **paths, u_int num_paths)
                    185: {
                    186:        u_int i;
                    187:        char *cp;
                    188:
                    189:        for (i = 0; i < num_paths; i++) {
1.490     dtucker   190:                cp = tilde_expand_filename(paths[i], getuid());
1.378     djm       191:                free(paths[i]);
1.361     djm       192:                paths[i] = cp;
                    193:        }
                    194: }
                    195:
1.527     dtucker   196: /*
                    197:  * Expands the set of percent_expand options used by the majority of keywords
                    198:  * in the client that support percent expansion.
                    199:  * Caller must free returned string.
                    200:  */
                    201: static char *
1.544     djm       202: default_client_percent_expand(const char *str,
                    203:     const struct ssh_conn_info *cinfo)
1.527     dtucker   204: {
                    205:        return percent_expand(str,
1.546     djm       206:            DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
1.527     dtucker   207:            (char *)NULL);
                    208: }
                    209:
1.400     djm       210: /*
1.528     dtucker   211:  * Expands the set of percent_expand options used by the majority of keywords
                    212:  * AND perform environment variable substitution.
                    213:  * Caller must free returned string.
                    214:  */
                    215: static char *
1.544     djm       216: default_client_percent_dollar_expand(const char *str,
                    217:     const struct ssh_conn_info *cinfo)
1.528     dtucker   218: {
                    219:        char *ret;
                    220:
                    221:        ret = percent_dollar_expand(str,
1.546     djm       222:            DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
1.528     dtucker   223:            (char *)NULL);
                    224:        if (ret == NULL)
                    225:                fatal("invalid environment variable expansion");
                    226:        return ret;
                    227: }
                    228:
                    229: /*
1.400     djm       230:  * Attempt to resolve a host name / port to a set of addresses and
                    231:  * optionally return any CNAMEs encountered along the way.
                    232:  * Returns NULL on failure.
                    233:  * NB. this function must operate with a options having undefined members.
                    234:  */
1.385     djm       235: static struct addrinfo *
1.400     djm       236: resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
1.385     djm       237: {
                    238:        char strport[NI_MAXSERV];
1.579     djm       239:        const char *errstr = NULL;
1.385     djm       240:        struct addrinfo hints, *res;
1.501     dtucker   241:        int gaierr;
                    242:        LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
1.385     djm       243:
1.400     djm       244:        if (port <= 0)
                    245:                port = default_ssh_port();
1.521     markus    246:        if (cname != NULL)
                    247:                *cname = '\0';
1.568     djm       248:        debug3_f("lookup %s:%d", name, port);
1.400     djm       249:
1.427     djm       250:        snprintf(strport, sizeof strport, "%d", port);
1.398     tedu      251:        memset(&hints, 0, sizeof(hints));
1.400     djm       252:        hints.ai_family = options.address_family == -1 ?
                    253:            AF_UNSPEC : options.address_family;
1.385     djm       254:        hints.ai_socktype = SOCK_STREAM;
                    255:        if (cname != NULL)
                    256:                hints.ai_flags = AI_CANONNAME;
                    257:        if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
                    258:                if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
                    259:                        loglevel = SYSLOG_LEVEL_ERROR;
                    260:                do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
                    261:                    __progname, name, ssh_gai_strerror(gaierr));
                    262:                return NULL;
                    263:        }
                    264:        if (cname != NULL && res->ai_canonname != NULL) {
1.579     djm       265:                if (!valid_domain(res->ai_canonname, 0, &errstr)) {
                    266:                        error("ignoring bad CNAME \"%s\" for host \"%s\": %s",
                    267:                            res->ai_canonname, name, errstr);
                    268:                } else if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
1.540     djm       269:                        error_f("host \"%s\" cname \"%s\" too long (max %lu)",
                    270:                            name,  res->ai_canonname, (u_long)clen);
1.385     djm       271:                        if (clen > 0)
                    272:                                *cname = '\0';
                    273:                }
                    274:        }
                    275:        return res;
                    276: }
                    277:
1.470     djm       278: /* Returns non-zero if name can only be an address and not a hostname */
                    279: static int
                    280: is_addr_fast(const char *name)
                    281: {
                    282:        return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
                    283:            strspn(name, "0123456789.") == strlen(name));
                    284: }
                    285:
                    286: /* Returns non-zero if name represents a valid, single address */
                    287: static int
                    288: is_addr(const char *name)
                    289: {
                    290:        char strport[NI_MAXSERV];
                    291:        struct addrinfo hints, *res;
                    292:
                    293:        if (is_addr_fast(name))
                    294:                return 1;
                    295:
                    296:        snprintf(strport, sizeof strport, "%u", default_ssh_port());
                    297:        memset(&hints, 0, sizeof(hints));
                    298:        hints.ai_family = options.address_family == -1 ?
                    299:            AF_UNSPEC : options.address_family;
                    300:        hints.ai_socktype = SOCK_STREAM;
                    301:        hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
                    302:        if (getaddrinfo(name, strport, &hints, &res) != 0)
                    303:                return 0;
                    304:        if (res == NULL || res->ai_next != NULL) {
                    305:                freeaddrinfo(res);
                    306:                return 0;
                    307:        }
                    308:        freeaddrinfo(res);
                    309:        return 1;
                    310: }
                    311:
1.385     djm       312: /*
1.413     djm       313:  * Attempt to resolve a numeric host address / port to a single address.
                    314:  * Returns a canonical address string.
                    315:  * Returns NULL on failure.
                    316:  * NB. this function must operate with a options having undefined members.
                    317:  */
                    318: static struct addrinfo *
                    319: resolve_addr(const char *name, int port, char *caddr, size_t clen)
                    320: {
                    321:        char addr[NI_MAXHOST], strport[NI_MAXSERV];
                    322:        struct addrinfo hints, *res;
                    323:        int gaierr;
                    324:
                    325:        if (port <= 0)
                    326:                port = default_ssh_port();
                    327:        snprintf(strport, sizeof strport, "%u", port);
                    328:        memset(&hints, 0, sizeof(hints));
                    329:        hints.ai_family = options.address_family == -1 ?
                    330:            AF_UNSPEC : options.address_family;
                    331:        hints.ai_socktype = SOCK_STREAM;
                    332:        hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
                    333:        if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
1.540     djm       334:                debug2_f("could not resolve name %.100s as address: %s",
                    335:                    name, ssh_gai_strerror(gaierr));
1.413     djm       336:                return NULL;
                    337:        }
                    338:        if (res == NULL) {
1.540     djm       339:                debug_f("getaddrinfo %.100s returned no addresses", name);
1.413     djm       340:                return NULL;
                    341:        }
                    342:        if (res->ai_next != NULL) {
1.540     djm       343:                debug_f("getaddrinfo %.100s returned multiple addresses", name);
1.413     djm       344:                goto fail;
                    345:        }
                    346:        if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
                    347:            addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
1.540     djm       348:                debug_f("Could not format address for name %.100s: %s",
                    349:                    name, ssh_gai_strerror(gaierr));
1.413     djm       350:                goto fail;
                    351:        }
                    352:        if (strlcpy(caddr, addr, clen) >= clen) {
1.540     djm       353:                error_f("host \"%s\" addr \"%s\" too long (max %lu)",
                    354:                    name,  addr, (u_long)clen);
1.413     djm       355:                if (clen > 0)
                    356:                        *caddr = '\0';
                    357:  fail:
                    358:                freeaddrinfo(res);
                    359:                return NULL;
                    360:        }
                    361:        return res;
                    362: }
                    363:
                    364: /*
1.385     djm       365:  * Check whether the cname is a permitted replacement for the hostname
                    366:  * and perform the replacement if it is.
1.400     djm       367:  * NB. this function must operate with a options having undefined members.
1.385     djm       368:  */
                    369: static int
1.443     djm       370: check_follow_cname(int direct, char **namep, const char *cname)
1.385     djm       371: {
                    372:        int i;
                    373:        struct allowed_cname *rule;
                    374:
1.568     djm       375:        if (*cname == '\0' || !config_has_permitted_cnames(&options) ||
1.385     djm       376:            strcmp(*namep, cname) == 0)
                    377:                return 0;
1.386     djm       378:        if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
1.385     djm       379:                return 0;
                    380:        /*
1.386     djm       381:         * Don't attempt to canonicalize names that will be interpreted by
1.443     djm       382:         * a proxy or jump host unless the user specifically requests so.
1.385     djm       383:         */
1.443     djm       384:        if (!direct &&
1.386     djm       385:            options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
1.385     djm       386:                return 0;
1.540     djm       387:        debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
1.385     djm       388:        for (i = 0; i < options.num_permitted_cnames; i++) {
                    389:                rule = options.permitted_cnames + i;
1.418     djm       390:                if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
                    391:                    match_pattern_list(cname, rule->target_list, 1) != 1)
1.385     djm       392:                        continue;
1.386     djm       393:                verbose("Canonicalized DNS aliased hostname "
1.385     djm       394:                    "\"%s\" => \"%s\"", *namep, cname);
                    395:                free(*namep);
                    396:                *namep = xstrdup(cname);
                    397:                return 1;
                    398:        }
                    399:        return 0;
                    400: }
                    401:
                    402: /*
                    403:  * Attempt to resolve the supplied hostname after applying the user's
1.387     djm       404:  * canonicalization rules. Returns the address list for the host or NULL
                    405:  * if no name was found after canonicalization.
1.400     djm       406:  * NB. this function must operate with a options having undefined members.
1.385     djm       407:  */
                    408: static struct addrinfo *
1.400     djm       409: resolve_canonicalize(char **hostp, int port)
1.385     djm       410: {
1.443     djm       411:        int i, direct, ndots;
1.413     djm       412:        char *cp, *fullhost, newname[NI_MAXHOST];
1.385     djm       413:        struct addrinfo *addrs;
                    414:
                    415:        /*
1.470     djm       416:         * Attempt to canonicalise addresses, regardless of
                    417:         * whether hostname canonicalisation was requested
1.385     djm       418:         */
1.413     djm       419:        if ((addrs = resolve_addr(*hostp, port,
                    420:            newname, sizeof(newname))) != NULL) {
1.540     djm       421:                debug2_f("hostname %.100s is address", *hostp);
1.413     djm       422:                if (strcasecmp(*hostp, newname) != 0) {
1.540     djm       423:                        debug2_f("canonicalised address \"%s\" => \"%s\"",
                    424:                            *hostp, newname);
1.413     djm       425:                        free(*hostp);
                    426:                        *hostp = xstrdup(newname);
                    427:                }
                    428:                return addrs;
                    429:        }
                    430:
1.470     djm       431:        /*
                    432:         * If this looks like an address but didn't parse as one, it might
                    433:         * be an address with an invalid interface scope. Skip further
                    434:         * attempts at canonicalisation.
                    435:         */
                    436:        if (is_addr_fast(*hostp)) {
1.540     djm       437:                debug_f("hostname %.100s is an unrecognised address", *hostp);
1.470     djm       438:                return NULL;
                    439:        }
                    440:
                    441:        if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
                    442:                return NULL;
                    443:
                    444:        /*
                    445:         * Don't attempt to canonicalize names that will be interpreted by
                    446:         * a proxy unless the user specifically requests so.
                    447:         */
                    448:        direct = option_clear_or_none(options.proxy_command) &&
1.588     djm       449:            option_clear_or_none(options.jump_host);
1.470     djm       450:        if (!direct &&
                    451:            options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
                    452:                return NULL;
                    453:
1.428     djm       454:        /* If domain name is anchored, then resolve it now */
                    455:        if ((*hostp)[strlen(*hostp) - 1] == '.') {
1.540     djm       456:                debug3_f("name is fully qualified");
1.428     djm       457:                fullhost = xstrdup(*hostp);
                    458:                if ((addrs = resolve_host(fullhost, port, 0,
                    459:                    newname, sizeof(newname))) != NULL)
                    460:                        goto found;
                    461:                free(fullhost);
                    462:                goto notfound;
                    463:        }
                    464:
1.387     djm       465:        /* Don't apply canonicalization to sufficiently-qualified hostnames */
1.385     djm       466:        ndots = 0;
                    467:        for (cp = *hostp; *cp != '\0'; cp++) {
                    468:                if (*cp == '.')
                    469:                        ndots++;
                    470:        }
1.386     djm       471:        if (ndots > options.canonicalize_max_dots) {
1.540     djm       472:                debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
                    473:                    *hostp, options.canonicalize_max_dots);
1.385     djm       474:                return NULL;
                    475:        }
                    476:        /* Attempt each supplied suffix */
                    477:        for (i = 0; i < options.num_canonical_domains; i++) {
1.559     djm       478:                if (strcasecmp(options.canonical_domains[i], "none") == 0)
                    479:                        break;
1.385     djm       480:                xasprintf(&fullhost, "%s.%s.", *hostp,
                    481:                    options.canonical_domains[i]);
1.540     djm       482:                debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
1.400     djm       483:                if ((addrs = resolve_host(fullhost, port, 0,
1.413     djm       484:                    newname, sizeof(newname))) == NULL) {
1.385     djm       485:                        free(fullhost);
                    486:                        continue;
                    487:                }
1.428     djm       488:  found:
1.385     djm       489:                /* Remove trailing '.' */
                    490:                fullhost[strlen(fullhost) - 1] = '\0';
                    491:                /* Follow CNAME if requested */
1.443     djm       492:                if (!check_follow_cname(direct, &fullhost, newname)) {
1.386     djm       493:                        debug("Canonicalized hostname \"%s\" => \"%s\"",
1.385     djm       494:                            *hostp, fullhost);
                    495:                }
                    496:                free(*hostp);
                    497:                *hostp = fullhost;
                    498:                return addrs;
                    499:        }
1.428     djm       500:  notfound:
1.386     djm       501:        if (!options.canonicalize_fallback_local)
1.400     djm       502:                fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
1.540     djm       503:        debug2_f("host %s not found in any suffix", *hostp);
1.385     djm       504:        return NULL;
                    505: }
                    506:
1.32      deraadt   507: /*
1.576     djm       508:  * Check the result of hostkey loading, ignoring some errors and either
                    509:  * discarding the key or fatal()ing for others.
1.483     markus    510:  */
                    511: static void
1.576     djm       512: check_load(int r, struct sshkey **k, const char *path, const char *message)
1.483     markus    513: {
                    514:        switch (r) {
                    515:        case 0:
1.576     djm       516:                /* Check RSA keys size and discard if undersized */
                    517:                if (k != NULL && *k != NULL &&
                    518:                    (r = sshkey_check_rsa_length(*k,
                    519:                    options.required_rsa_size)) != 0) {
                    520:                        error_r(r, "load %s \"%s\"", message, path);
                    521:                        free(*k);
                    522:                        *k = NULL;
                    523:                }
1.483     markus    524:                break;
                    525:        case SSH_ERR_INTERNAL_ERROR:
                    526:        case SSH_ERR_ALLOC_FAIL:
1.540     djm       527:                fatal_r(r, "load %s \"%s\"", message, path);
1.483     markus    528:        case SSH_ERR_SYSTEM_ERROR:
                    529:                /* Ignore missing files */
                    530:                if (errno == ENOENT)
                    531:                        break;
                    532:                /* FALLTHROUGH */
                    533:        default:
1.540     djm       534:                error_r(r, "load %s \"%s\"", message, path);
1.483     markus    535:                break;
                    536:        }
                    537: }
                    538:
                    539: /*
1.400     djm       540:  * Read per-user configuration file.  Ignore the system wide config
                    541:  * file if the user specifies a config file on the command line.
                    542:  */
                    543: static void
1.496     djm       544: process_config_files(const char *host_name, struct passwd *pw, int final_pass,
                    545:     int *want_final_pass)
1.400     djm       546: {
1.414     deraadt   547:        char buf[PATH_MAX];
1.400     djm       548:        int r;
                    549:
                    550:        if (config != NULL) {
                    551:                if (strcasecmp(config, "none") != 0 &&
1.466     djm       552:                    !read_config_file(config, pw, host, host_name, &options,
1.496     djm       553:                    SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
                    554:                    want_final_pass))
1.400     djm       555:                        fatal("Can't open user config file %.100s: "
                    556:                            "%.100s", config, strerror(errno));
                    557:        } else {
                    558:                r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
                    559:                    _PATH_SSH_USER_CONFFILE);
                    560:                if (r > 0 && (size_t)r < sizeof(buf))
1.466     djm       561:                        (void)read_config_file(buf, pw, host, host_name,
1.408     djm       562:                            &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
1.496     djm       563:                            (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
1.400     djm       564:
                    565:                /* Read systemwide configuration file after user config. */
1.408     djm       566:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
1.466     djm       567:                    host, host_name, &options,
1.496     djm       568:                    final_pass ? SSHCONF_FINAL : 0, want_final_pass);
1.408     djm       569:        }
                    570: }
                    571:
                    572: /* Rewrite the port number in an addrinfo list of addresses */
                    573: static void
                    574: set_addrinfo_port(struct addrinfo *addrs, int port)
                    575: {
                    576:        struct addrinfo *addr;
                    577:
                    578:        for (addr = addrs; addr != NULL; addr = addr->ai_next) {
                    579:                switch (addr->ai_family) {
                    580:                case AF_INET:
                    581:                        ((struct sockaddr_in *)addr->ai_addr)->
                    582:                            sin_port = htons(port);
                    583:                        break;
                    584:                case AF_INET6:
                    585:                        ((struct sockaddr_in6 *)addr->ai_addr)->
                    586:                            sin6_port = htons(port);
                    587:                        break;
                    588:                }
1.400     djm       589:        }
                    590: }
                    591:
1.544     djm       592: static void
                    593: ssh_conn_info_free(struct ssh_conn_info *cinfo)
                    594: {
                    595:        if (cinfo == NULL)
                    596:                return;
                    597:        free(cinfo->conn_hash_hex);
                    598:        free(cinfo->shorthost);
                    599:        free(cinfo->uidstr);
                    600:        free(cinfo->keyalias);
                    601:        free(cinfo->thishost);
                    602:        free(cinfo->host_arg);
                    603:        free(cinfo->portstr);
                    604:        free(cinfo->remhost);
                    605:        free(cinfo->remuser);
                    606:        free(cinfo->homedir);
                    607:        free(cinfo->locuser);
                    608:        free(cinfo);
                    609: }
                    610:
1.400     djm       611: /*
1.32      deraadt   612:  * Main program for the ssh client.
                    613:  */
1.2       provos    614: int
                    615: main(int ac, char **av)
1.1       deraadt   616: {
1.437     djm       617:        struct ssh *ssh = NULL;
1.462     djm       618:        int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
1.496     djm       619:        int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
1.583     dtucker   620:        char *p, *cp, *line, *argv0, *logfile;
1.544     djm       621:        char cname[NI_MAXHOST], thishost[NI_MAXHOST];
1.31      markus    622:        struct stat st;
1.98      markus    623:        struct passwd *pw;
1.144     stevesk   624:        extern int optind, optreset;
                    625:        extern char *optarg;
1.406     millert   626:        struct Forward fwd;
1.385     djm       627:        struct addrinfo *addrs = NULL;
1.513     dtucker   628:        size_t n, len;
1.532     dtucker   629:        u_int j;
1.544     djm       630:        struct ssh_conn_info *cinfo = NULL;
1.250     djm       631:
                    632:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    633:        sanitise_stdfd();
1.31      markus    634:
1.33      markus    635:        /*
1.346     djm       636:         * Discard other fds that are hanging around. These can cause problem
                    637:         * with backgrounded ssh processes started by ControlPersist.
                    638:         */
                    639:        closefrom(STDERR_FILENO + 1);
                    640:
1.487     dtucker   641:        if (getuid() != geteuid())
                    642:                fatal("ssh setuid not supported.");
                    643:        if (getgid() != getegid())
                    644:                fatal("ssh setgid not supported.");
1.184     stevesk   645:
1.107     markus    646:        /* Get user data. */
1.490     dtucker   647:        pw = getpwuid(getuid());
1.107     markus    648:        if (!pw) {
1.490     dtucker   649:                logit("No user exists for uid %lu", (u_long)getuid());
1.257     dtucker   650:                exit(255);
1.107     markus    651:        }
                    652:        /* Take a copy of the returned structure. */
                    653:        pw = pwcopy(pw);
1.31      markus    654:
1.33      markus    655:        /*
                    656:         * Set our umask to something reasonable, as some files are created
                    657:         * with the default umask.  This will make them world-readable but
                    658:         * writable only by the owner, which is ok for all files for which we
                    659:         * don't set the modes explicitly.
                    660:         */
1.577     djm       661:        umask(022 | umask(077));
1.445     djm       662:
                    663:        setlocale(LC_CTYPE, "");
1.31      markus    664:
1.316     djm       665:        /*
                    666:         * Initialize option structure to indicate that no values have been
                    667:         * set.
                    668:         */
1.31      markus    669:        initialize_options(&options);
                    670:
1.463     djm       671:        /*
                    672:         * Prepare main ssh transport/connection structures
                    673:         */
                    674:        if ((ssh = ssh_alloc_session_state()) == NULL)
                    675:                fatal("Couldn't allocate session state");
                    676:        channel_init_channels(ssh);
                    677:
1.31      markus    678:        /* Parse command-line arguments. */
                    679:        host = NULL;
1.320     djm       680:        use_syslog = 0;
1.375     dtucker   681:        logfile = NULL;
1.325     markus    682:        argv0 = av[0];
1.31      markus    683:
1.266     djm       684:  again:
1.316     djm       685:        while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
1.591     djm       686:            "AB:CD:E:F:GI:J:KL:MNO:P:Q:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
1.31      markus    687:                switch (opt) {
1.91      jakob     688:                case '1':
1.454     djm       689:                        fatal("SSH protocol v.1 is no longer supported");
1.91      jakob     690:                        break;
1.47      markus    691:                case '2':
1.454     djm       692:                        /* Ignored */
1.47      markus    693:                        break;
1.37      markus    694:                case '4':
1.196     djm       695:                        options.address_family = AF_INET;
1.37      markus    696:                        break;
                    697:                case '6':
1.196     djm       698:                        options.address_family = AF_INET6;
1.37      markus    699:                        break;
1.31      markus    700:                case 'n':
1.563     djm       701:                        options.stdin_null = 1;
1.31      markus    702:                        break;
                    703:                case 'f':
1.564     djm       704:                        options.fork_after_authentication = 1;
1.563     djm       705:                        options.stdin_null = 1;
1.31      markus    706:                        break;
                    707:                case 'x':
                    708:                        options.forward_x11 = 0;
                    709:                        break;
                    710:                case 'X':
                    711:                        options.forward_x11 = 1;
                    712:                        break;
1.320     djm       713:                case 'y':
                    714:                        use_syslog = 1;
                    715:                        break;
1.375     dtucker   716:                case 'E':
1.422     dtucker   717:                        logfile = optarg;
1.375     dtucker   718:                        break;
1.408     djm       719:                case 'G':
                    720:                        config_test = 1;
                    721:                        break;
1.202     markus    722:                case 'Y':
                    723:                        options.forward_x11 = 1;
                    724:                        options.forward_x11_trusted = 1;
                    725:                        break;
1.31      markus    726:                case 'g':
1.406     millert   727:                        options.fwd_opts.gateway_ports = 1;
1.31      markus    728:                        break;
1.229     djm       729:                case 'O':
1.441     dtucker   730:                        if (options.stdio_forward_host != NULL)
1.332     djm       731:                                fatal("Cannot specify multiplexing "
                    732:                                    "command with -W");
                    733:                        else if (muxclient_command != 0)
                    734:                                fatal("Multiplexing command already specified");
1.229     djm       735:                        if (strcmp(optarg, "check") == 0)
1.312     djm       736:                                muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
1.338     markus    737:                        else if (strcmp(optarg, "forward") == 0)
                    738:                                muxclient_command = SSHMUX_COMMAND_FORWARD;
1.229     djm       739:                        else if (strcmp(optarg, "exit") == 0)
1.312     djm       740:                                muxclient_command = SSHMUX_COMMAND_TERMINATE;
1.357     djm       741:                        else if (strcmp(optarg, "stop") == 0)
                    742:                                muxclient_command = SSHMUX_COMMAND_STOP;
1.365     djm       743:                        else if (strcmp(optarg, "cancel") == 0)
                    744:                                muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
1.447     markus    745:                        else if (strcmp(optarg, "proxy") == 0)
                    746:                                muxclient_command = SSHMUX_COMMAND_PROXY;
1.229     djm       747:                        else
                    748:                                fatal("Invalid multiplex command.");
                    749:                        break;
1.591     djm       750:                case 'P':
                    751:                        if (options.tag == NULL)
                    752:                                options.tag = xstrdup(optarg);
1.376     djm       753:                        break;
1.394     deraadt   754:                case 'Q':
1.376     djm       755:                        cp = NULL;
1.519     dtucker   756:                        if (strcmp(optarg, "cipher") == 0 ||
                    757:                            strcasecmp(optarg, "Ciphers") == 0)
1.393     djm       758:                                cp = cipher_alg_list('\n', 0);
1.394     deraadt   759:                        else if (strcmp(optarg, "cipher-auth") == 0)
1.393     djm       760:                                cp = cipher_alg_list('\n', 1);
1.519     dtucker   761:                        else if (strcmp(optarg, "mac") == 0 ||
                    762:                            strcasecmp(optarg, "MACs") == 0)
1.392     dtucker   763:                                cp = mac_alg_list('\n');
1.519     dtucker   764:                        else if (strcmp(optarg, "kex") == 0 ||
                    765:                            strcasecmp(optarg, "KexAlgorithms") == 0)
1.392     dtucker   766:                                cp = kex_alg_list('\n');
1.394     deraadt   767:                        else if (strcmp(optarg, "key") == 0)
1.451     djm       768:                                cp = sshkey_alg_list(0, 0, 0, '\n');
1.396     markus    769:                        else if (strcmp(optarg, "key-cert") == 0)
1.451     djm       770:                                cp = sshkey_alg_list(1, 0, 0, '\n');
1.396     markus    771:                        else if (strcmp(optarg, "key-plain") == 0)
1.451     djm       772:                                cp = sshkey_alg_list(0, 1, 0, '\n');
1.589     djm       773:                        else if (strcmp(optarg, "key-ca-sign") == 0 ||
                    774:                            strcasecmp(optarg, "CASignatureAlgorithms") == 0)
                    775:                                cp = sshkey_alg_list(0, 1, 1, '\n');
1.519     dtucker   776:                        else if (strcmp(optarg, "key-sig") == 0 ||
1.547     dtucker   777:                            strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
                    778:                            strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
1.519     dtucker   779:                            strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
1.548     dtucker   780:                            strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
                    781:                            strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
                    782:                            strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
1.519     dtucker   783:                                cp = sshkey_alg_list(0, 0, 1, '\n');
1.491     djm       784:                        else if (strcmp(optarg, "sig") == 0)
1.492     djm       785:                                cp = sshkey_alg_list(0, 1, 1, '\n');
1.491     djm       786:                        else if (strcmp(optarg, "protocol-version") == 0)
1.416     djm       787:                                cp = xstrdup("2");
1.513     dtucker   788:                        else if (strcmp(optarg, "compression") == 0) {
                    789:                                cp = xstrdup(compression_alg_list(0));
                    790:                                len = strlen(cp);
                    791:                                for (n = 0; n < len; n++)
                    792:                                        if (cp[n] == ',')
                    793:                                                cp[n] = '\n';
                    794:                        } else if (strcmp(optarg, "help") == 0) {
1.491     djm       795:                                cp = xstrdup(
1.513     dtucker   796:                                    "cipher\ncipher-auth\ncompression\nkex\n"
1.519     dtucker   797:                                    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
1.491     djm       798:                                    "protocol-version\nsig");
1.416     djm       799:                        }
1.376     djm       800:                        if (cp == NULL)
                    801:                                fatal("Unsupported query \"%s\"", optarg);
                    802:                        printf("%s\n", cp);
                    803:                        free(cp);
                    804:                        exit(0);
1.31      markus    805:                        break;
                    806:                case 'a':
                    807:                        options.forward_agent = 0;
1.53      markus    808:                        break;
                    809:                case 'A':
                    810:                        options.forward_agent = 1;
1.31      markus    811:                        break;
                    812:                case 'k':
1.204     dtucker   813:                        options.gss_deleg_creds = 0;
1.297     djm       814:                        break;
                    815:                case 'K':
                    816:                        options.gss_authentication = 1;
                    817:                        options.gss_deleg_creds = 1;
1.31      markus    818:                        break;
                    819:                case 'i':
1.490     dtucker   820:                        p = tilde_expand_filename(optarg, getuid());
1.505     deraadt   821:                        if (stat(p, &st) == -1)
1.128     fgsch     822:                                fprintf(stderr, "Warning: Identity file %s "
1.429     dtucker   823:                                    "not accessible: %s.\n", p,
1.231     otto      824:                                    strerror(errno));
1.429     dtucker   825:                        else
                    826:                                add_identity_file(&options, NULL, p, 1);
                    827:                        free(p);
1.31      markus    828:                        break;
1.127     markus    829:                case 'I':
1.333     markus    830: #ifdef ENABLE_PKCS11
1.422     dtucker   831:                        free(options.pkcs11_provider);
1.333     markus    832:                        options.pkcs11_provider = xstrdup(optarg);
1.137     jakob     833: #else
1.333     markus    834:                        fprintf(stderr, "no support for PKCS#11.\n");
1.137     jakob     835: #endif
1.127     markus    836:                        break;
1.443     djm       837:                case 'J':
1.504     djm       838:                        if (options.jump_host != NULL) {
                    839:                                fatal("Only a single -J option is permitted "
                    840:                                    "(use commas to separate multiple "
                    841:                                    "jump hops)");
                    842:                        }
1.443     djm       843:                        if (options.proxy_command != NULL)
                    844:                                fatal("Cannot specify -J with ProxyCommand");
                    845:                        if (parse_jump(optarg, &options, 1) == -1)
                    846:                                fatal("Invalid -J argument");
                    847:                        options.proxy_command = xstrdup("none");
                    848:                        break;
1.31      markus    849:                case 't':
1.359     djm       850:                        if (options.request_tty == REQUEST_TTY_YES)
                    851:                                options.request_tty = REQUEST_TTY_FORCE;
                    852:                        else
                    853:                                options.request_tty = REQUEST_TTY_YES;
1.31      markus    854:                        break;
                    855:                case 'v':
1.197     markus    856:                        if (debug_flag == 0) {
1.66      markus    857:                                debug_flag = 1;
                    858:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    859:                        } else {
1.443     djm       860:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
                    861:                                        debug_flag++;
1.197     markus    862:                                        options.log_level++;
1.443     djm       863:                                }
1.197     markus    864:                        }
1.375     dtucker   865:                        break;
1.31      markus    866:                case 'V':
1.209     markus    867:                        fprintf(stderr, "%s, %s\n",
1.541     dtucker   868:                            SSH_VERSION, SSH_OPENSSL_VERSION);
1.584     millert   869:                        exit(0);
1.31      markus    870:                        break;
1.255     reyk      871:                case 'w':
1.256     reyk      872:                        if (options.tun_open == -1)
                    873:                                options.tun_open = SSH_TUNMODE_DEFAULT;
1.255     reyk      874:                        options.tun_local = a2tun(optarg, &options.tun_remote);
1.256     reyk      875:                        if (options.tun_local == SSH_TUNID_ERR) {
1.316     djm       876:                                fprintf(stderr,
                    877:                                    "Bad tun device '%s'\n", optarg);
1.257     dtucker   878:                                exit(255);
1.255     reyk      879:                        }
                    880:                        break;
1.331     dtucker   881:                case 'W':
1.441     dtucker   882:                        if (options.stdio_forward_host != NULL)
1.332     djm       883:                                fatal("stdio forward already specified");
                    884:                        if (muxclient_command != 0)
                    885:                                fatal("Cannot specify stdio forward with -O");
1.331     dtucker   886:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.590     dlg       887:                                options.stdio_forward_host =
                    888:                                    fwd.listen_port == PORT_STREAMLOCAL ?
                    889:                                    fwd.listen_path : fwd.listen_host;
1.441     dtucker   890:                                options.stdio_forward_port = fwd.listen_port;
1.378     djm       891:                                free(fwd.connect_host);
1.331     dtucker   892:                        } else {
                    893:                                fprintf(stderr,
                    894:                                    "Bad stdio forwarding specification '%s'\n",
                    895:                                    optarg);
                    896:                                exit(255);
                    897:                        }
1.359     djm       898:                        options.request_tty = REQUEST_TTY_NO;
1.560     djm       899:                        options.session_type = SESSION_TYPE_NONE;
1.331     dtucker   900:                        break;
1.31      markus    901:                case 'q':
                    902:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    903:                        break;
                    904:                case 'e':
                    905:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     906:                            (u_char) optarg[1] >= 64 &&
                    907:                            (u_char) optarg[1] < 128)
1.78      markus    908:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    909:                        else if (strlen(optarg) == 1)
1.78      markus    910:                                options.escape_char = (u_char) optarg[0];
1.31      markus    911:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   912:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    913:                        else {
1.128     fgsch     914:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    915:                                    optarg);
1.257     dtucker   916:                                exit(255);
1.31      markus    917:                        }
                    918:                        break;
                    919:                case 'c':
1.506     naddy     920:                        if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
1.420     djm       921:                            optarg + 1 : optarg)) {
                    922:                                fprintf(stderr, "Unknown cipher type '%s'\n",
                    923:                                    optarg);
                    924:                                exit(255);
1.95      markus    925:                        }
1.456     djm       926:                        free(options.ciphers);
                    927:                        options.ciphers = xstrdup(optarg);
1.95      markus    928:                        break;
                    929:                case 'm':
1.422     dtucker   930:                        if (mac_valid(optarg)) {
                    931:                                free(options.macs);
1.95      markus    932:                                options.macs = xstrdup(optarg);
1.422     dtucker   933:                        } else {
1.128     fgsch     934:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    935:                                    optarg);
1.257     dtucker   936:                                exit(255);
1.31      markus    937:                        }
                    938:                        break;
1.214     djm       939:                case 'M':
1.242     djm       940:                        if (options.control_master == SSHCTL_MASTER_YES)
                    941:                                options.control_master = SSHCTL_MASTER_ASK;
                    942:                        else
                    943:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       944:                        break;
1.31      markus    945:                case 'p':
1.465     millert   946:                        if (options.port == -1) {
                    947:                                options.port = a2port(optarg);
                    948:                                if (options.port <= 0) {
                    949:                                        fprintf(stderr, "Bad port '%s'\n",
                    950:                                            optarg);
                    951:                                        exit(255);
                    952:                                }
1.109     markus    953:                        }
1.31      markus    954:                        break;
                    955:                case 'l':
1.465     millert   956:                        if (options.user == NULL)
                    957:                                options.user = optarg;
1.31      markus    958:                        break;
1.141     stevesk   959:
                    960:                case 'L':
1.324     djm       961:                        if (parse_forward(&fwd, optarg, 0, 0))
1.232     djm       962:                                add_local_forward(&options, &fwd);
                    963:                        else {
1.128     fgsch     964:                                fprintf(stderr,
1.232     djm       965:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     966:                                    optarg);
1.257     dtucker   967:                                exit(255);
1.31      markus    968:                        }
1.232     djm       969:                        break;
                    970:
                    971:                case 'R':
1.464     markus    972:                        if (parse_forward(&fwd, optarg, 0, 1) ||
                    973:                            parse_forward(&fwd, optarg, 1, 1)) {
1.232     djm       974:                                add_remote_forward(&options, &fwd);
                    975:                        } else {
1.128     fgsch     976:                                fprintf(stderr,
1.232     djm       977:                                    "Bad remote forwarding specification "
                    978:                                    "'%s'\n", optarg);
1.257     dtucker   979:                                exit(255);
1.31      markus    980:                        }
                    981:                        break;
1.108     markus    982:
                    983:                case 'D':
1.324     djm       984:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.322     stevesk   985:                                add_local_forward(&options, &fwd);
1.232     djm       986:                        } else {
1.322     stevesk   987:                                fprintf(stderr,
                    988:                                    "Bad dynamic forwarding specification "
                    989:                                    "'%s'\n", optarg);
1.257     dtucker   990:                                exit(255);
1.109     markus    991:                        }
1.108     markus    992:                        break;
                    993:
1.31      markus    994:                case 'C':
1.513     dtucker   995: #ifdef WITH_ZLIB
1.31      markus    996:                        options.compression = 1;
1.513     dtucker   997: #else
                    998:                        error("Compression not supported, disabling.");
                    999: #endif
1.31      markus   1000:                        break;
1.45      markus   1001:                case 'N':
1.560     djm      1002:                        if (options.session_type != -1 &&
                   1003:                            options.session_type != SESSION_TYPE_NONE)
                   1004:                                fatal("Cannot specify -N with -s/SessionType");
                   1005:                        options.session_type = SESSION_TYPE_NONE;
1.359     djm      1006:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus   1007:                        break;
                   1008:                case 'T':
1.359     djm      1009:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus   1010:                        break;
1.31      markus   1011:                case 'o':
1.205     markus   1012:                        line = xstrdup(optarg);
1.408     djm      1013:                        if (process_config_line(&options, pw,
                   1014:                            host ? host : "", host ? host : "", line,
                   1015:                            "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1.257     dtucker  1016:                                exit(255);
1.378     djm      1017:                        free(line);
1.31      markus   1018:                        break;
1.85      djm      1019:                case 's':
1.560     djm      1020:                        if (options.session_type != -1 &&
                   1021:                            options.session_type != SESSION_TYPE_SUBSYSTEM)
                   1022:                                fatal("Cannot specify -s with -N/SessionType");
                   1023:                        options.session_type = SESSION_TYPE_SUBSYSTEM;
1.117     markus   1024:                        break;
1.214     djm      1025:                case 'S':
1.431     mmcc     1026:                        free(options.control_path);
1.214     djm      1027:                        options.control_path = xstrdup(optarg);
                   1028:                        break;
1.117     markus   1029:                case 'b':
                   1030:                        options.bind_address = optarg;
1.474     djm      1031:                        break;
                   1032:                case 'B':
                   1033:                        options.bind_interface = optarg;
1.85      djm      1034:                        break;
1.139     markus   1035:                case 'F':
                   1036:                        config = optarg;
                   1037:                        break;
1.31      markus   1038:                default:
                   1039:                        usage();
1.1       deraadt  1040:                }
1.31      markus   1041:        }
                   1042:
1.462     djm      1043:        if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
                   1044:                opt_terminated = 1;
                   1045:
1.128     fgsch    1046:        ac -= optind;
                   1047:        av += optind;
                   1048:
1.329     guenther 1049:        if (ac > 0 && !host) {
1.465     millert  1050:                int tport;
                   1051:                char *tuser;
                   1052:                switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
                   1053:                case -1:
                   1054:                        usage();
                   1055:                        break;
                   1056:                case 0:
                   1057:                        if (options.user == NULL) {
                   1058:                                options.user = tuser;
                   1059:                                tuser = NULL;
                   1060:                        }
                   1061:                        free(tuser);
                   1062:                        if (options.port == -1 && tport != -1)
                   1063:                                options.port = tport;
                   1064:                        break;
                   1065:                default:
1.128     fgsch    1066:                        p = xstrdup(*av);
1.188     markus   1067:                        cp = strrchr(p, '@');
1.465     millert  1068:                        if (cp != NULL) {
                   1069:                                if (cp == p)
                   1070:                                        usage();
                   1071:                                if (options.user == NULL) {
                   1072:                                        options.user = p;
                   1073:                                        p = NULL;
                   1074:                                }
                   1075:                                *cp++ = '\0';
                   1076:                                host = xstrdup(cp);
                   1077:                                free(p);
                   1078:                        } else
                   1079:                                host = p;
                   1080:                        break;
                   1081:                }
1.462     djm      1082:                if (ac > 1 && !opt_terminated) {
1.189     millert  1083:                        optind = optreset = 1;
1.128     fgsch    1084:                        goto again;
                   1085:                }
1.189     millert  1086:                ac--, av++;
1.128     fgsch    1087:        }
                   1088:
1.31      markus   1089:        /* Check that we got a host name. */
                   1090:        if (!host)
                   1091:                usage();
                   1092:
1.583     dtucker  1093:        options.host_arg = xstrdup(host);
1.385     djm      1094:
1.402     markus   1095: #ifdef WITH_OPENSSL
1.350     djm      1096:        OpenSSL_add_all_algorithms();
1.72      markus   1097:        ERR_load_crypto_strings();
1.402     markus   1098: #endif
1.31      markus   1099:
                   1100:        /* Initialize the command to execute on remote host. */
1.482     markus   1101:        if ((command = sshbuf_new()) == NULL)
                   1102:                fatal("sshbuf_new failed");
1.1       deraadt  1103:
1.33      markus   1104:        /*
                   1105:         * Save the command to execute on the remote host in a buffer. There
                   1106:         * is no limit on the length of the command, except by the maximum
                   1107:         * packet size.  Also sets the tty flag if there is no command.
                   1108:         */
1.128     fgsch    1109:        if (!ac) {
1.31      markus   1110:                /* No command specified - execute shell on a tty. */
1.560     djm      1111:                if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1.128     fgsch    1112:                        fprintf(stderr,
                   1113:                            "You must specify a subsystem to invoke.\n");
1.85      djm      1114:                        usage();
                   1115:                }
1.31      markus   1116:        } else {
1.128     fgsch    1117:                /* A command has been specified.  Store it into the buffer. */
                   1118:                for (i = 0; i < ac; i++) {
1.482     markus   1119:                        if ((r = sshbuf_putf(command, "%s%s",
                   1120:                            i ? " " : "", av[i])) != 0)
1.540     djm      1121:                                fatal_fr(r, "buffer error");
1.31      markus   1122:                }
                   1123:        }
                   1124:
1.575     djm      1125:        ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
                   1126:
1.101     markus   1127:        /*
                   1128:         * Initialize "log" output.  Since we are the client all output
1.375     dtucker  1129:         * goes to stderr unless otherwise specified by -y or -E.
1.101     markus   1130:         */
1.375     dtucker  1131:        if (use_syslog && logfile != NULL)
                   1132:                fatal("Can't specify both -y and -E");
1.422     dtucker  1133:        if (logfile != NULL)
1.375     dtucker  1134:                log_redirect_stderr_to(logfile);
1.325     markus   1135:        log_init(argv0,
1.468     djm      1136:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
1.452     dtucker  1137:            SYSLOG_LEVEL_INFO : options.log_level,
1.468     djm      1138:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1.452     dtucker  1139:            SYSLOG_FACILITY_USER : options.log_facility,
                   1140:            !use_syslog);
1.375     dtucker  1141:
                   1142:        if (debug_flag)
1.541     dtucker  1143:                logit("%s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1.31      markus   1144:
1.400     djm      1145:        /* Parse the configuration files */
1.583     dtucker  1146:        process_config_files(options.host_arg, pw, 0, &want_final_pass);
1.496     djm      1147:        if (want_final_pass)
                   1148:                debug("configuration requests final Match pass");
1.400     djm      1149:
                   1150:        /* Hostname canonicalisation needs a few options filled. */
                   1151:        fill_default_options_for_canonicalization(&options);
                   1152:
                   1153:        /* If the user has replaced the hostname then take it into use now */
                   1154:        if (options.hostname != NULL) {
                   1155:                /* NB. Please keep in sync with readconf.c:match_cfg_line() */
                   1156:                cp = percent_expand(options.hostname,
                   1157:                    "h", host, (char *)NULL);
                   1158:                free(host);
                   1159:                host = cp;
1.408     djm      1160:                free(options.hostname);
                   1161:                options.hostname = xstrdup(host);
1.400     djm      1162:        }
                   1163:
1.470     djm      1164:        /* Don't lowercase addresses, they will be explicitly canonicalised */
                   1165:        if ((was_addr = is_addr(host)) == 0)
                   1166:                lowercase(host);
                   1167:
                   1168:        /*
                   1169:         * Try to canonicalize if requested by configuration or the
                   1170:         * hostname is an address.
                   1171:         */
                   1172:        if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1.400     djm      1173:                addrs = resolve_canonicalize(&host, options.port);
                   1174:
1.139     markus   1175:        /*
1.401     djm      1176:         * If CanonicalizePermittedCNAMEs have been specified but
                   1177:         * other canonicalization did not happen (by not being requested
                   1178:         * or by failing with fallback) then the hostname may still be changed
1.468     djm      1179:         * as a result of CNAME following.
1.401     djm      1180:         *
                   1181:         * Try to resolve the bare hostname name using the system resolver's
                   1182:         * usual search rules and then apply the CNAME follow rules.
                   1183:         *
                   1184:         * Skip the lookup if a ProxyCommand is being used unless the user
                   1185:         * has specifically requested canonicalisation for this case via
                   1186:         * CanonicalizeHostname=always
1.139     markus   1187:         */
1.443     djm      1188:        direct = option_clear_or_none(options.proxy_command) &&
1.588     djm      1189:            option_clear_or_none(options.jump_host);
1.568     djm      1190:        if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1.443     djm      1191:            options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1.403     djm      1192:                if ((addrs = resolve_host(host, options.port,
1.493     djm      1193:                    direct, cname, sizeof(cname))) == NULL) {
1.403     djm      1194:                        /* Don't fatal proxied host names not in the DNS */
1.493     djm      1195:                        if (direct)
1.403     djm      1196:                                cleanup_exit(255); /* logged in resolve_host */
                   1197:                } else
1.443     djm      1198:                        check_follow_cname(direct, &host, cname);
1.400     djm      1199:        }
1.139     markus   1200:
1.400     djm      1201:        /*
1.408     djm      1202:         * If canonicalisation is enabled then re-parse the configuration
                   1203:         * files as new stanzas may match.
1.400     djm      1204:         */
1.496     djm      1205:        if (options.canonicalize_hostname != 0 && !want_final_pass) {
                   1206:                debug("hostname canonicalisation enabled, "
                   1207:                    "will re-parse configuration");
                   1208:                want_final_pass = 1;
                   1209:        }
                   1210:
                   1211:        if (want_final_pass) {
                   1212:                debug("re-parsing configuration");
1.408     djm      1213:                free(options.hostname);
                   1214:                options.hostname = xstrdup(host);
1.583     dtucker  1215:                process_config_files(options.host_arg, pw, 1, NULL);
1.408     djm      1216:                /*
                   1217:                 * Address resolution happens early with canonicalisation
                   1218:                 * enabled and the port number may have changed since, so
                   1219:                 * reset it in address list
                   1220:                 */
                   1221:                if (addrs != NULL && options.port > 0)
                   1222:                        set_addrinfo_port(addrs, options.port);
1.139     markus   1223:        }
1.31      markus   1224:
                   1225:        /* Fill configuration defaults. */
1.543     djm      1226:        if (fill_default_options(&options) != 0)
                   1227:                cleanup_exit(255);
1.443     djm      1228:
1.534     dtucker  1229:        if (options.user == NULL)
                   1230:                options.user = xstrdup(pw->pw_name);
                   1231:
1.443     djm      1232:        /*
                   1233:         * If ProxyJump option specified, then construct a ProxyCommand now.
                   1234:         */
                   1235:        if (options.jump_host != NULL) {
                   1236:                char port_s[8];
1.534     dtucker  1237:                const char *jumpuser = options.jump_user, *sshbin = argv0;
1.520     dtucker  1238:                int port = options.port, jumpport = options.jump_port;
                   1239:
                   1240:                if (port <= 0)
                   1241:                        port = default_ssh_port();
                   1242:                if (jumpport <= 0)
                   1243:                        jumpport = default_ssh_port();
1.534     dtucker  1244:                if (jumpuser == NULL)
                   1245:                        jumpuser = options.user;
                   1246:                if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
                   1247:                    strcmp(options.user, jumpuser) == 0)
1.520     dtucker  1248:                        fatal("jumphost loop via %s", options.jump_host);
1.478     djm      1249:
                   1250:                /*
                   1251:                 * Try to use SSH indicated by argv[0], but fall back to
                   1252:                 * "ssh" if it appears unavailable.
                   1253:                 */
                   1254:                if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
                   1255:                        sshbin = "ssh";
1.443     djm      1256:
                   1257:                /* Consistency check */
                   1258:                if (options.proxy_command != NULL)
                   1259:                        fatal("inconsistent options: ProxyCommand+ProxyJump");
                   1260:                /* Never use FD passing for ProxyJump */
                   1261:                options.proxy_use_fdpass = 0;
                   1262:                snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
                   1263:                xasprintf(&options.proxy_command,
1.478     djm      1264:                    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
                   1265:                    sshbin,
1.443     djm      1266:                    /* Optional "-l user" argument if jump_user set */
                   1267:                    options.jump_user == NULL ? "" : " -l ",
                   1268:                    options.jump_user == NULL ? "" : options.jump_user,
                   1269:                    /* Optional "-p port" argument if jump_port set */
                   1270:                    options.jump_port <= 0 ? "" : " -p ",
                   1271:                    options.jump_port <= 0 ? "" : port_s,
                   1272:                    /* Optional additional jump hosts ",..." */
                   1273:                    options.jump_extra == NULL ? "" : " -J ",
                   1274:                    options.jump_extra == NULL ? "" : options.jump_extra,
1.571     jsg      1275:                    /* Optional "-F" argument if -F specified */
1.443     djm      1276:                    config == NULL ? "" : " -F ",
                   1277:                    config == NULL ? "" : config,
                   1278:                    /* Optional "-v" arguments if -v set */
                   1279:                    debug_flag ? " -" : "",
                   1280:                    debug_flag, "vvv",
                   1281:                    /* Mandatory hostname */
                   1282:                    options.jump_host);
                   1283:                debug("Setting implicit ProxyCommand from ProxyJump: %s",
                   1284:                    options.proxy_command);
                   1285:        }
1.31      markus   1286:
1.400     djm      1287:        if (options.port == 0)
                   1288:                options.port = default_ssh_port();
1.463     djm      1289:        channel_set_af(ssh, options.address_family);
1.196     djm      1290:
1.383     djm      1291:        /* Tidy and check options */
                   1292:        if (options.host_key_alias != NULL)
                   1293:                lowercase(options.host_key_alias);
                   1294:        if (options.proxy_command != NULL &&
                   1295:            strcmp(options.proxy_command, "-") == 0 &&
                   1296:            options.proxy_use_fdpass)
                   1297:                fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1.516     markus   1298:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
                   1299:                if (options.control_persist && options.control_path != NULL) {
                   1300:                        debug("UpdateHostKeys=ask is incompatible with "
                   1301:                            "ControlPersist; disabling");
                   1302:                        options.update_hostkeys = 0;
                   1303:                } else if (sshbuf_len(command) != 0 ||
                   1304:                    options.remote_command != NULL ||
                   1305:                    options.request_tty == REQUEST_TTY_NO) {
                   1306:                        debug("UpdateHostKeys=ask is incompatible with "
                   1307:                            "remote command execution; disabling");
1.517     djm      1308:                        options.update_hostkeys = 0;
                   1309:                } else if (options.log_level < SYSLOG_LEVEL_INFO) {
                   1310:                        /* no point logging anything; user won't see it */
1.516     markus   1311:                        options.update_hostkeys = 0;
                   1312:                }
1.415     djm      1313:        }
1.430     djm      1314:        if (options.connection_attempts <= 0)
                   1315:                fatal("Invalid number of ConnectionAttempts");
                   1316:
1.482     markus   1317:        if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1.461     bluhm    1318:                fatal("Cannot execute command-line and remote command.");
                   1319:
                   1320:        /* Cannot fork to background if no command. */
1.564     djm      1321:        if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1.562     djm      1322:            options.remote_command == NULL &&
                   1323:            options.session_type != SESSION_TYPE_NONE)
1.461     bluhm    1324:                fatal("Cannot fork into background without a command "
                   1325:                    "to execute.");
                   1326:
1.31      markus   1327:        /* reinit */
1.452     dtucker  1328:        log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1.559     djm      1329:        for (j = 0; j < options.num_log_verbose; j++) {
                   1330:                if (strcasecmp(options.log_verbose[j], "none") == 0)
                   1331:                        break;
1.539     djm      1332:                log_verbose_add(options.log_verbose[j]);
1.559     djm      1333:        }
1.370     djm      1334:
                   1335:        if (options.request_tty == REQUEST_TTY_YES ||
                   1336:            options.request_tty == REQUEST_TTY_FORCE)
                   1337:                tty_flag = 1;
                   1338:
                   1339:        /* Allocate a tty by default if no command specified. */
1.482     markus   1340:        if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1.370     djm      1341:                tty_flag = options.request_tty != REQUEST_TTY_NO;
                   1342:
                   1343:        /* Force no tty */
1.447     markus   1344:        if (options.request_tty == REQUEST_TTY_NO ||
1.570     djm      1345:            (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
                   1346:            options.session_type == SESSION_TYPE_NONE)
1.370     djm      1347:                tty_flag = 0;
                   1348:        /* Do not allocate a tty if stdin is not a tty. */
1.563     djm      1349:        if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1.370     djm      1350:            options.request_tty != REQUEST_TTY_FORCE) {
                   1351:                if (tty_flag)
                   1352:                        logit("Pseudo-terminal will not be allocated because "
                   1353:                            "stdin is not a terminal.");
                   1354:                tty_flag = 0;
                   1355:        }
1.343     djm      1356:
1.466     djm      1357:        /* Set up strings used to percent_expand() arguments */
1.544     djm      1358:        cinfo = xcalloc(1, sizeof(*cinfo));
1.358     djm      1359:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1360:                fatal("gethostname: %s", strerror(errno));
1.544     djm      1361:        cinfo->thishost = xstrdup(thishost);
                   1362:        thishost[strcspn(thishost, ".")] = '\0';
                   1363:        cinfo->shorthost = xstrdup(thishost);
                   1364:        xasprintf(&cinfo->portstr, "%d", options.port);
                   1365:        xasprintf(&cinfo->uidstr, "%llu",
1.479     djm      1366:            (unsigned long long)pw->pw_uid);
1.544     djm      1367:        cinfo->keyalias = xstrdup(options.host_key_alias ?
1.583     dtucker  1368:            options.host_key_alias : options.host_arg);
1.544     djm      1369:        cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
                   1370:            cinfo->portstr, options.user);
1.583     dtucker  1371:        cinfo->host_arg = xstrdup(options.host_arg);
1.544     djm      1372:        cinfo->remhost = xstrdup(host);
                   1373:        cinfo->remuser = xstrdup(options.user);
                   1374:        cinfo->homedir = xstrdup(pw->pw_dir);
                   1375:        cinfo->locuser = xstrdup(pw->pw_name);
1.405     djm      1376:
1.466     djm      1377:        /*
                   1378:         * Expand tokens in arguments. NB. LocalCommand is expanded later,
                   1379:         * after port-forwarding is set up, so it may pick up any local
                   1380:         * tunnel interface name allocated.
                   1381:         */
1.461     bluhm    1382:        if (options.remote_command != NULL) {
                   1383:                debug3("expanding RemoteCommand: %s", options.remote_command);
                   1384:                cp = options.remote_command;
1.527     dtucker  1385:                options.remote_command = default_client_percent_expand(cp,
1.544     djm      1386:                    cinfo);
1.461     bluhm    1387:                debug3("expanded RemoteCommand: %s", options.remote_command);
                   1388:                free(cp);
1.482     markus   1389:                if ((r = sshbuf_put(command, options.remote_command,
                   1390:                    strlen(options.remote_command))) != 0)
1.540     djm      1391:                        fatal_fr(r, "buffer error");
1.304     dtucker  1392:        }
1.31      markus   1393:
1.214     djm      1394:        if (options.control_path != NULL) {
1.490     dtucker  1395:                cp = tilde_expand_filename(options.control_path, getuid());
1.378     djm      1396:                free(options.control_path);
1.528     dtucker  1397:                options.control_path = default_client_percent_dollar_expand(cp,
1.544     djm      1398:                    cinfo);
1.378     djm      1399:                free(cp);
1.214     djm      1400:        }
1.408     djm      1401:
1.522     dtucker  1402:        if (options.identity_agent != NULL) {
                   1403:                p = tilde_expand_filename(options.identity_agent, getuid());
1.544     djm      1404:                cp = default_client_percent_dollar_expand(p, cinfo);
1.522     dtucker  1405:                free(p);
                   1406:                free(options.identity_agent);
                   1407:                options.identity_agent = cp;
1.586     dtucker  1408:        }
                   1409:
                   1410:        if (options.revoked_host_keys != NULL) {
                   1411:                p = tilde_expand_filename(options.revoked_host_keys, getuid());
                   1412:                cp = default_client_percent_dollar_expand(p, cinfo);
                   1413:                free(p);
                   1414:                free(options.revoked_host_keys);
                   1415:                options.revoked_host_keys = cp;
1.522     dtucker  1416:        }
                   1417:
                   1418:        if (options.forward_agent_sock_path != NULL) {
                   1419:                p = tilde_expand_filename(options.forward_agent_sock_path,
                   1420:                    getuid());
1.544     djm      1421:                cp = default_client_percent_dollar_expand(p, cinfo);
1.522     dtucker  1422:                free(p);
                   1423:                free(options.forward_agent_sock_path);
                   1424:                options.forward_agent_sock_path = cp;
1.552     djm      1425:                if (stat(options.forward_agent_sock_path, &st) != 0) {
                   1426:                        error("Cannot forward agent socket path \"%s\": %s",
                   1427:                            options.forward_agent_sock_path, strerror(errno));
                   1428:                        if (options.exit_on_forward_failure)
                   1429:                                cleanup_exit(255);
                   1430:                }
1.532     dtucker  1431:        }
                   1432:
1.545     djm      1433:        if (options.num_system_hostfiles > 0 &&
                   1434:            strcasecmp(options.system_hostfiles[0], "none") == 0) {
                   1435:                if (options.num_system_hostfiles > 1)
                   1436:                        fatal("Invalid GlobalKnownHostsFiles: \"none\" "
                   1437:                            "appears with other entries");
                   1438:                free(options.system_hostfiles[0]);
                   1439:                options.system_hostfiles[0] = NULL;
                   1440:                options.num_system_hostfiles = 0;
                   1441:        }
                   1442:
                   1443:        if (options.num_user_hostfiles > 0 &&
                   1444:            strcasecmp(options.user_hostfiles[0], "none") == 0) {
                   1445:                if (options.num_user_hostfiles > 1)
                   1446:                        fatal("Invalid UserKnownHostsFiles: \"none\" "
                   1447:                            "appears with other entries");
                   1448:                free(options.user_hostfiles[0]);
                   1449:                options.user_hostfiles[0] = NULL;
                   1450:                options.num_user_hostfiles = 0;
                   1451:        }
1.532     dtucker  1452:        for (j = 0; j < options.num_user_hostfiles; j++) {
1.545     djm      1453:                if (options.user_hostfiles[j] == NULL)
                   1454:                        continue;
                   1455:                cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
                   1456:                p = default_client_percent_dollar_expand(cp, cinfo);
                   1457:                if (strcmp(options.user_hostfiles[j], p) != 0)
                   1458:                        debug3("expanded UserKnownHostsFile '%s' -> "
                   1459:                            "'%s'", options.user_hostfiles[j], p);
                   1460:                free(options.user_hostfiles[j]);
                   1461:                free(cp);
                   1462:                options.user_hostfiles[j] = p;
1.522     dtucker  1463:        }
                   1464:
1.527     dtucker  1465:        for (i = 0; i < options.num_local_forwards; i++) {
                   1466:                if (options.local_forwards[i].listen_path != NULL) {
                   1467:                        cp = options.local_forwards[i].listen_path;
                   1468:                        p = options.local_forwards[i].listen_path =
1.544     djm      1469:                            default_client_percent_expand(cp, cinfo);
1.527     dtucker  1470:                        if (strcmp(cp, p) != 0)
                   1471:                                debug3("expanded LocalForward listen path "
                   1472:                                    "'%s' -> '%s'", cp, p);
                   1473:                        free(cp);
                   1474:                }
                   1475:                if (options.local_forwards[i].connect_path != NULL) {
                   1476:                        cp = options.local_forwards[i].connect_path;
                   1477:                        p = options.local_forwards[i].connect_path =
1.544     djm      1478:                            default_client_percent_expand(cp, cinfo);
1.527     dtucker  1479:                        if (strcmp(cp, p) != 0)
                   1480:                                debug3("expanded LocalForward connect path "
                   1481:                                    "'%s' -> '%s'", cp, p);
                   1482:                        free(cp);
                   1483:                }
                   1484:        }
                   1485:
                   1486:        for (i = 0; i < options.num_remote_forwards; i++) {
                   1487:                if (options.remote_forwards[i].listen_path != NULL) {
                   1488:                        cp = options.remote_forwards[i].listen_path;
                   1489:                        p = options.remote_forwards[i].listen_path =
1.544     djm      1490:                            default_client_percent_expand(cp, cinfo);
1.527     dtucker  1491:                        if (strcmp(cp, p) != 0)
                   1492:                                debug3("expanded RemoteForward listen path "
                   1493:                                    "'%s' -> '%s'", cp, p);
                   1494:                        free(cp);
                   1495:                }
                   1496:                if (options.remote_forwards[i].connect_path != NULL) {
                   1497:                        cp = options.remote_forwards[i].connect_path;
                   1498:                        p = options.remote_forwards[i].connect_path =
1.544     djm      1499:                            default_client_percent_expand(cp, cinfo);
1.527     dtucker  1500:                        if (strcmp(cp, p) != 0)
                   1501:                                debug3("expanded RemoteForward connect path "
                   1502:                                    "'%s' -> '%s'", cp, p);
                   1503:                        free(cp);
                   1504:                }
                   1505:        }
                   1506:
1.408     djm      1507:        if (config_test) {
                   1508:                dump_client_config(&options, host);
                   1509:                exit(0);
1.508     djm      1510:        }
                   1511:
                   1512:        /* Expand SecurityKeyProvider if it refers to an environment variable */
                   1513:        if (options.sk_provider != NULL && *options.sk_provider == '$' &&
                   1514:            strlen(options.sk_provider) > 1) {
                   1515:                if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1.518     naddy    1516:                        debug("Authenticator provider %s did not resolve; "
1.508     djm      1517:                            "disabling", options.sk_provider);
                   1518:                        free(options.sk_provider);
                   1519:                        options.sk_provider = NULL;
                   1520:                } else {
                   1521:                        debug2("resolved SecurityKeyProvider %s => %s",
                   1522:                            options.sk_provider, cp);
                   1523:                        free(options.sk_provider);
                   1524:                        options.sk_provider = xstrdup(cp);
                   1525:                }
1.408     djm      1526:        }
1.405     djm      1527:
1.312     djm      1528:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm      1529:                fatal("No ControlPath specified for \"-O\" command");
1.447     markus   1530:        if (options.control_path != NULL) {
                   1531:                int sock;
                   1532:                if ((sock = muxclient(options.control_path)) >= 0) {
1.463     djm      1533:                        ssh_packet_set_connection(ssh, sock, sock);
1.499     djm      1534:                        ssh_packet_set_mux(ssh);
1.447     markus   1535:                        goto skip_connect;
                   1536:                }
                   1537:        }
1.401     djm      1538:
                   1539:        /*
                   1540:         * If hostname canonicalisation was not enabled, then we may not
                   1541:         * have yet resolved the hostname. Do so now.
                   1542:         */
                   1543:        if (addrs == NULL && options.proxy_command == NULL) {
1.421     djm      1544:                debug2("resolving \"%s\" port %d", host, options.port);
1.401     djm      1545:                if ((addrs = resolve_host(host, options.port, 1,
                   1546:                    cname, sizeof(cname))) == NULL)
                   1547:                        cleanup_exit(255); /* resolve_host logs the error */
                   1548:        }
1.214     djm      1549:
1.542     dtucker  1550:        if (options.connection_timeout >= INT_MAX/1000)
                   1551:                timeout_ms = INT_MAX;
                   1552:        else
                   1553:                timeout_ms = options.connection_timeout * 1000;
1.303     djm      1554:
1.77      markus   1555:        /* Open a connection to the remote host. */
1.583     dtucker  1556:        if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
                   1557:            options.port, options.connection_attempts,
1.488     dtucker  1558:            &timeout_ms, options.tcp_keep_alive) != 0)
1.257     dtucker  1559:                exit(255);
1.31      markus   1560:
1.391     djm      1561:        if (addrs != NULL)
                   1562:                freeaddrinfo(addrs);
                   1563:
1.499     djm      1564:        ssh_packet_set_timeout(ssh, options.server_alive_interval,
1.385     djm      1565:            options.server_alive_count_max);
                   1566:
1.303     djm      1567:        if (timeout_ms > 0)
                   1568:                debug3("timeout: %d ms remain after connect", timeout_ms);
                   1569:
1.33      markus   1570:        /*
1.485     dtucker  1571:         * If we successfully made the connection and we have hostbased auth
                   1572:         * enabled, load the public keys so we can later use the ssh-keysign
                   1573:         * helper to sign challenges.
1.33      markus   1574:         */
1.112     markus   1575:        sensitive_data.nkeys = 0;
                   1576:        sensitive_data.keys = NULL;
1.457     djm      1577:        if (options.hostbased_authentication) {
1.581     dtucker  1578:                int loaded = 0;
                   1579:
1.486     dtucker  1580:                sensitive_data.nkeys = 10;
1.274     deraadt  1581:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.578     jsg      1582:                    sizeof(*sensitive_data.keys));
1.483     markus   1583:
                   1584:                /* XXX check errors? */
1.486     dtucker  1585: #define L_PUBKEY(p,o) do { \
                   1586:        if ((o) >= sensitive_data.nkeys) \
1.540     djm      1587:                fatal_f("pubkey out of array bounds"); \
1.483     markus   1588:        check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1.576     djm      1589:            &(sensitive_data.keys[o]), p, "pubkey"); \
1.581     dtucker  1590:        if (sensitive_data.keys[o] != NULL) { \
1.572     djm      1591:                debug2("hostbased key %d: %s key from \"%s\"", o, \
                   1592:                    sshkey_ssh_name(sensitive_data.keys[o]), p); \
1.581     dtucker  1593:                loaded++; \
                   1594:        } \
1.486     dtucker  1595: } while (0)
                   1596: #define L_CERT(p,o) do { \
                   1597:        if ((o) >= sensitive_data.nkeys) \
1.540     djm      1598:                fatal_f("cert out of array bounds"); \
1.576     djm      1599:        check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
                   1600:            &(sensitive_data.keys[o]), p, "cert"); \
1.581     dtucker  1601:        if (sensitive_data.keys[o] != NULL) { \
1.572     djm      1602:                debug2("hostbased key %d: %s cert from \"%s\"", o, \
                   1603:                    sshkey_ssh_name(sensitive_data.keys[o]), p); \
1.581     dtucker  1604:                loaded++; \
                   1605:        } \
1.486     dtucker  1606: } while (0)
1.177     markus   1607:
1.485     dtucker  1608:                if (options.hostbased_authentication == 1) {
1.486     dtucker  1609:                        L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
                   1610:                        L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
                   1611:                        L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
                   1612:                        L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
                   1613:                        L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
                   1614:                        L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
                   1615:                        L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
                   1616:                        L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
                   1617:                        L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
                   1618:                        L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1.581     dtucker  1619:                        if (loaded == 0)
                   1620:                                debug("HostbasedAuthentication enabled but no "
                   1621:                                   "local public host keys could be loaded.");
1.173     markus   1622:                }
1.367     djm      1623:        }
1.31      markus   1624:
1.104     markus   1625:        /* load options.identity_files */
1.544     djm      1626:        load_public_identity_files(cinfo);
1.439     markus   1627:
1.476     djm      1628:        /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1.440     markus   1629:        if (options.identity_agent &&
                   1630:            strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1.439     markus   1631:                if (strcmp(options.identity_agent, "none") == 0) {
                   1632:                        unsetenv(SSH_AUTHSOCKET_ENV_NAME);
                   1633:                } else {
1.522     dtucker  1634:                        cp = options.identity_agent;
1.528     dtucker  1635:                        /* legacy (limited) format */
                   1636:                        if (cp[0] == '$' && cp[1] != '{') {
1.494     djm      1637:                                if (!valid_env_name(cp + 1)) {
                   1638:                                        fatal("Invalid IdentityAgent "
                   1639:                                            "environment variable name %s", cp);
                   1640:                                }
                   1641:                                if ((p = getenv(cp + 1)) == NULL)
                   1642:                                        unsetenv(SSH_AUTHSOCKET_ENV_NAME);
                   1643:                                else
                   1644:                                        setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
                   1645:                        } else {
                   1646:                                /* identity_agent specifies a path directly */
                   1647:                                setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
                   1648:                        }
1.510     djm      1649:                }
                   1650:        }
                   1651:
1.522     dtucker  1652:        if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1.526     djm      1653:                cp = options.forward_agent_sock_path;
1.510     djm      1654:                if (cp[0] == '$') {
                   1655:                        if (!valid_env_name(cp + 1)) {
                   1656:                                fatal("Invalid ForwardAgent environment variable name %s", cp);
                   1657:                        }
                   1658:                        if ((p = getenv(cp + 1)) != NULL)
1.566     dtucker  1659:                                forward_agent_sock_path = xstrdup(p);
1.510     djm      1660:                        else
                   1661:                                options.forward_agent = 0;
                   1662:                        free(cp);
                   1663:                } else {
                   1664:                        forward_agent_sock_path = cp;
1.439     markus   1665:                }
                   1666:        }
1.104     markus   1667:
                   1668:        /* Expand ~ in known host file names. */
1.361     djm      1669:        tilde_expand_paths(options.system_hostfiles,
                   1670:            options.num_system_hostfiles);
                   1671:        tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1.149     markus   1672:
1.512     dtucker  1673:        ssh_signal(SIGCHLD, main_sigchld_handler);
1.31      markus   1674:
1.316     djm      1675:        /* Log into the remote system.  Never returns if the login fails. */
1.497     djm      1676:        ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1.546     djm      1677:            options.port, pw, timeout_ms, cinfo);
1.31      markus   1678:
1.112     markus   1679:        /* We no longer need the private host keys.  Clear them now. */
                   1680:        if (sensitive_data.nkeys != 0) {
                   1681:                for (i = 0; i < sensitive_data.nkeys; i++) {
                   1682:                        if (sensitive_data.keys[i] != NULL) {
                   1683:                                /* Destroys contents safely */
                   1684:                                debug3("clear hostkey %d", i);
1.483     markus   1685:                                sshkey_free(sensitive_data.keys[i]);
1.112     markus   1686:                                sensitive_data.keys[i] = NULL;
                   1687:                        }
                   1688:                }
1.378     djm      1689:                free(sensitive_data.keys);
1.134     markus   1690:        }
                   1691:        for (i = 0; i < options.num_identity_files; i++) {
1.378     djm      1692:                free(options.identity_files[i]);
                   1693:                options.identity_files[i] = NULL;
1.134     markus   1694:                if (options.identity_keys[i]) {
1.483     markus   1695:                        sshkey_free(options.identity_keys[i]);
1.134     markus   1696:                        options.identity_keys[i] = NULL;
                   1697:                }
1.112     markus   1698:        }
1.426     djm      1699:        for (i = 0; i < options.num_certificate_files; i++) {
                   1700:                free(options.certificate_files[i]);
                   1701:                options.certificate_files[i] = NULL;
                   1702:        }
1.553     djm      1703:
                   1704: #ifdef ENABLE_PKCS11
                   1705:        (void)pkcs11_del_provider(options.pkcs11_provider);
                   1706: #endif
1.31      markus   1707:
1.447     markus   1708:  skip_connect:
1.544     djm      1709:        exit_status = ssh_session2(ssh, cinfo);
                   1710:        ssh_conn_info_free(cinfo);
1.499     djm      1711:        ssh_packet_close(ssh);
1.186     djm      1712:
1.312     djm      1713:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm      1714:                unlink(options.control_path);
                   1715:
1.353     djm      1716:        /* Kill ProxyCommand if it is running. */
                   1717:        ssh_kill_proxy_command();
1.186     djm      1718:
1.45      markus   1719:        return exit_status;
                   1720: }
                   1721:
1.344     djm      1722: static void
                   1723: control_persist_detach(void)
                   1724: {
                   1725:        pid_t pid;
                   1726:
1.540     djm      1727:        debug_f("backgrounding master process");
1.344     djm      1728:
1.473     djm      1729:        /*
                   1730:         * master (current process) into the background, and make the
                   1731:         * foreground process a client of the backgrounded master.
                   1732:         */
1.344     djm      1733:        switch ((pid = fork())) {
                   1734:        case -1:
1.540     djm      1735:                fatal_f("fork: %s", strerror(errno));
1.344     djm      1736:        case 0:
                   1737:                /* Child: master process continues mainloop */
1.473     djm      1738:                break;
                   1739:        default:
1.593     djm      1740:                /*
                   1741:                 * Parent: set up mux client to connect to backgrounded
                   1742:                 * master.
                   1743:                 */
1.540     djm      1744:                debug2_f("background process is %ld", (long)pid);
1.563     djm      1745:                options.stdin_null = ostdin_null_flag;
1.359     djm      1746:                options.request_tty = orequest_tty;
1.344     djm      1747:                tty_flag = otty_flag;
1.593     djm      1748:                options.fork_after_authentication = ofork_after_authentication;
1.561     djm      1749:                options.session_type = osession_type;
1.473     djm      1750:                close(muxserver_sock);
                   1751:                muxserver_sock = -1;
1.351     markus   1752:                options.control_master = SSHCTL_MASTER_NO;
1.587     dtucker  1753:                (void)muxclient(options.control_path);
1.344     djm      1754:                /* muxclient() doesn't return on success. */
1.473     djm      1755:                fatal("Failed to connect to new control master");
                   1756:        }
1.537     djm      1757:        if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1.540     djm      1758:                error_f("stdfd_devnull failed");
1.381     djm      1759:        daemon(1, 1);
1.362     djm      1760:        setproctitle("%s [mux]", options.control_path);
1.344     djm      1761: }
                   1762:
                   1763: /* Do fork() after authentication. Used by "ssh -f" */
                   1764: static void
                   1765: fork_postauth(void)
                   1766: {
                   1767:        if (need_controlpersist_detach)
                   1768:                control_persist_detach();
                   1769:        debug("forking to background");
1.564     djm      1770:        options.fork_after_authentication = 0;
1.505     deraadt  1771:        if (daemon(1, 1) == -1)
1.344     djm      1772:                fatal("daemon() failed: %.200s", strerror(errno));
1.537     djm      1773:        if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1.540     djm      1774:                error_f("stdfd_devnull failed");
1.344     djm      1775: }
                   1776:
1.523     djm      1777: static void
                   1778: forwarding_success(void)
                   1779: {
1.524     djm      1780:        if (forward_confirms_pending == -1)
                   1781:                return;
                   1782:        if (--forward_confirms_pending == 0) {
1.540     djm      1783:                debug_f("all expected forwarding replies received");
1.564     djm      1784:                if (options.fork_after_authentication)
1.523     djm      1785:                        fork_postauth();
1.524     djm      1786:        } else {
1.540     djm      1787:                debug2_f("%d expected forwarding replies remaining",
                   1788:                    forward_confirms_pending);
1.523     djm      1789:        }
                   1790: }
                   1791:
1.315     djm      1792: /* Callback for remote forward global requests */
                   1793: static void
1.463     djm      1794: ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1.315     djm      1795: {
1.406     millert  1796:        struct Forward *rfwd = (struct Forward *)ctxt;
1.499     djm      1797:        u_int port;
                   1798:        int r;
1.315     djm      1799:
1.324     djm      1800:        /* XXX verbose() on failure? */
1.404     markus   1801:        debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1.315     djm      1802:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1.406     millert  1803:            rfwd->listen_path ? rfwd->listen_path :
                   1804:            rfwd->listen_host ? rfwd->listen_host : "",
                   1805:            (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
                   1806:            rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
                   1807:            rfwd->connect_host, rfwd->connect_port);
                   1808:        if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1.366     markus   1809:                if (type == SSH2_MSG_REQUEST_SUCCESS) {
1.499     djm      1810:                        if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1.540     djm      1811:                                fatal_fr(r, "parse packet");
1.499     djm      1812:                        if (port > 65535) {
                   1813:                                error("Invalid allocated port %u for remote "
                   1814:                                    "forward to %s:%d", port,
                   1815:                                    rfwd->connect_host, rfwd->connect_port);
                   1816:                                /* Ensure failure processing runs below */
                   1817:                                type = SSH2_MSG_REQUEST_FAILURE;
                   1818:                                channel_update_permission(ssh,
                   1819:                                    rfwd->handle, -1);
                   1820:                        } else {
                   1821:                                rfwd->allocated_port = (int)port;
                   1822:                                logit("Allocated port %u for remote "
                   1823:                                    "forward to %s:%d",
1.569     dtucker  1824:                                    rfwd->allocated_port, rfwd->connect_path ?
                   1825:                                    rfwd->connect_path : rfwd->connect_host,
1.499     djm      1826:                                    rfwd->connect_port);
                   1827:                                channel_update_permission(ssh,
                   1828:                                    rfwd->handle, rfwd->allocated_port);
                   1829:                        }
1.366     markus   1830:                } else {
1.480     djm      1831:                        channel_update_permission(ssh, rfwd->handle, -1);
1.366     markus   1832:                }
1.324     djm      1833:        }
1.468     djm      1834:
1.315     djm      1835:        if (type == SSH2_MSG_REQUEST_FAILURE) {
1.406     millert  1836:                if (options.exit_on_forward_failure) {
                   1837:                        if (rfwd->listen_path != NULL)
                   1838:                                fatal("Error: remote port forwarding failed "
                   1839:                                    "for listen path %s", rfwd->listen_path);
                   1840:                        else
                   1841:                                fatal("Error: remote port forwarding failed "
                   1842:                                    "for listen port %d", rfwd->listen_port);
                   1843:                } else {
                   1844:                        if (rfwd->listen_path != NULL)
                   1845:                                logit("Warning: remote port forwarding failed "
                   1846:                                    "for listen path %s", rfwd->listen_path);
                   1847:                        else
                   1848:                                logit("Warning: remote port forwarding failed "
                   1849:                                    "for listen port %d", rfwd->listen_port);
                   1850:                }
1.315     djm      1851:        }
1.523     djm      1852:        forwarding_success();
1.315     djm      1853: }
                   1854:
1.126     itojun   1855: static void
1.582     djm      1856: client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
1.331     dtucker  1857: {
                   1858:        debug("stdio forwarding: done");
                   1859:        cleanup_exit(0);
                   1860: }
                   1861:
1.368     djm      1862: static void
1.463     djm      1863: ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1.407     djm      1864: {
                   1865:        if (!success)
                   1866:                fatal("stdio forwarding failed");
                   1867: }
                   1868:
                   1869: static void
1.523     djm      1870: ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
                   1871: {
                   1872:        if (!success) {
                   1873:                error("Tunnel forwarding failed");
                   1874:                if (options.exit_on_forward_failure)
                   1875:                        cleanup_exit(255);
                   1876:        }
                   1877:
1.540     djm      1878:        debug_f("tunnel forward established, id=%d", id);
1.523     djm      1879:        forwarding_success();
                   1880: }
                   1881:
                   1882: static void
1.463     djm      1883: ssh_init_stdio_forwarding(struct ssh *ssh)
1.331     dtucker  1884: {
                   1885:        Channel *c;
1.332     djm      1886:        int in, out;
1.331     dtucker  1887:
1.441     dtucker  1888:        if (options.stdio_forward_host == NULL)
1.368     djm      1889:                return;
                   1890:
1.540     djm      1891:        debug3_f("%s:%d", options.stdio_forward_host,
1.441     dtucker  1892:            options.stdio_forward_port);
1.332     djm      1893:
1.505     deraadt  1894:        if ((in = dup(STDIN_FILENO)) == -1 ||
                   1895:            (out = dup(STDOUT_FILENO)) == -1)
1.557     djm      1896:                fatal_f("dup() in/out failed");
1.463     djm      1897:        if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1.557     djm      1898:            options.stdio_forward_port, in, out,
                   1899:            CHANNEL_NONBLOCK_STDIO)) == NULL)
1.540     djm      1900:                fatal_f("channel_connect_stdio_fwd failed");
1.463     djm      1901:        channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
                   1902:        channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1.331     dtucker  1903: }
                   1904:
                   1905: static void
1.551     markus   1906: ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
                   1907:     u_int num_opens)
                   1908: {
                   1909:        u_int i;
                   1910:        int port;
1.573     dtucker  1911:        char *addr, *arg, *oarg;
1.551     markus   1912:        int where = FORWARD_LOCAL;
                   1913:
                   1914:        channel_clear_permission(ssh, FORWARD_ADM, where);
                   1915:        if (num_opens == 0)
                   1916:                return; /* permit any */
                   1917:
                   1918:        /* handle keywords: "any" / "none" */
                   1919:        if (num_opens == 1 && strcmp(opens[0], "any") == 0)
                   1920:                return;
                   1921:        if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
                   1922:                channel_disable_admin(ssh, where);
                   1923:                return;
                   1924:        }
                   1925:        /* Otherwise treat it as a list of permitted host:port */
                   1926:        for (i = 0; i < num_opens; i++) {
                   1927:                oarg = arg = xstrdup(opens[i]);
1.573     dtucker  1928:                addr = hpdelim(&arg);
                   1929:                if (addr == NULL)
1.551     markus   1930:                        fatal_f("missing host in %s", what);
                   1931:                addr = cleanhostname(addr);
                   1932:                if (arg == NULL || ((port = permitopen_port(arg)) < 0))
                   1933:                        fatal_f("bad port number in %s", what);
                   1934:                /* Send it to channels layer */
                   1935:                channel_add_permission(ssh, FORWARD_ADM,
                   1936:                    where, addr, port);
                   1937:                free(oarg);
                   1938:        }
                   1939: }
                   1940:
                   1941: static void
1.466     djm      1942: ssh_init_forwarding(struct ssh *ssh, char **ifname)
1.70      markus   1943: {
1.86      markus   1944:        int success = 0;
1.70      markus   1945:        int i;
1.551     markus   1946:
                   1947:        ssh_init_forward_permissions(ssh, "permitremoteopen",
                   1948:            options.permitted_remote_opens,
                   1949:            options.num_permitted_remote_opens);
1.331     dtucker  1950:
1.524     djm      1951:        if (options.exit_on_forward_failure)
                   1952:                forward_confirms_pending = 0; /* track pending requests */
1.70      markus   1953:        /* Initiate local TCP/IP port forwardings. */
                   1954:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm      1955:                debug("Local connections to %.200s:%d forwarded to remote "
                   1956:                    "address %.200s:%d",
1.406     millert  1957:                    (options.local_forwards[i].listen_path != NULL) ?
                   1958:                    options.local_forwards[i].listen_path :
1.234     deraadt  1959:                    (options.local_forwards[i].listen_host == NULL) ?
1.406     millert  1960:                    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm      1961:                    options.local_forwards[i].listen_host,
                   1962:                    options.local_forwards[i].listen_port,
1.406     millert  1963:                    (options.local_forwards[i].connect_path != NULL) ?
                   1964:                    options.local_forwards[i].connect_path :
1.232     djm      1965:                    options.local_forwards[i].connect_host,
                   1966:                    options.local_forwards[i].connect_port);
1.463     djm      1967:                success += channel_setup_local_fwd_listener(ssh,
1.406     millert  1968:                    &options.local_forwards[i], &options.fwd_opts);
1.70      markus   1969:        }
1.283     markus   1970:        if (i > 0 && success != i && options.exit_on_forward_failure)
                   1971:                fatal("Could not request local forwarding.");
1.86      markus   1972:        if (i > 0 && success == 0)
                   1973:                error("Could not request local forwarding.");
1.70      markus   1974:
                   1975:        /* Initiate remote TCP/IP port forwardings. */
                   1976:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm      1977:                debug("Remote connections from %.200s:%d forwarded to "
                   1978:                    "local address %.200s:%d",
1.406     millert  1979:                    (options.remote_forwards[i].listen_path != NULL) ?
                   1980:                    options.remote_forwards[i].listen_path :
1.248     djm      1981:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm      1982:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm      1983:                    options.remote_forwards[i].listen_port,
1.406     millert  1984:                    (options.remote_forwards[i].connect_path != NULL) ?
                   1985:                    options.remote_forwards[i].connect_path :
1.232     djm      1986:                    options.remote_forwards[i].connect_host,
                   1987:                    options.remote_forwards[i].connect_port);
1.523     djm      1988:                if ((options.remote_forwards[i].handle =
1.463     djm      1989:                    channel_request_remote_forwarding(ssh,
1.523     djm      1990:                    &options.remote_forwards[i])) >= 0) {
1.463     djm      1991:                        client_register_global_confirm(
                   1992:                            ssh_confirm_remote_forward,
1.366     markus   1993:                            &options.remote_forwards[i]);
1.523     djm      1994:                        forward_confirms_pending++;
                   1995:                } else if (options.exit_on_forward_failure)
                   1996:                        fatal("Could not request remote forwarding.");
                   1997:                else
                   1998:                        logit("Warning: Could not request remote forwarding.");
1.70      markus   1999:        }
1.301     djm      2000:
                   2001:        /* Initiate tunnel forwarding. */
                   2002:        if (options.tun_open != SSH_TUNMODE_NO) {
1.466     djm      2003:                if ((*ifname = client_request_tun_fwd(ssh,
                   2004:                    options.tun_open, options.tun_local,
1.523     djm      2005:                    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
                   2006:                        forward_confirms_pending++;
                   2007:                else if (options.exit_on_forward_failure)
                   2008:                        fatal("Could not request tunnel forwarding.");
                   2009:                else
                   2010:                        error("Could not request tunnel forwarding.");
1.524     djm      2011:        }
                   2012:        if (forward_confirms_pending > 0) {
1.540     djm      2013:                debug_f("expecting replies for %d forwards",
1.524     djm      2014:                    forward_confirms_pending);
1.468     djm      2015:        }
1.70      markus   2016: }
                   2017:
1.126     itojun   2018: static void
1.70      markus   2019: check_agent_present(void)
                   2020: {
1.412     djm      2021:        int r;
                   2022:
1.70      markus   2023:        if (options.forward_agent) {
1.254     djm      2024:                /* Clear agent forwarding if we don't have an agent. */
1.412     djm      2025:                if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1.70      markus   2026:                        options.forward_agent = 0;
1.412     djm      2027:                        if (r != SSH_ERR_AGENT_NOT_PRESENT)
1.540     djm      2028:                                debug_r(r, "ssh_get_authentication_socket");
1.412     djm      2029:                }
1.70      markus   2030:        }
                   2031: }
                   2032:
1.214     djm      2033: static void
1.463     djm      2034: ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1.214     djm      2035: {
1.215     djm      2036:        extern char **environ;
1.558     djm      2037:        const char *display, *term;
1.499     djm      2038:        int r, interactive = tty_flag;
1.433     djm      2039:        char *proto = NULL, *data = NULL;
1.337     djm      2040:
                   2041:        if (!success)
1.580     djm      2042:                return; /* No need for error message, channels code sends one */
1.215     djm      2043:
1.248     djm      2044:        display = getenv("DISPLAY");
1.417     djm      2045:        if (display == NULL && options.forward_x11)
                   2046:                debug("X11 forwarding requested but DISPLAY not set");
1.463     djm      2047:        if (options.forward_x11 && client_x11_get_proto(ssh, display,
1.433     djm      2048:            options.xauth_location, options.forward_x11_trusted,
                   2049:            options.forward_x11_timeout, &proto, &data) == 0) {
1.50      markus   2050:                /* Request forwarding with authentication spoofing. */
1.316     djm      2051:                debug("Requesting X11 forwarding with authentication "
                   2052:                    "spoofing.");
1.463     djm      2053:                x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1.363     djm      2054:                    data, 1);
1.463     djm      2055:                client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1.363     djm      2056:                /* XXX exit_on_forward_failure */
1.80      markus   2057:                interactive = 1;
1.50      markus   2058:        }
                   2059:
1.70      markus   2060:        check_agent_present();
                   2061:        if (options.forward_agent) {
                   2062:                debug("Requesting authentication agent forwarding.");
1.463     djm      2063:                channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1.499     djm      2064:                if ((r = sshpkt_send(ssh)) != 0)
1.540     djm      2065:                        fatal_fr(r, "send packet");
1.212     djm      2066:        }
1.369     dtucker  2067:
                   2068:        /* Tell the packet module whether this is an interactive session. */
1.499     djm      2069:        ssh_packet_set_interactive(ssh, interactive,
1.369     dtucker  2070:            options.ip_qos_interactive, options.ip_qos_bulk);
1.212     djm      2071:
1.558     djm      2072:        if ((term = lookup_env_in_list("TERM", options.setenv,
                   2073:            options.num_setenv)) == NULL || *term == '\0')
                   2074:                term = getenv("TERM");
1.562     djm      2075:        client_session2_setup(ssh, id, tty_flag,
                   2076:            options.session_type == SESSION_TYPE_SUBSYSTEM, term,
1.482     markus   2077:            NULL, fileno(stdin), command, environ);
1.45      markus   2078: }
                   2079:
1.143     markus   2080: /* open new channel for a session */
1.126     itojun   2081: static int
1.463     djm      2082: ssh_session2_open(struct ssh *ssh)
1.45      markus   2083: {
1.118     markus   2084:        Channel *c;
                   2085:        int window, packetmax, in, out, err;
1.60      markus   2086:
1.563     djm      2087:        if (options.stdin_null) {
1.93      itojun   2088:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   2089:        } else {
                   2090:                in = dup(STDIN_FILENO);
                   2091:        }
1.60      markus   2092:        out = dup(STDOUT_FILENO);
                   2093:        err = dup(STDERR_FILENO);
1.45      markus   2094:
1.505     deraadt  2095:        if (in == -1 || out == -1 || err == -1)
1.62      markus   2096:                fatal("dup() in/out/err failed");
1.45      markus   2097:
1.65      markus   2098:        window = CHAN_SES_WINDOW_DEFAULT;
                   2099:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   2100:        if (tty_flag) {
                   2101:                window >>= 1;
                   2102:                packetmax >>= 1;
1.45      markus   2103:        }
1.463     djm      2104:        c = channel_new(ssh,
1.45      markus   2105:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   2106:            window, packetmax, CHAN_EXTENDED_WRITE,
1.557     djm      2107:            "client-session", CHANNEL_NONBLOCK_STDIO);
1.45      markus   2108:
1.540     djm      2109:        debug3_f("channel_new: %d", c->self);
1.106     markus   2110:
1.463     djm      2111:        channel_send_open(ssh, c->self);
1.560     djm      2112:        if (options.session_type != SESSION_TYPE_NONE)
1.463     djm      2113:                channel_register_open_confirm(ssh, c->self,
1.310     djm      2114:                    ssh_session2_setup, NULL);
1.106     markus   2115:
1.118     markus   2116:        return c->self;
1.106     markus   2117: }
                   2118:
1.126     itojun   2119: static int
1.544     djm      2120: ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
1.106     markus   2121: {
1.594   ! djm      2122:        int r, interactive, id = -1;
1.466     djm      2123:        char *cp, *tun_fwd_ifname = NULL;
1.106     markus   2124:
                   2125:        /* XXX should be pre-session */
1.368     djm      2126:        if (!options.control_persist)
1.463     djm      2127:                ssh_init_stdio_forwarding(ssh);
1.466     djm      2128:
                   2129:        ssh_init_forwarding(ssh, &tun_fwd_ifname);
                   2130:
                   2131:        if (options.local_command != NULL) {
                   2132:                debug3("expanding LocalCommand: %s", options.local_command);
                   2133:                cp = options.local_command;
                   2134:                options.local_command = percent_expand(cp,
1.546     djm      2135:                    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
1.466     djm      2136:                    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
                   2137:                    (char *)NULL);
                   2138:                debug3("expanded LocalCommand: %s", options.local_command);
                   2139:                free(cp);
                   2140:        }
1.106     markus   2141:
1.344     djm      2142:        /* Start listening for multiplex clients */
1.499     djm      2143:        if (!ssh_packet_get_mux(ssh))
1.463     djm      2144:                muxserver_listen(ssh);
1.344     djm      2145:
1.473     djm      2146:        /*
1.368     djm      2147:         * If we are in control persist mode and have a working mux listen
                   2148:         * socket, then prepare to background ourselves and have a foreground
1.531     djm      2149:         * client attach as a control client.
1.368     djm      2150:         * NB. we must save copies of the flags that we override for
1.531     djm      2151:         * the backgrounding, since we defer attachment of the client until
1.344     djm      2152:         * after the connection is fully established (in particular,
                   2153:         * async rfwd replies have been received for ExitOnForwardFailure).
                   2154:         */
1.473     djm      2155:        if (options.control_persist && muxserver_sock != -1) {
1.563     djm      2156:                ostdin_null_flag = options.stdin_null;
1.560     djm      2157:                osession_type = options.session_type;
1.359     djm      2158:                orequest_tty = options.request_tty;
1.344     djm      2159:                otty_flag = tty_flag;
1.593     djm      2160:                ofork_after_authentication = options.fork_after_authentication;
1.563     djm      2161:                options.stdin_null = 1;
1.560     djm      2162:                options.session_type = SESSION_TYPE_NONE;
1.473     djm      2163:                tty_flag = 0;
1.593     djm      2164:                if ((osession_type != SESSION_TYPE_NONE ||
1.562     djm      2165:                    options.stdio_forward_host != NULL))
1.344     djm      2166:                        need_controlpersist_detach = 1;
1.564     djm      2167:                options.fork_after_authentication = 1;
1.473     djm      2168:        }
1.368     djm      2169:        /*
                   2170:         * ControlPersist mux listen socket setup failed, attempt the
                   2171:         * stdio forward setup that we skipped earlier.
                   2172:         */
                   2173:        if (options.control_persist && muxserver_sock == -1)
1.463     djm      2174:                ssh_init_stdio_forwarding(ssh);
1.344     djm      2175:
1.560     djm      2176:        if (options.session_type != SESSION_TYPE_NONE)
1.463     djm      2177:                id = ssh_session2_open(ssh);
1.379     djm      2178:        else {
1.594   ! djm      2179:                interactive = options.control_master == SSHCTL_MASTER_NO;
        !          2180:                /* ControlPersist may have clobbered ControlMaster, so check */
        !          2181:                if (need_controlpersist_detach)
        !          2182:                        interactive = otty_flag != 0;
        !          2183:                ssh_packet_set_interactive(ssh, interactive,
1.379     djm      2184:                    options.ip_qos_interactive, options.ip_qos_bulk);
                   2185:        }
1.314     djm      2186:
                   2187:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   2188:        if (options.control_master == SSHCTL_MASTER_NO &&
1.549     djm      2189:            (ssh->compat & SSH_NEW_OPENSSH)) {
1.314     djm      2190:                debug("Requesting no-more-sessions@openssh.com");
1.499     djm      2191:                if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                   2192:                    (r = sshpkt_put_cstring(ssh,
                   2193:                    "no-more-sessions@openssh.com")) != 0 ||
                   2194:                    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
                   2195:                    (r = sshpkt_send(ssh)) != 0)
1.540     djm      2196:                        fatal_fr(r, "send packet");
1.314     djm      2197:        }
1.255     reyk     2198:
                   2199:        /* Execute a local command */
                   2200:        if (options.local_command != NULL &&
                   2201:            options.permit_local_command)
                   2202:                ssh_local_cmd(options.local_command);
1.467     djm      2203:
                   2204:        /*
                   2205:         * stdout is now owned by the session channel; clobber it here
                   2206:         * so future channel closes are propagated to the local fd.
                   2207:         * NB. this can only happen after LocalCommand has completed,
                   2208:         * as it may want to write to stdout.
                   2209:         */
1.537     djm      2210:        if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
1.540     djm      2211:                error_f("stdfd_devnull failed");
1.301     djm      2212:
1.342     djm      2213:        /*
                   2214:         * If requested and we are not interested in replies to remote
                   2215:         * forwarding requests, then let ssh continue in the background.
                   2216:         */
1.564     djm      2217:        if (options.fork_after_authentication) {
1.344     djm      2218:                if (options.exit_on_forward_failure &&
                   2219:                    options.num_remote_forwards > 0) {
                   2220:                        debug("deferring postauth fork until remote forward "
                   2221:                            "confirmation received");
                   2222:                } else
                   2223:                        fork_postauth();
1.318     djm      2224:        }
1.31      markus   2225:
1.463     djm      2226:        return client_loop(ssh, tty_flag, tty_flag ?
1.119     stevesk  2227:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   2228: }
                   2229:
1.426     djm      2230: /* Loads all IdentityFile and CertificateFile keys */
1.126     itojun   2231: static void
1.544     djm      2232: load_public_identity_files(const struct ssh_conn_info *cinfo)
1.104     markus   2233: {
1.466     djm      2234:        char *filename, *cp;
1.460     markus   2235:        struct sshkey *public;
1.426     djm      2236:        int i;
                   2237:        u_int n_ids, n_certs;
1.335     djm      2238:        char *identity_files[SSH_MAX_IDENTITY_FILES];
1.460     markus   2239:        struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
1.484     djm      2240:        int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
1.426     djm      2241:        char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
                   2242:        struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1.484     djm      2243:        int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
1.333     markus   2244: #ifdef ENABLE_PKCS11
1.514     djm      2245:        struct sshkey **keys = NULL;
                   2246:        char **comments = NULL;
1.333     markus   2247:        int nkeys;
1.335     djm      2248: #endif /* PKCS11 */
1.104     markus   2249:
1.426     djm      2250:        n_ids = n_certs = 0;
1.398     tedu     2251:        memset(identity_files, 0, sizeof(identity_files));
                   2252:        memset(identity_keys, 0, sizeof(identity_keys));
1.484     djm      2253:        memset(identity_file_userprovided, 0,
                   2254:            sizeof(identity_file_userprovided));
1.426     djm      2255:        memset(certificate_files, 0, sizeof(certificate_files));
                   2256:        memset(certificates, 0, sizeof(certificates));
1.484     djm      2257:        memset(certificate_file_userprovided, 0,
                   2258:            sizeof(certificate_file_userprovided));
1.335     djm      2259:
                   2260: #ifdef ENABLE_PKCS11
1.333     markus   2261:        if (options.pkcs11_provider != NULL &&
1.167     markus   2262:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   2263:            (pkcs11_init(!options.batch_mode) == 0) &&
                   2264:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1.514     djm      2265:            &keys, &comments)) > 0) {
1.333     markus   2266:                for (i = 0; i < nkeys; i++) {
1.335     djm      2267:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1.483     markus   2268:                                sshkey_free(keys[i]);
1.514     djm      2269:                                free(comments[i]);
1.335     djm      2270:                                continue;
                   2271:                        }
                   2272:                        identity_keys[n_ids] = keys[i];
1.514     djm      2273:                        identity_files[n_ids] = comments[i]; /* transferred */
1.335     djm      2274:                        n_ids++;
1.167     markus   2275:                }
1.378     djm      2276:                free(keys);
1.514     djm      2277:                free(comments);
1.127     markus   2278:        }
1.333     markus   2279: #endif /* ENABLE_PKCS11 */
1.335     djm      2280:        for (i = 0; i < options.num_identity_files; i++) {
1.373     djm      2281:                if (n_ids >= SSH_MAX_IDENTITY_FILES ||
                   2282:                    strcasecmp(options.identity_files[i], "none") == 0) {
1.378     djm      2283:                        free(options.identity_files[i]);
1.426     djm      2284:                        options.identity_files[i] = NULL;
1.335     djm      2285:                        continue;
                   2286:                }
1.490     dtucker  2287:                cp = tilde_expand_filename(options.identity_files[i], getuid());
1.544     djm      2288:                filename = default_client_percent_dollar_expand(cp, cinfo);
1.378     djm      2289:                free(cp);
1.483     markus   2290:                check_load(sshkey_load_public(filename, &public, NULL),
1.576     djm      2291:                    &public, filename, "pubkey");
1.131     millert  2292:                debug("identity file %s type %d", filename,
                   2293:                    public ? public->type : -1);
1.378     djm      2294:                free(options.identity_files[i]);
1.335     djm      2295:                identity_files[n_ids] = filename;
                   2296:                identity_keys[n_ids] = public;
1.484     djm      2297:                identity_file_userprovided[n_ids] =
                   2298:                    options.identity_file_userprovided[i];
1.335     djm      2299:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
                   2300:                        continue;
                   2301:
1.426     djm      2302:                /*
                   2303:                 * If no certificates have been explicitly listed then try
                   2304:                 * to add the default certificate variant too.
                   2305:                 */
                   2306:                if (options.num_certificate_files != 0)
                   2307:                        continue;
1.335     djm      2308:                xasprintf(&cp, "%s-cert", filename);
1.483     markus   2309:                check_load(sshkey_load_public(cp, &public, NULL),
1.576     djm      2310:                    &public, filename, "pubkey");
1.335     djm      2311:                debug("identity file %s type %d", cp,
                   2312:                    public ? public->type : -1);
                   2313:                if (public == NULL) {
1.378     djm      2314:                        free(cp);
1.335     djm      2315:                        continue;
                   2316:                }
1.483     markus   2317:                if (!sshkey_is_cert(public)) {
1.540     djm      2318:                        debug_f("key %s type %s is not a certificate",
                   2319:                            cp, sshkey_type(public));
1.483     markus   2320:                        sshkey_free(public);
1.378     djm      2321:                        free(cp);
1.335     djm      2322:                        continue;
                   2323:                }
1.448     djm      2324:                /* NB. leave filename pointing to private key */
                   2325:                identity_files[n_ids] = xstrdup(filename);
1.335     djm      2326:                identity_keys[n_ids] = public;
1.484     djm      2327:                identity_file_userprovided[n_ids] =
                   2328:                    options.identity_file_userprovided[i];
1.335     djm      2329:                n_ids++;
                   2330:        }
1.426     djm      2331:
                   2332:        if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
1.540     djm      2333:                fatal_f("too many certificates");
1.426     djm      2334:        for (i = 0; i < options.num_certificate_files; i++) {
                   2335:                cp = tilde_expand_filename(options.certificate_files[i],
1.490     dtucker  2336:                    getuid());
1.544     djm      2337:                filename = default_client_percent_dollar_expand(cp, cinfo);
1.426     djm      2338:                free(cp);
                   2339:
1.483     markus   2340:                check_load(sshkey_load_public(filename, &public, NULL),
1.576     djm      2341:                    &public, filename, "certificate");
1.426     djm      2342:                debug("certificate file %s type %d", filename,
                   2343:                    public ? public->type : -1);
                   2344:                free(options.certificate_files[i]);
                   2345:                options.certificate_files[i] = NULL;
                   2346:                if (public == NULL) {
                   2347:                        free(filename);
                   2348:                        continue;
                   2349:                }
1.483     markus   2350:                if (!sshkey_is_cert(public)) {
1.540     djm      2351:                        debug_f("key %s type %s is not a certificate",
                   2352:                            filename, sshkey_type(public));
1.483     markus   2353:                        sshkey_free(public);
1.426     djm      2354:                        free(filename);
                   2355:                        continue;
                   2356:                }
                   2357:                certificate_files[n_certs] = filename;
                   2358:                certificates[n_certs] = public;
1.484     djm      2359:                certificate_file_userprovided[n_certs] =
                   2360:                    options.certificate_file_userprovided[i];
1.426     djm      2361:                ++n_certs;
                   2362:        }
                   2363:
1.335     djm      2364:        options.num_identity_files = n_ids;
                   2365:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
                   2366:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1.484     djm      2367:        memcpy(options.identity_file_userprovided,
                   2368:            identity_file_userprovided, sizeof(identity_file_userprovided));
1.426     djm      2369:
                   2370:        options.num_certificate_files = n_certs;
                   2371:        memcpy(options.certificate_files,
                   2372:            certificate_files, sizeof(certificate_files));
                   2373:        memcpy(options.certificates, certificates, sizeof(certificates));
1.484     djm      2374:        memcpy(options.certificate_file_userprovided,
                   2375:            certificate_file_userprovided,
                   2376:            sizeof(certificate_file_userprovided));
1.214     djm      2377: }
1.352     djm      2378:
                   2379: static void
                   2380: main_sigchld_handler(int sig)
                   2381: {
                   2382:        int save_errno = errno;
                   2383:        pid_t pid;
                   2384:        int status;
                   2385:
                   2386:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1.505     deraadt  2387:            (pid == -1 && errno == EINTR))
1.352     djm      2388:                ;
                   2389:        errno = save_errno;
                   2390: }