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

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