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

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