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

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