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

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