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

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