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

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