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

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