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

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