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

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