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

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