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

1.502   ! otto        1: /* $OpenBSD: ssh.c,v 1.501 2019/04/23 11:56:41 dtucker Exp $ */
1.1       deraadt     2: /*
1.32      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Ssh client program.  This program can be used to log into a remote machine.
                      7:  * The software supports strong authentication, encryption, and forwarding
                      8:  * of X11, TCP/IP, and authentication connections.
                      9:  *
1.64      deraadt    10:  * As far as I am concerned, the code I have written for this software
                     11:  * can be used freely for any purpose.  Any derived versions of this
                     12:  * software must be clearly marked as such, and if the derived work is
                     13:  * incompatible with the protocol description in the RFC file, it must be
                     14:  * called by a name other than "ssh" or "Secure Shell".
                     15:  *
                     16:  * Copyright (c) 1999 Niels Provos.  All rights reserved.
1.202     markus     17:  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
1.64      deraadt    18:  *
                     19:  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
                     20:  * in Canada (German citizen).
                     21:  *
                     22:  * Redistribution and use in source and binary forms, with or without
                     23:  * modification, are permitted provided that the following conditions
                     24:  * are met:
                     25:  * 1. Redistributions of source code must retain the above copyright
                     26:  *    notice, this list of conditions and the following disclaimer.
                     27:  * 2. Redistributions in binary form must reproduce the above copyright
                     28:  *    notice, this list of conditions and the following disclaimer in the
                     29:  *    documentation and/or other materials provided with the distribution.
                     30:  *
                     31:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     32:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     33:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     34:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     35:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     36:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     37:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     38:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     39:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     40:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.32      deraadt    41:  */
1.1       deraadt    42:
1.293     deraadt    43: #include <sys/types.h>
1.312     djm        44: #include <sys/ioctl.h>
                     45: #include <sys/queue.h>
1.259     stevesk    46: #include <sys/resource.h>
1.280     stevesk    47: #include <sys/socket.h>
1.264     stevesk    48: #include <sys/stat.h>
1.312     djm        49: #include <sys/time.h>
1.352     djm        50: #include <sys/wait.h>
1.258     stevesk    51:
1.265     stevesk    52: #include <ctype.h>
1.285     stevesk    53: #include <errno.h>
1.281     stevesk    54: #include <fcntl.h>
1.286     stevesk    55: #include <netdb.h>
1.258     stevesk    56: #include <paths.h>
1.279     stevesk    57: #include <pwd.h>
1.263     stevesk    58: #include <signal.h>
1.287     stevesk    59: #include <stddef.h>
1.291     stevesk    60: #include <stdio.h>
1.290     stevesk    61: #include <stdlib.h>
1.289     stevesk    62: #include <string.h>
1.288     stevesk    63: #include <unistd.h>
1.414     deraadt    64: #include <limits.h>
1.445     djm        65: #include <locale.h>
1.49      markus     66:
1.402     markus     67: #ifdef WITH_OPENSSL
1.49      markus     68: #include <openssl/evp.h>
1.72      markus     69: #include <openssl/err.h>
1.402     markus     70: #endif
1.1       deraadt    71:
1.293     deraadt    72: #include "xmalloc.h"
1.84      markus     73: #include "ssh.h"
                     74: #include "ssh2.h"
1.341     djm        75: #include "canohost.h"
1.84      markus     76: #include "compat.h"
                     77: #include "cipher.h"
1.405     djm        78: #include "digest.h"
1.1       deraadt    79: #include "packet.h"
1.482     markus     80: #include "sshbuf.h"
1.123     markus     81: #include "channels.h"
1.483     markus     82: #include "sshkey.h"
1.58      markus     83: #include "authfd.h"
1.49      markus     84: #include "authfile.h"
1.83      markus     85: #include "pathnames.h"
1.214     djm        86: #include "dispatch.h"
1.81      markus     87: #include "clientloop.h"
1.84      markus     88: #include "log.h"
1.406     millert    89: #include "misc.h"
1.84      markus     90: #include "readconf.h"
                     91: #include "sshconnect.h"
1.95      markus     92: #include "kex.h"
                     93: #include "mac.h"
1.213     deraadt    94: #include "sshpty.h"
1.212     djm        95: #include "match.h"
1.214     djm        96: #include "msg.h"
1.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
                    149:  * command line, or the HostName specified for the user-supplied name in a
                    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':
                    767:                        if (options.jump_host != NULL)
                    768:                                fatal("Only a single -J option permitted");
                    769:                        if (options.proxy_command != NULL)
                    770:                                fatal("Cannot specify -J with ProxyCommand");
                    771:                        if (parse_jump(optarg, &options, 1) == -1)
                    772:                                fatal("Invalid -J argument");
                    773:                        options.proxy_command = xstrdup("none");
                    774:                        break;
1.31      markus    775:                case 't':
1.359     djm       776:                        if (options.request_tty == REQUEST_TTY_YES)
                    777:                                options.request_tty = REQUEST_TTY_FORCE;
                    778:                        else
                    779:                                options.request_tty = REQUEST_TTY_YES;
1.31      markus    780:                        break;
                    781:                case 'v':
1.197     markus    782:                        if (debug_flag == 0) {
1.66      markus    783:                                debug_flag = 1;
                    784:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    785:                        } else {
1.443     djm       786:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
                    787:                                        debug_flag++;
1.197     markus    788:                                        options.log_level++;
1.443     djm       789:                                }
1.197     markus    790:                        }
1.375     dtucker   791:                        break;
1.31      markus    792:                case 'V':
1.209     markus    793:                        fprintf(stderr, "%s, %s\n",
1.402     markus    794:                            SSH_VERSION,
                    795: #ifdef WITH_OPENSSL
1.495     djm       796:                            OpenSSL_version(OPENSSL_VERSION)
1.402     markus    797: #else
                    798:                            "without OpenSSL"
                    799: #endif
                    800:                        );
1.31      markus    801:                        if (opt == 'V')
                    802:                                exit(0);
                    803:                        break;
1.255     reyk      804:                case 'w':
1.256     reyk      805:                        if (options.tun_open == -1)
                    806:                                options.tun_open = SSH_TUNMODE_DEFAULT;
1.255     reyk      807:                        options.tun_local = a2tun(optarg, &options.tun_remote);
1.256     reyk      808:                        if (options.tun_local == SSH_TUNID_ERR) {
1.316     djm       809:                                fprintf(stderr,
                    810:                                    "Bad tun device '%s'\n", optarg);
1.257     dtucker   811:                                exit(255);
1.255     reyk      812:                        }
                    813:                        break;
1.331     dtucker   814:                case 'W':
1.441     dtucker   815:                        if (options.stdio_forward_host != NULL)
1.332     djm       816:                                fatal("stdio forward already specified");
                    817:                        if (muxclient_command != 0)
                    818:                                fatal("Cannot specify stdio forward with -O");
1.331     dtucker   819:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.441     dtucker   820:                                options.stdio_forward_host = fwd.listen_host;
                    821:                                options.stdio_forward_port = fwd.listen_port;
1.378     djm       822:                                free(fwd.connect_host);
1.331     dtucker   823:                        } else {
                    824:                                fprintf(stderr,
                    825:                                    "Bad stdio forwarding specification '%s'\n",
                    826:                                    optarg);
                    827:                                exit(255);
                    828:                        }
1.359     djm       829:                        options.request_tty = REQUEST_TTY_NO;
1.331     dtucker   830:                        no_shell_flag = 1;
                    831:                        break;
1.31      markus    832:                case 'q':
                    833:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    834:                        break;
                    835:                case 'e':
                    836:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     837:                            (u_char) optarg[1] >= 64 &&
                    838:                            (u_char) optarg[1] < 128)
1.78      markus    839:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    840:                        else if (strlen(optarg) == 1)
1.78      markus    841:                                options.escape_char = (u_char) optarg[0];
1.31      markus    842:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   843:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    844:                        else {
1.128     fgsch     845:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    846:                                    optarg);
1.257     dtucker   847:                                exit(255);
1.31      markus    848:                        }
                    849:                        break;
                    850:                case 'c':
1.456     djm       851:                        if (!ciphers_valid(*optarg == '+' ?
1.420     djm       852:                            optarg + 1 : optarg)) {
                    853:                                fprintf(stderr, "Unknown cipher type '%s'\n",
                    854:                                    optarg);
                    855:                                exit(255);
1.95      markus    856:                        }
1.456     djm       857:                        free(options.ciphers);
                    858:                        options.ciphers = xstrdup(optarg);
1.95      markus    859:                        break;
                    860:                case 'm':
1.422     dtucker   861:                        if (mac_valid(optarg)) {
                    862:                                free(options.macs);
1.95      markus    863:                                options.macs = xstrdup(optarg);
1.422     dtucker   864:                        } else {
1.128     fgsch     865:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    866:                                    optarg);
1.257     dtucker   867:                                exit(255);
1.31      markus    868:                        }
                    869:                        break;
1.214     djm       870:                case 'M':
1.242     djm       871:                        if (options.control_master == SSHCTL_MASTER_YES)
                    872:                                options.control_master = SSHCTL_MASTER_ASK;
                    873:                        else
                    874:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       875:                        break;
1.31      markus    876:                case 'p':
1.465     millert   877:                        if (options.port == -1) {
                    878:                                options.port = a2port(optarg);
                    879:                                if (options.port <= 0) {
                    880:                                        fprintf(stderr, "Bad port '%s'\n",
                    881:                                            optarg);
                    882:                                        exit(255);
                    883:                                }
1.109     markus    884:                        }
1.31      markus    885:                        break;
                    886:                case 'l':
1.465     millert   887:                        if (options.user == NULL)
                    888:                                options.user = optarg;
1.31      markus    889:                        break;
1.141     stevesk   890:
                    891:                case 'L':
1.324     djm       892:                        if (parse_forward(&fwd, optarg, 0, 0))
1.232     djm       893:                                add_local_forward(&options, &fwd);
                    894:                        else {
1.128     fgsch     895:                                fprintf(stderr,
1.232     djm       896:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     897:                                    optarg);
1.257     dtucker   898:                                exit(255);
1.31      markus    899:                        }
1.232     djm       900:                        break;
                    901:
                    902:                case 'R':
1.464     markus    903:                        if (parse_forward(&fwd, optarg, 0, 1) ||
                    904:                            parse_forward(&fwd, optarg, 1, 1)) {
1.232     djm       905:                                add_remote_forward(&options, &fwd);
                    906:                        } else {
1.128     fgsch     907:                                fprintf(stderr,
1.232     djm       908:                                    "Bad remote forwarding specification "
                    909:                                    "'%s'\n", optarg);
1.257     dtucker   910:                                exit(255);
1.31      markus    911:                        }
                    912:                        break;
1.108     markus    913:
                    914:                case 'D':
1.324     djm       915:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.322     stevesk   916:                                add_local_forward(&options, &fwd);
1.232     djm       917:                        } else {
1.322     stevesk   918:                                fprintf(stderr,
                    919:                                    "Bad dynamic forwarding specification "
                    920:                                    "'%s'\n", optarg);
1.257     dtucker   921:                                exit(255);
1.109     markus    922:                        }
1.108     markus    923:                        break;
                    924:
1.31      markus    925:                case 'C':
                    926:                        options.compression = 1;
                    927:                        break;
1.45      markus    928:                case 'N':
                    929:                        no_shell_flag = 1;
1.359     djm       930:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus    931:                        break;
                    932:                case 'T':
1.359     djm       933:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus    934:                        break;
1.31      markus    935:                case 'o':
1.205     markus    936:                        line = xstrdup(optarg);
1.408     djm       937:                        if (process_config_line(&options, pw,
                    938:                            host ? host : "", host ? host : "", line,
                    939:                            "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1.257     dtucker   940:                                exit(255);
1.378     djm       941:                        free(line);
1.31      markus    942:                        break;
1.85      djm       943:                case 's':
                    944:                        subsystem_flag = 1;
1.117     markus    945:                        break;
1.214     djm       946:                case 'S':
1.431     mmcc      947:                        free(options.control_path);
1.214     djm       948:                        options.control_path = xstrdup(optarg);
                    949:                        break;
1.117     markus    950:                case 'b':
                    951:                        options.bind_address = optarg;
1.474     djm       952:                        break;
                    953:                case 'B':
                    954:                        options.bind_interface = optarg;
1.85      djm       955:                        break;
1.139     markus    956:                case 'F':
                    957:                        config = optarg;
                    958:                        break;
1.31      markus    959:                default:
                    960:                        usage();
1.1       deraadt   961:                }
1.31      markus    962:        }
                    963:
1.462     djm       964:        if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
                    965:                opt_terminated = 1;
                    966:
1.128     fgsch     967:        ac -= optind;
                    968:        av += optind;
                    969:
1.329     guenther  970:        if (ac > 0 && !host) {
1.465     millert   971:                int tport;
                    972:                char *tuser;
                    973:                switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
                    974:                case -1:
                    975:                        usage();
                    976:                        break;
                    977:                case 0:
                    978:                        if (options.user == NULL) {
                    979:                                options.user = tuser;
                    980:                                tuser = NULL;
                    981:                        }
                    982:                        free(tuser);
                    983:                        if (options.port == -1 && tport != -1)
                    984:                                options.port = tport;
                    985:                        break;
                    986:                default:
1.128     fgsch     987:                        p = xstrdup(*av);
1.188     markus    988:                        cp = strrchr(p, '@');
1.465     millert   989:                        if (cp != NULL) {
                    990:                                if (cp == p)
                    991:                                        usage();
                    992:                                if (options.user == NULL) {
                    993:                                        options.user = p;
                    994:                                        p = NULL;
                    995:                                }
                    996:                                *cp++ = '\0';
                    997:                                host = xstrdup(cp);
                    998:                                free(p);
                    999:                        } else
                   1000:                                host = p;
                   1001:                        break;
                   1002:                }
1.462     djm      1003:                if (ac > 1 && !opt_terminated) {
1.189     millert  1004:                        optind = optreset = 1;
1.128     fgsch    1005:                        goto again;
                   1006:                }
1.189     millert  1007:                ac--, av++;
1.128     fgsch    1008:        }
                   1009:
1.31      markus   1010:        /* Check that we got a host name. */
                   1011:        if (!host)
                   1012:                usage();
                   1013:
1.385     djm      1014:        host_arg = xstrdup(host);
                   1015:
1.402     markus   1016: #ifdef WITH_OPENSSL
1.350     djm      1017:        OpenSSL_add_all_algorithms();
1.72      markus   1018:        ERR_load_crypto_strings();
1.402     markus   1019: #endif
1.31      markus   1020:
                   1021:        /* Initialize the command to execute on remote host. */
1.482     markus   1022:        if ((command = sshbuf_new()) == NULL)
                   1023:                fatal("sshbuf_new failed");
1.1       deraadt  1024:
1.33      markus   1025:        /*
                   1026:         * Save the command to execute on the remote host in a buffer. There
                   1027:         * is no limit on the length of the command, except by the maximum
                   1028:         * packet size.  Also sets the tty flag if there is no command.
                   1029:         */
1.128     fgsch    1030:        if (!ac) {
1.31      markus   1031:                /* No command specified - execute shell on a tty. */
1.85      djm      1032:                if (subsystem_flag) {
1.128     fgsch    1033:                        fprintf(stderr,
                   1034:                            "You must specify a subsystem to invoke.\n");
1.85      djm      1035:                        usage();
                   1036:                }
1.31      markus   1037:        } else {
1.128     fgsch    1038:                /* A command has been specified.  Store it into the buffer. */
                   1039:                for (i = 0; i < ac; i++) {
1.482     markus   1040:                        if ((r = sshbuf_putf(command, "%s%s",
                   1041:                            i ? " " : "", av[i])) != 0)
                   1042:                                fatal("%s: buffer error: %s",
                   1043:                                    __func__, ssh_err(r));
1.31      markus   1044:                }
                   1045:        }
                   1046:
1.101     markus   1047:        /*
                   1048:         * Initialize "log" output.  Since we are the client all output
1.375     dtucker  1049:         * goes to stderr unless otherwise specified by -y or -E.
1.101     markus   1050:         */
1.375     dtucker  1051:        if (use_syslog && logfile != NULL)
                   1052:                fatal("Can't specify both -y and -E");
1.422     dtucker  1053:        if (logfile != NULL)
1.375     dtucker  1054:                log_redirect_stderr_to(logfile);
1.325     markus   1055:        log_init(argv0,
1.468     djm      1056:            options.log_level == SYSLOG_LEVEL_NOT_SET ?
1.452     dtucker  1057:            SYSLOG_LEVEL_INFO : options.log_level,
1.468     djm      1058:            options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1.452     dtucker  1059:            SYSLOG_FACILITY_USER : options.log_facility,
                   1060:            !use_syslog);
1.375     dtucker  1061:
                   1062:        if (debug_flag)
1.402     markus   1063:                logit("%s, %s", SSH_VERSION,
                   1064: #ifdef WITH_OPENSSL
1.495     djm      1065:                    OpenSSL_version(OPENSSL_VERSION)
1.402     markus   1066: #else
                   1067:                    "without OpenSSL"
                   1068: #endif
                   1069:                );
1.31      markus   1070:
1.400     djm      1071:        /* Parse the configuration files */
1.496     djm      1072:        process_config_files(host_arg, pw, 0, &want_final_pass);
                   1073:        if (want_final_pass)
                   1074:                debug("configuration requests final Match pass");
1.400     djm      1075:
                   1076:        /* Hostname canonicalisation needs a few options filled. */
                   1077:        fill_default_options_for_canonicalization(&options);
                   1078:
                   1079:        /* If the user has replaced the hostname then take it into use now */
                   1080:        if (options.hostname != NULL) {
                   1081:                /* NB. Please keep in sync with readconf.c:match_cfg_line() */
                   1082:                cp = percent_expand(options.hostname,
                   1083:                    "h", host, (char *)NULL);
                   1084:                free(host);
                   1085:                host = cp;
1.408     djm      1086:                free(options.hostname);
                   1087:                options.hostname = xstrdup(host);
1.400     djm      1088:        }
                   1089:
1.470     djm      1090:        /* Don't lowercase addresses, they will be explicitly canonicalised */
                   1091:        if ((was_addr = is_addr(host)) == 0)
                   1092:                lowercase(host);
                   1093:
                   1094:        /*
                   1095:         * Try to canonicalize if requested by configuration or the
                   1096:         * hostname is an address.
                   1097:         */
                   1098:        if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1.400     djm      1099:                addrs = resolve_canonicalize(&host, options.port);
                   1100:
1.139     markus   1101:        /*
1.401     djm      1102:         * If CanonicalizePermittedCNAMEs have been specified but
                   1103:         * other canonicalization did not happen (by not being requested
                   1104:         * or by failing with fallback) then the hostname may still be changed
1.468     djm      1105:         * as a result of CNAME following.
1.401     djm      1106:         *
                   1107:         * Try to resolve the bare hostname name using the system resolver's
                   1108:         * usual search rules and then apply the CNAME follow rules.
                   1109:         *
                   1110:         * Skip the lookup if a ProxyCommand is being used unless the user
                   1111:         * has specifically requested canonicalisation for this case via
                   1112:         * CanonicalizeHostname=always
1.139     markus   1113:         */
1.443     djm      1114:        direct = option_clear_or_none(options.proxy_command) &&
                   1115:            options.jump_host == NULL;
                   1116:        if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
                   1117:            options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1.403     djm      1118:                if ((addrs = resolve_host(host, options.port,
1.493     djm      1119:                    direct, cname, sizeof(cname))) == NULL) {
1.403     djm      1120:                        /* Don't fatal proxied host names not in the DNS */
1.493     djm      1121:                        if (direct)
1.403     djm      1122:                                cleanup_exit(255); /* logged in resolve_host */
                   1123:                } else
1.443     djm      1124:                        check_follow_cname(direct, &host, cname);
1.400     djm      1125:        }
1.139     markus   1126:
1.400     djm      1127:        /*
1.408     djm      1128:         * If canonicalisation is enabled then re-parse the configuration
                   1129:         * files as new stanzas may match.
1.400     djm      1130:         */
1.496     djm      1131:        if (options.canonicalize_hostname != 0 && !want_final_pass) {
                   1132:                debug("hostname canonicalisation enabled, "
                   1133:                    "will re-parse configuration");
                   1134:                want_final_pass = 1;
                   1135:        }
                   1136:
                   1137:        if (want_final_pass) {
                   1138:                debug("re-parsing configuration");
1.408     djm      1139:                free(options.hostname);
                   1140:                options.hostname = xstrdup(host);
1.496     djm      1141:                process_config_files(host_arg, pw, 1, NULL);
1.408     djm      1142:                /*
                   1143:                 * Address resolution happens early with canonicalisation
                   1144:                 * enabled and the port number may have changed since, so
                   1145:                 * reset it in address list
                   1146:                 */
                   1147:                if (addrs != NULL && options.port > 0)
                   1148:                        set_addrinfo_port(addrs, options.port);
1.139     markus   1149:        }
1.31      markus   1150:
                   1151:        /* Fill configuration defaults. */
                   1152:        fill_default_options(&options);
1.443     djm      1153:
                   1154:        /*
                   1155:         * If ProxyJump option specified, then construct a ProxyCommand now.
                   1156:         */
                   1157:        if (options.jump_host != NULL) {
                   1158:                char port_s[8];
1.478     djm      1159:                const char *sshbin = argv0;
                   1160:
                   1161:                /*
                   1162:                 * Try to use SSH indicated by argv[0], but fall back to
                   1163:                 * "ssh" if it appears unavailable.
                   1164:                 */
                   1165:                if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
                   1166:                        sshbin = "ssh";
1.443     djm      1167:
                   1168:                /* Consistency check */
                   1169:                if (options.proxy_command != NULL)
                   1170:                        fatal("inconsistent options: ProxyCommand+ProxyJump");
                   1171:                /* Never use FD passing for ProxyJump */
                   1172:                options.proxy_use_fdpass = 0;
                   1173:                snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
                   1174:                xasprintf(&options.proxy_command,
1.478     djm      1175:                    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
                   1176:                    sshbin,
1.443     djm      1177:                    /* Optional "-l user" argument if jump_user set */
                   1178:                    options.jump_user == NULL ? "" : " -l ",
                   1179:                    options.jump_user == NULL ? "" : options.jump_user,
                   1180:                    /* Optional "-p port" argument if jump_port set */
                   1181:                    options.jump_port <= 0 ? "" : " -p ",
                   1182:                    options.jump_port <= 0 ? "" : port_s,
                   1183:                    /* Optional additional jump hosts ",..." */
                   1184:                    options.jump_extra == NULL ? "" : " -J ",
                   1185:                    options.jump_extra == NULL ? "" : options.jump_extra,
                   1186:                    /* Optional "-F" argumment if -F specified */
                   1187:                    config == NULL ? "" : " -F ",
                   1188:                    config == NULL ? "" : config,
                   1189:                    /* Optional "-v" arguments if -v set */
                   1190:                    debug_flag ? " -" : "",
                   1191:                    debug_flag, "vvv",
                   1192:                    /* Mandatory hostname */
                   1193:                    options.jump_host);
                   1194:                debug("Setting implicit ProxyCommand from ProxyJump: %s",
                   1195:                    options.proxy_command);
                   1196:        }
1.31      markus   1197:
1.400     djm      1198:        if (options.port == 0)
                   1199:                options.port = default_ssh_port();
1.463     djm      1200:        channel_set_af(ssh, options.address_family);
1.196     djm      1201:
1.383     djm      1202:        /* Tidy and check options */
                   1203:        if (options.host_key_alias != NULL)
                   1204:                lowercase(options.host_key_alias);
                   1205:        if (options.proxy_command != NULL &&
                   1206:            strcmp(options.proxy_command, "-") == 0 &&
                   1207:            options.proxy_use_fdpass)
                   1208:                fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1.415     djm      1209:        if (options.control_persist &&
                   1210:            options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
                   1211:                debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
                   1212:                    "disabling");
                   1213:                options.update_hostkeys = 0;
                   1214:        }
1.430     djm      1215:        if (options.connection_attempts <= 0)
                   1216:                fatal("Invalid number of ConnectionAttempts");
                   1217:
1.482     markus   1218:        if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1.461     bluhm    1219:                fatal("Cannot execute command-line and remote command.");
                   1220:
                   1221:        /* Cannot fork to background if no command. */
1.482     markus   1222:        if (fork_after_authentication_flag && sshbuf_len(command) == 0 &&
1.461     bluhm    1223:            options.remote_command == NULL && !no_shell_flag)
                   1224:                fatal("Cannot fork into background without a command "
                   1225:                    "to execute.");
                   1226:
1.31      markus   1227:        /* reinit */
1.452     dtucker  1228:        log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1.370     djm      1229:
                   1230:        if (options.request_tty == REQUEST_TTY_YES ||
                   1231:            options.request_tty == REQUEST_TTY_FORCE)
                   1232:                tty_flag = 1;
                   1233:
                   1234:        /* Allocate a tty by default if no command specified. */
1.482     markus   1235:        if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1.370     djm      1236:                tty_flag = options.request_tty != REQUEST_TTY_NO;
                   1237:
                   1238:        /* Force no tty */
1.447     markus   1239:        if (options.request_tty == REQUEST_TTY_NO ||
                   1240:            (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1.370     djm      1241:                tty_flag = 0;
                   1242:        /* Do not allocate a tty if stdin is not a tty. */
                   1243:        if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
                   1244:            options.request_tty != REQUEST_TTY_FORCE) {
                   1245:                if (tty_flag)
                   1246:                        logit("Pseudo-terminal will not be allocated because "
                   1247:                            "stdin is not a terminal.");
                   1248:                tty_flag = 0;
                   1249:        }
1.31      markus   1250:
                   1251:        if (options.user == NULL)
                   1252:                options.user = xstrdup(pw->pw_name);
1.343     djm      1253:
1.466     djm      1254:        /* Set up strings used to percent_expand() arguments */
1.358     djm      1255:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1256:                fatal("gethostname: %s", strerror(errno));
                   1257:        strlcpy(shorthost, thishost, sizeof(shorthost));
                   1258:        shorthost[strcspn(thishost, ".")] = '\0';
                   1259:        snprintf(portstr, sizeof(portstr), "%d", options.port);
1.479     djm      1260:        snprintf(uidstr, sizeof(uidstr), "%llu",
                   1261:            (unsigned long long)pw->pw_uid);
1.358     djm      1262:
1.405     djm      1263:        if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
                   1264:            ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
                   1265:            ssh_digest_update(md, host, strlen(host)) < 0 ||
                   1266:            ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
                   1267:            ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
                   1268:            ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
                   1269:                fatal("%s: mux digest failed", __func__);
                   1270:        ssh_digest_free(md);
                   1271:        conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
                   1272:
1.466     djm      1273:        /*
                   1274:         * Expand tokens in arguments. NB. LocalCommand is expanded later,
                   1275:         * after port-forwarding is set up, so it may pick up any local
                   1276:         * tunnel interface name allocated.
                   1277:         */
1.461     bluhm    1278:        if (options.remote_command != NULL) {
                   1279:                debug3("expanding RemoteCommand: %s", options.remote_command);
                   1280:                cp = options.remote_command;
                   1281:                options.remote_command = percent_expand(cp,
                   1282:                    "C", conn_hash_hex,
                   1283:                    "L", shorthost,
                   1284:                    "d", pw->pw_dir,
                   1285:                    "h", host,
1.479     djm      1286:                    "i", uidstr,
1.461     bluhm    1287:                    "l", thishost,
                   1288:                    "n", host_arg,
                   1289:                    "p", portstr,
                   1290:                    "r", options.user,
                   1291:                    "u", pw->pw_name,
                   1292:                    (char *)NULL);
                   1293:                debug3("expanded RemoteCommand: %s", options.remote_command);
                   1294:                free(cp);
1.482     markus   1295:                if ((r = sshbuf_put(command, options.remote_command,
                   1296:                    strlen(options.remote_command))) != 0)
                   1297:                        fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.304     dtucker  1298:        }
1.31      markus   1299:
1.214     djm      1300:        if (options.control_path != NULL) {
1.490     dtucker  1301:                cp = tilde_expand_filename(options.control_path, getuid());
1.378     djm      1302:                free(options.control_path);
1.405     djm      1303:                options.control_path = percent_expand(cp,
                   1304:                    "C", conn_hash_hex,
                   1305:                    "L", shorthost,
                   1306:                    "h", host,
1.479     djm      1307:                    "i", uidstr,
1.405     djm      1308:                    "l", thishost,
                   1309:                    "n", host_arg,
                   1310:                    "p", portstr,
                   1311:                    "r", options.user,
                   1312:                    "u", pw->pw_name,
1.423     djm      1313:                    "i", uidstr,
1.358     djm      1314:                    (char *)NULL);
1.378     djm      1315:                free(cp);
1.214     djm      1316:        }
1.408     djm      1317:
                   1318:        if (config_test) {
                   1319:                dump_client_config(&options, host);
                   1320:                exit(0);
                   1321:        }
1.405     djm      1322:
1.312     djm      1323:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm      1324:                fatal("No ControlPath specified for \"-O\" command");
1.447     markus   1325:        if (options.control_path != NULL) {
                   1326:                int sock;
                   1327:                if ((sock = muxclient(options.control_path)) >= 0) {
1.463     djm      1328:                        ssh_packet_set_connection(ssh, sock, sock);
1.499     djm      1329:                        ssh_packet_set_mux(ssh);
1.447     markus   1330:                        goto skip_connect;
                   1331:                }
                   1332:        }
1.401     djm      1333:
                   1334:        /*
                   1335:         * If hostname canonicalisation was not enabled, then we may not
                   1336:         * have yet resolved the hostname. Do so now.
                   1337:         */
                   1338:        if (addrs == NULL && options.proxy_command == NULL) {
1.421     djm      1339:                debug2("resolving \"%s\" port %d", host, options.port);
1.401     djm      1340:                if ((addrs = resolve_host(host, options.port, 1,
                   1341:                    cname, sizeof(cname))) == NULL)
                   1342:                        cleanup_exit(255); /* resolve_host logs the error */
                   1343:        }
1.214     djm      1344:
1.303     djm      1345:        timeout_ms = options.connection_timeout * 1000;
                   1346:
1.77      markus   1347:        /* Open a connection to the remote host. */
1.463     djm      1348:        if (ssh_connect(ssh, host, addrs, &hostaddr, options.port,
1.385     djm      1349:            options.address_family, options.connection_attempts,
1.488     dtucker  1350:            &timeout_ms, options.tcp_keep_alive) != 0)
1.257     dtucker  1351:                exit(255);
1.31      markus   1352:
1.391     djm      1353:        if (addrs != NULL)
                   1354:                freeaddrinfo(addrs);
                   1355:
1.499     djm      1356:        ssh_packet_set_timeout(ssh, options.server_alive_interval,
1.385     djm      1357:            options.server_alive_count_max);
                   1358:
1.303     djm      1359:        if (timeout_ms > 0)
                   1360:                debug3("timeout: %d ms remain after connect", timeout_ms);
                   1361:
1.33      markus   1362:        /*
1.485     dtucker  1363:         * If we successfully made the connection and we have hostbased auth
                   1364:         * enabled, load the public keys so we can later use the ssh-keysign
                   1365:         * helper to sign challenges.
1.33      markus   1366:         */
1.112     markus   1367:        sensitive_data.nkeys = 0;
                   1368:        sensitive_data.keys = NULL;
1.457     djm      1369:        if (options.hostbased_authentication) {
1.486     dtucker  1370:                sensitive_data.nkeys = 10;
1.274     deraadt  1371:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.483     markus   1372:                    sizeof(struct sshkey));
                   1373:
                   1374:                /* XXX check errors? */
1.486     dtucker  1375: #define L_PUBKEY(p,o) do { \
                   1376:        if ((o) >= sensitive_data.nkeys) \
                   1377:                fatal("%s pubkey out of array bounds", __func__); \
1.483     markus   1378:        check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1.486     dtucker  1379:            p, "pubkey"); \
                   1380: } while (0)
                   1381: #define L_CERT(p,o) do { \
                   1382:        if ((o) >= sensitive_data.nkeys) \
                   1383:                fatal("%s cert out of array bounds", __func__); \
                   1384:        check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
                   1385: } while (0)
1.177     markus   1386:
1.485     dtucker  1387:                if (options.hostbased_authentication == 1) {
1.486     dtucker  1388:                        L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
                   1389:                        L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
                   1390:                        L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
                   1391:                        L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
                   1392:                        L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
                   1393:                        L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
                   1394:                        L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
                   1395:                        L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
                   1396:                        L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
                   1397:                        L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1.173     markus   1398:                }
1.31      markus   1399:        }
                   1400:
1.487     dtucker  1401:        /* Create ~/.ssh * directory if it doesn't already exist. */
1.367     djm      1402:        if (config == NULL) {
                   1403:                r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
                   1404:                    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
                   1405:                if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
                   1406:                        if (mkdir(buf, 0700) < 0)
                   1407:                                error("Could not create directory '%.200s'.",
                   1408:                                    buf);
                   1409:        }
1.31      markus   1410:
1.104     markus   1411:        /* load options.identity_files */
1.466     djm      1412:        load_public_identity_files(pw);
1.439     markus   1413:
1.476     djm      1414:        /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1.440     markus   1415:        if (options.identity_agent &&
                   1416:            strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1.439     markus   1417:                if (strcmp(options.identity_agent, "none") == 0) {
                   1418:                        unsetenv(SSH_AUTHSOCKET_ENV_NAME);
                   1419:                } else {
                   1420:                        p = tilde_expand_filename(options.identity_agent,
1.490     dtucker  1421:                            getuid());
1.479     djm      1422:                        cp = percent_expand(p,
                   1423:                            "d", pw->pw_dir,
                   1424:                            "h", host,
                   1425:                            "i", uidstr,
                   1426:                            "l", thishost,
                   1427:                            "r", options.user,
                   1428:                            "u", pw->pw_name,
                   1429:                            (char *)NULL);
1.494     djm      1430:                        free(p);
                   1431:                        /*
                   1432:                         * If identity_agent represents an environment variable
                   1433:                         * then recheck that it is valid (since processing with
                   1434:                         * percent_expand() may have changed it) and substitute
                   1435:                         * its value.
                   1436:                         */
                   1437:                        if (cp[0] == '$') {
                   1438:                                if (!valid_env_name(cp + 1)) {
                   1439:                                        fatal("Invalid IdentityAgent "
                   1440:                                            "environment variable name %s", cp);
                   1441:                                }
                   1442:                                if ((p = getenv(cp + 1)) == NULL)
                   1443:                                        unsetenv(SSH_AUTHSOCKET_ENV_NAME);
                   1444:                                else
                   1445:                                        setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
                   1446:                        } else {
                   1447:                                /* identity_agent specifies a path directly */
                   1448:                                setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
                   1449:                        }
1.439     markus   1450:                        free(cp);
                   1451:                }
                   1452:        }
1.104     markus   1453:
                   1454:        /* Expand ~ in known host file names. */
1.361     djm      1455:        tilde_expand_paths(options.system_hostfiles,
                   1456:            options.num_system_hostfiles);
                   1457:        tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1.149     markus   1458:
                   1459:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.352     djm      1460:        signal(SIGCHLD, main_sigchld_handler);
1.31      markus   1461:
1.316     djm      1462:        /* Log into the remote system.  Never returns if the login fails. */
1.497     djm      1463:        ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1.355     djm      1464:            options.port, pw, timeout_ms);
1.339     djm      1465:
1.499     djm      1466:        if (ssh_packet_connection_is_on_socket(ssh)) {
1.339     djm      1467:                verbose("Authenticated to %s ([%s]:%d).", host,
1.437     djm      1468:                    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1.339     djm      1469:        } else {
                   1470:                verbose("Authenticated to %s (via proxy).", host);
                   1471:        }
1.31      markus   1472:
1.112     markus   1473:        /* We no longer need the private host keys.  Clear them now. */
                   1474:        if (sensitive_data.nkeys != 0) {
                   1475:                for (i = 0; i < sensitive_data.nkeys; i++) {
                   1476:                        if (sensitive_data.keys[i] != NULL) {
                   1477:                                /* Destroys contents safely */
                   1478:                                debug3("clear hostkey %d", i);
1.483     markus   1479:                                sshkey_free(sensitive_data.keys[i]);
1.112     markus   1480:                                sensitive_data.keys[i] = NULL;
                   1481:                        }
                   1482:                }
1.378     djm      1483:                free(sensitive_data.keys);
1.134     markus   1484:        }
                   1485:        for (i = 0; i < options.num_identity_files; i++) {
1.378     djm      1486:                free(options.identity_files[i]);
                   1487:                options.identity_files[i] = NULL;
1.134     markus   1488:                if (options.identity_keys[i]) {
1.483     markus   1489:                        sshkey_free(options.identity_keys[i]);
1.134     markus   1490:                        options.identity_keys[i] = NULL;
                   1491:                }
1.112     markus   1492:        }
1.426     djm      1493:        for (i = 0; i < options.num_certificate_files; i++) {
                   1494:                free(options.certificate_files[i]);
                   1495:                options.certificate_files[i] = NULL;
                   1496:        }
1.31      markus   1497:
1.447     markus   1498:  skip_connect:
1.466     djm      1499:        exit_status = ssh_session2(ssh, pw);
1.499     djm      1500:        ssh_packet_close(ssh);
1.186     djm      1501:
1.312     djm      1502:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm      1503:                unlink(options.control_path);
                   1504:
1.353     djm      1505:        /* Kill ProxyCommand if it is running. */
                   1506:        ssh_kill_proxy_command();
1.186     djm      1507:
1.45      markus   1508:        return exit_status;
                   1509: }
                   1510:
1.344     djm      1511: static void
                   1512: control_persist_detach(void)
                   1513: {
                   1514:        pid_t pid;
1.438     djm      1515:        int devnull, keep_stderr;
1.344     djm      1516:
                   1517:        debug("%s: backgrounding master process", __func__);
                   1518:
1.473     djm      1519:        /*
                   1520:         * master (current process) into the background, and make the
                   1521:         * foreground process a client of the backgrounded master.
                   1522:         */
1.344     djm      1523:        switch ((pid = fork())) {
                   1524:        case -1:
                   1525:                fatal("%s: fork: %s", __func__, strerror(errno));
                   1526:        case 0:
                   1527:                /* Child: master process continues mainloop */
1.473     djm      1528:                break;
                   1529:        default:
1.344     djm      1530:                /* Parent: set up mux slave to connect to backgrounded master */
                   1531:                debug2("%s: background process is %ld", __func__, (long)pid);
                   1532:                stdin_null_flag = ostdin_null_flag;
1.359     djm      1533:                options.request_tty = orequest_tty;
1.344     djm      1534:                tty_flag = otty_flag;
1.473     djm      1535:                close(muxserver_sock);
                   1536:                muxserver_sock = -1;
1.351     markus   1537:                options.control_master = SSHCTL_MASTER_NO;
1.473     djm      1538:                muxclient(options.control_path);
1.344     djm      1539:                /* muxclient() doesn't return on success. */
1.473     djm      1540:                fatal("Failed to connect to new control master");
                   1541:        }
1.346     djm      1542:        if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
                   1543:                error("%s: open(\"/dev/null\"): %s", __func__,
                   1544:                    strerror(errno));
                   1545:        } else {
1.438     djm      1546:                keep_stderr = log_is_on_stderr() && debug_flag;
1.346     djm      1547:                if (dup2(devnull, STDIN_FILENO) == -1 ||
1.438     djm      1548:                    dup2(devnull, STDOUT_FILENO) == -1 ||
                   1549:                    (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1.346     djm      1550:                        error("%s: dup2: %s", __func__, strerror(errno));
                   1551:                if (devnull > STDERR_FILENO)
                   1552:                        close(devnull);
                   1553:        }
1.381     djm      1554:        daemon(1, 1);
1.362     djm      1555:        setproctitle("%s [mux]", options.control_path);
1.344     djm      1556: }
                   1557:
                   1558: /* Do fork() after authentication. Used by "ssh -f" */
                   1559: static void
                   1560: fork_postauth(void)
                   1561: {
                   1562:        if (need_controlpersist_detach)
                   1563:                control_persist_detach();
                   1564:        debug("forking to background");
                   1565:        fork_after_authentication_flag = 0;
                   1566:        if (daemon(1, 1) < 0)
                   1567:                fatal("daemon() failed: %.200s", strerror(errno));
                   1568: }
                   1569:
1.315     djm      1570: /* Callback for remote forward global requests */
                   1571: static void
1.463     djm      1572: ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1.315     djm      1573: {
1.406     millert  1574:        struct Forward *rfwd = (struct Forward *)ctxt;
1.499     djm      1575:        u_int port;
                   1576:        int r;
1.315     djm      1577:
1.324     djm      1578:        /* XXX verbose() on failure? */
1.404     markus   1579:        debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1.315     djm      1580:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1.406     millert  1581:            rfwd->listen_path ? rfwd->listen_path :
                   1582:            rfwd->listen_host ? rfwd->listen_host : "",
                   1583:            (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
                   1584:            rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
                   1585:            rfwd->connect_host, rfwd->connect_port);
                   1586:        if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1.366     markus   1587:                if (type == SSH2_MSG_REQUEST_SUCCESS) {
1.499     djm      1588:                        if ((r = sshpkt_get_u32(ssh, &port)) != 0)
                   1589:                                fatal("%s: %s", __func__, ssh_err(r));
                   1590:                        if (port > 65535) {
                   1591:                                error("Invalid allocated port %u for remote "
                   1592:                                    "forward to %s:%d", port,
                   1593:                                    rfwd->connect_host, rfwd->connect_port);
                   1594:                                /* Ensure failure processing runs below */
                   1595:                                type = SSH2_MSG_REQUEST_FAILURE;
                   1596:                                channel_update_permission(ssh,
                   1597:                                    rfwd->handle, -1);
                   1598:                        } else {
                   1599:                                rfwd->allocated_port = (int)port;
                   1600:                                logit("Allocated port %u for remote "
                   1601:                                    "forward to %s:%d",
                   1602:                                    rfwd->allocated_port, rfwd->connect_host,
                   1603:                                    rfwd->connect_port);
                   1604:                                channel_update_permission(ssh,
                   1605:                                    rfwd->handle, rfwd->allocated_port);
                   1606:                        }
1.366     markus   1607:                } else {
1.480     djm      1608:                        channel_update_permission(ssh, rfwd->handle, -1);
1.366     markus   1609:                }
1.324     djm      1610:        }
1.468     djm      1611:
1.315     djm      1612:        if (type == SSH2_MSG_REQUEST_FAILURE) {
1.406     millert  1613:                if (options.exit_on_forward_failure) {
                   1614:                        if (rfwd->listen_path != NULL)
                   1615:                                fatal("Error: remote port forwarding failed "
                   1616:                                    "for listen path %s", rfwd->listen_path);
                   1617:                        else
                   1618:                                fatal("Error: remote port forwarding failed "
                   1619:                                    "for listen port %d", rfwd->listen_port);
                   1620:                } else {
                   1621:                        if (rfwd->listen_path != NULL)
                   1622:                                logit("Warning: remote port forwarding failed "
                   1623:                                    "for listen path %s", rfwd->listen_path);
                   1624:                        else
                   1625:                                logit("Warning: remote port forwarding failed "
                   1626:                                    "for listen port %d", rfwd->listen_port);
                   1627:                }
1.315     djm      1628:        }
1.318     djm      1629:        if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315     djm      1630:                debug("All remote forwarding requests processed");
1.344     djm      1631:                if (fork_after_authentication_flag)
                   1632:                        fork_postauth();
1.318     djm      1633:        }
1.315     djm      1634: }
                   1635:
1.126     itojun   1636: static void
1.463     djm      1637: client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1.331     dtucker  1638: {
                   1639:        debug("stdio forwarding: done");
                   1640:        cleanup_exit(0);
                   1641: }
                   1642:
1.368     djm      1643: static void
1.463     djm      1644: ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1.407     djm      1645: {
                   1646:        if (!success)
                   1647:                fatal("stdio forwarding failed");
                   1648: }
                   1649:
                   1650: static void
1.463     djm      1651: ssh_init_stdio_forwarding(struct ssh *ssh)
1.331     dtucker  1652: {
                   1653:        Channel *c;
1.332     djm      1654:        int in, out;
1.331     dtucker  1655:
1.441     dtucker  1656:        if (options.stdio_forward_host == NULL)
1.368     djm      1657:                return;
                   1658:
1.441     dtucker  1659:        debug3("%s: %s:%d", __func__, options.stdio_forward_host,
                   1660:            options.stdio_forward_port);
1.332     djm      1661:
1.368     djm      1662:        if ((in = dup(STDIN_FILENO)) < 0 ||
                   1663:            (out = dup(STDOUT_FILENO)) < 0)
1.332     djm      1664:                fatal("channel_connect_stdio_fwd: dup() in/out failed");
1.463     djm      1665:        if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1.441     dtucker  1666:            options.stdio_forward_port, in, out)) == NULL)
1.368     djm      1667:                fatal("%s: channel_connect_stdio_fwd failed", __func__);
1.463     djm      1668:        channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
                   1669:        channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1.331     dtucker  1670: }
                   1671:
                   1672: static void
1.466     djm      1673: ssh_init_forwarding(struct ssh *ssh, char **ifname)
1.70      markus   1674: {
1.86      markus   1675:        int success = 0;
1.70      markus   1676:        int i;
1.331     dtucker  1677:
1.70      markus   1678:        /* Initiate local TCP/IP port forwardings. */
                   1679:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm      1680:                debug("Local connections to %.200s:%d forwarded to remote "
                   1681:                    "address %.200s:%d",
1.406     millert  1682:                    (options.local_forwards[i].listen_path != NULL) ?
                   1683:                    options.local_forwards[i].listen_path :
1.234     deraadt  1684:                    (options.local_forwards[i].listen_host == NULL) ?
1.406     millert  1685:                    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm      1686:                    options.local_forwards[i].listen_host,
                   1687:                    options.local_forwards[i].listen_port,
1.406     millert  1688:                    (options.local_forwards[i].connect_path != NULL) ?
                   1689:                    options.local_forwards[i].connect_path :
1.232     djm      1690:                    options.local_forwards[i].connect_host,
                   1691:                    options.local_forwards[i].connect_port);
1.463     djm      1692:                success += channel_setup_local_fwd_listener(ssh,
1.406     millert  1693:                    &options.local_forwards[i], &options.fwd_opts);
1.70      markus   1694:        }
1.283     markus   1695:        if (i > 0 && success != i && options.exit_on_forward_failure)
                   1696:                fatal("Could not request local forwarding.");
1.86      markus   1697:        if (i > 0 && success == 0)
                   1698:                error("Could not request local forwarding.");
1.70      markus   1699:
                   1700:        /* Initiate remote TCP/IP port forwardings. */
                   1701:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm      1702:                debug("Remote connections from %.200s:%d forwarded to "
                   1703:                    "local address %.200s:%d",
1.406     millert  1704:                    (options.remote_forwards[i].listen_path != NULL) ?
                   1705:                    options.remote_forwards[i].listen_path :
1.248     djm      1706:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm      1707:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm      1708:                    options.remote_forwards[i].listen_port,
1.406     millert  1709:                    (options.remote_forwards[i].connect_path != NULL) ?
                   1710:                    options.remote_forwards[i].connect_path :
1.232     djm      1711:                    options.remote_forwards[i].connect_host,
                   1712:                    options.remote_forwards[i].connect_port);
1.366     markus   1713:                options.remote_forwards[i].handle =
1.463     djm      1714:                    channel_request_remote_forwarding(ssh,
1.406     millert  1715:                    &options.remote_forwards[i]);
1.366     markus   1716:                if (options.remote_forwards[i].handle < 0) {
1.283     markus   1717:                        if (options.exit_on_forward_failure)
                   1718:                                fatal("Could not request remote forwarding.");
                   1719:                        else
                   1720:                                logit("Warning: Could not request remote "
                   1721:                                    "forwarding.");
1.366     markus   1722:                } else {
1.463     djm      1723:                        client_register_global_confirm(
                   1724:                            ssh_confirm_remote_forward,
1.366     markus   1725:                            &options.remote_forwards[i]);
1.283     markus   1726:                }
1.70      markus   1727:        }
1.301     djm      1728:
                   1729:        /* Initiate tunnel forwarding. */
                   1730:        if (options.tun_open != SSH_TUNMODE_NO) {
1.466     djm      1731:                if ((*ifname = client_request_tun_fwd(ssh,
                   1732:                    options.tun_open, options.tun_local,
                   1733:                    options.tun_remote)) == NULL) {
1.301     djm      1734:                        if (options.exit_on_forward_failure)
                   1735:                                fatal("Could not request tunnel forwarding.");
                   1736:                        else
                   1737:                                error("Could not request tunnel forwarding.");
                   1738:                }
1.468     djm      1739:        }
1.70      markus   1740: }
                   1741:
1.126     itojun   1742: static void
1.70      markus   1743: check_agent_present(void)
                   1744: {
1.412     djm      1745:        int r;
                   1746:
1.70      markus   1747:        if (options.forward_agent) {
1.254     djm      1748:                /* Clear agent forwarding if we don't have an agent. */
1.412     djm      1749:                if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1.70      markus   1750:                        options.forward_agent = 0;
1.412     djm      1751:                        if (r != SSH_ERR_AGENT_NOT_PRESENT)
                   1752:                                debug("ssh_get_authentication_socket: %s",
                   1753:                                    ssh_err(r));
                   1754:                }
1.70      markus   1755:        }
                   1756: }
                   1757:
1.214     djm      1758: static void
1.463     djm      1759: ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1.214     djm      1760: {
1.215     djm      1761:        extern char **environ;
1.243     djm      1762:        const char *display;
1.499     djm      1763:        int r, interactive = tty_flag;
1.433     djm      1764:        char *proto = NULL, *data = NULL;
1.337     djm      1765:
                   1766:        if (!success)
                   1767:                return; /* No need for error message, channels code sens one */
1.215     djm      1768:
1.248     djm      1769:        display = getenv("DISPLAY");
1.417     djm      1770:        if (display == NULL && options.forward_x11)
                   1771:                debug("X11 forwarding requested but DISPLAY not set");
1.463     djm      1772:        if (options.forward_x11 && client_x11_get_proto(ssh, display,
1.433     djm      1773:            options.xauth_location, options.forward_x11_trusted,
                   1774:            options.forward_x11_timeout, &proto, &data) == 0) {
1.50      markus   1775:                /* Request forwarding with authentication spoofing. */
1.316     djm      1776:                debug("Requesting X11 forwarding with authentication "
                   1777:                    "spoofing.");
1.463     djm      1778:                x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1.363     djm      1779:                    data, 1);
1.463     djm      1780:                client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1.363     djm      1781:                /* XXX exit_on_forward_failure */
1.80      markus   1782:                interactive = 1;
1.50      markus   1783:        }
                   1784:
1.70      markus   1785:        check_agent_present();
                   1786:        if (options.forward_agent) {
                   1787:                debug("Requesting authentication agent forwarding.");
1.463     djm      1788:                channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1.499     djm      1789:                if ((r = sshpkt_send(ssh)) != 0)
                   1790:                        fatal("%s: %s", __func__, ssh_err(r));
1.212     djm      1791:        }
1.369     dtucker  1792:
                   1793:        /* Tell the packet module whether this is an interactive session. */
1.499     djm      1794:        ssh_packet_set_interactive(ssh, interactive,
1.369     dtucker  1795:            options.ip_qos_interactive, options.ip_qos_bulk);
1.212     djm      1796:
1.463     djm      1797:        client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1.482     markus   1798:            NULL, fileno(stdin), command, environ);
1.45      markus   1799: }
                   1800:
1.143     markus   1801: /* open new channel for a session */
1.126     itojun   1802: static int
1.463     djm      1803: ssh_session2_open(struct ssh *ssh)
1.45      markus   1804: {
1.118     markus   1805:        Channel *c;
                   1806:        int window, packetmax, in, out, err;
1.60      markus   1807:
1.62      markus   1808:        if (stdin_null_flag) {
1.93      itojun   1809:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1810:        } else {
                   1811:                in = dup(STDIN_FILENO);
                   1812:        }
1.60      markus   1813:        out = dup(STDOUT_FILENO);
                   1814:        err = dup(STDERR_FILENO);
1.45      markus   1815:
                   1816:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1817:                fatal("dup() in/out/err failed");
1.45      markus   1818:
1.69      markus   1819:        /* enable nonblocking unless tty */
                   1820:        if (!isatty(in))
                   1821:                set_nonblock(in);
                   1822:        if (!isatty(out))
                   1823:                set_nonblock(out);
                   1824:        if (!isatty(err))
                   1825:                set_nonblock(err);
                   1826:
1.65      markus   1827:        window = CHAN_SES_WINDOW_DEFAULT;
                   1828:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1829:        if (tty_flag) {
                   1830:                window >>= 1;
                   1831:                packetmax >>= 1;
1.45      markus   1832:        }
1.463     djm      1833:        c = channel_new(ssh,
1.45      markus   1834:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1835:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1836:            "client-session", /*nonblock*/0);
1.45      markus   1837:
1.463     djm      1838:        debug3("%s: channel_new: %d", __func__, c->self);
1.106     markus   1839:
1.463     djm      1840:        channel_send_open(ssh, c->self);
1.143     markus   1841:        if (!no_shell_flag)
1.463     djm      1842:                channel_register_open_confirm(ssh, c->self,
1.310     djm      1843:                    ssh_session2_setup, NULL);
1.106     markus   1844:
1.118     markus   1845:        return c->self;
1.106     markus   1846: }
                   1847:
1.126     itojun   1848: static int
1.466     djm      1849: ssh_session2(struct ssh *ssh, struct passwd *pw)
1.106     markus   1850: {
1.499     djm      1851:        int r, devnull, id = -1;
1.466     djm      1852:        char *cp, *tun_fwd_ifname = NULL;
1.106     markus   1853:
                   1854:        /* XXX should be pre-session */
1.368     djm      1855:        if (!options.control_persist)
1.463     djm      1856:                ssh_init_stdio_forwarding(ssh);
1.466     djm      1857:
                   1858:        ssh_init_forwarding(ssh, &tun_fwd_ifname);
                   1859:
                   1860:        if (options.local_command != NULL) {
                   1861:                debug3("expanding LocalCommand: %s", options.local_command);
                   1862:                cp = options.local_command;
                   1863:                options.local_command = percent_expand(cp,
                   1864:                    "C", conn_hash_hex,
                   1865:                    "L", shorthost,
                   1866:                    "d", pw->pw_dir,
                   1867:                    "h", host,
1.479     djm      1868:                    "i", uidstr,
1.466     djm      1869:                    "l", thishost,
                   1870:                    "n", host_arg,
                   1871:                    "p", portstr,
                   1872:                    "r", options.user,
                   1873:                    "u", pw->pw_name,
                   1874:                    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
                   1875:                    (char *)NULL);
                   1876:                debug3("expanded LocalCommand: %s", options.local_command);
                   1877:                free(cp);
                   1878:        }
1.106     markus   1879:
1.344     djm      1880:        /* Start listening for multiplex clients */
1.499     djm      1881:        if (!ssh_packet_get_mux(ssh))
1.463     djm      1882:                muxserver_listen(ssh);
1.344     djm      1883:
1.473     djm      1884:        /*
1.368     djm      1885:         * If we are in control persist mode and have a working mux listen
                   1886:         * socket, then prepare to background ourselves and have a foreground
                   1887:         * client attach as a control slave.
                   1888:         * NB. we must save copies of the flags that we override for
1.344     djm      1889:         * the backgrounding, since we defer attachment of the slave until
                   1890:         * after the connection is fully established (in particular,
                   1891:         * async rfwd replies have been received for ExitOnForwardFailure).
                   1892:         */
1.473     djm      1893:        if (options.control_persist && muxserver_sock != -1) {
1.344     djm      1894:                ostdin_null_flag = stdin_null_flag;
                   1895:                ono_shell_flag = no_shell_flag;
1.359     djm      1896:                orequest_tty = options.request_tty;
1.344     djm      1897:                otty_flag = tty_flag;
1.473     djm      1898:                stdin_null_flag = 1;
                   1899:                no_shell_flag = 1;
                   1900:                tty_flag = 0;
1.344     djm      1901:                if (!fork_after_authentication_flag)
                   1902:                        need_controlpersist_detach = 1;
                   1903:                fork_after_authentication_flag = 1;
1.473     djm      1904:        }
1.368     djm      1905:        /*
                   1906:         * ControlPersist mux listen socket setup failed, attempt the
                   1907:         * stdio forward setup that we skipped earlier.
                   1908:         */
                   1909:        if (options.control_persist && muxserver_sock == -1)
1.463     djm      1910:                ssh_init_stdio_forwarding(ssh);
1.344     djm      1911:
1.471     djm      1912:        if (!no_shell_flag)
1.463     djm      1913:                id = ssh_session2_open(ssh);
1.379     djm      1914:        else {
1.499     djm      1915:                ssh_packet_set_interactive(ssh,
1.379     djm      1916:                    options.control_master == SSHCTL_MASTER_NO,
                   1917:                    options.ip_qos_interactive, options.ip_qos_bulk);
                   1918:        }
1.314     djm      1919:
                   1920:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   1921:        if (options.control_master == SSHCTL_MASTER_NO &&
                   1922:            (datafellows & SSH_NEW_OPENSSH)) {
1.314     djm      1923:                debug("Requesting no-more-sessions@openssh.com");
1.499     djm      1924:                if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                   1925:                    (r = sshpkt_put_cstring(ssh,
                   1926:                    "no-more-sessions@openssh.com")) != 0 ||
                   1927:                    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
                   1928:                    (r = sshpkt_send(ssh)) != 0)
                   1929:                        fatal("%s: %s", __func__, ssh_err(r));
1.314     djm      1930:        }
1.255     reyk     1931:
                   1932:        /* Execute a local command */
                   1933:        if (options.local_command != NULL &&
                   1934:            options.permit_local_command)
                   1935:                ssh_local_cmd(options.local_command);
1.467     djm      1936:
                   1937:        /*
                   1938:         * stdout is now owned by the session channel; clobber it here
                   1939:         * so future channel closes are propagated to the local fd.
                   1940:         * NB. this can only happen after LocalCommand has completed,
                   1941:         * as it may want to write to stdout.
                   1942:         */
1.469     djm      1943:        if (!need_controlpersist_detach) {
                   1944:                if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1)
                   1945:                        error("%s: open %s: %s", __func__,
                   1946:                            _PATH_DEVNULL, strerror(errno));
                   1947:                if (dup2(devnull, STDOUT_FILENO) < 0)
                   1948:                        fatal("%s: dup2() stdout failed", __func__);
                   1949:                if (devnull > STDERR_FILENO)
                   1950:                        close(devnull);
                   1951:        }
1.301     djm      1952:
1.342     djm      1953:        /*
                   1954:         * If requested and we are not interested in replies to remote
                   1955:         * forwarding requests, then let ssh continue in the background.
                   1956:         */
1.344     djm      1957:        if (fork_after_authentication_flag) {
                   1958:                if (options.exit_on_forward_failure &&
                   1959:                    options.num_remote_forwards > 0) {
                   1960:                        debug("deferring postauth fork until remote forward "
                   1961:                            "confirmation received");
                   1962:                } else
                   1963:                        fork_postauth();
1.318     djm      1964:        }
1.31      markus   1965:
1.463     djm      1966:        return client_loop(ssh, tty_flag, tty_flag ?
1.119     stevesk  1967:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1968: }
                   1969:
1.426     djm      1970: /* Loads all IdentityFile and CertificateFile keys */
1.126     itojun   1971: static void
1.466     djm      1972: load_public_identity_files(struct passwd *pw)
1.104     markus   1973: {
1.466     djm      1974:        char *filename, *cp;
1.460     markus   1975:        struct sshkey *public;
1.426     djm      1976:        int i;
                   1977:        u_int n_ids, n_certs;
1.335     djm      1978:        char *identity_files[SSH_MAX_IDENTITY_FILES];
1.460     markus   1979:        struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
1.484     djm      1980:        int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
1.426     djm      1981:        char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
                   1982:        struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1.484     djm      1983:        int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
1.333     markus   1984: #ifdef ENABLE_PKCS11
1.460     markus   1985:        struct sshkey **keys;
1.333     markus   1986:        int nkeys;
1.335     djm      1987: #endif /* PKCS11 */
1.104     markus   1988:
1.426     djm      1989:        n_ids = n_certs = 0;
1.398     tedu     1990:        memset(identity_files, 0, sizeof(identity_files));
                   1991:        memset(identity_keys, 0, sizeof(identity_keys));
1.484     djm      1992:        memset(identity_file_userprovided, 0,
                   1993:            sizeof(identity_file_userprovided));
1.426     djm      1994:        memset(certificate_files, 0, sizeof(certificate_files));
                   1995:        memset(certificates, 0, sizeof(certificates));
1.484     djm      1996:        memset(certificate_file_userprovided, 0,
                   1997:            sizeof(certificate_file_userprovided));
1.335     djm      1998:
                   1999: #ifdef ENABLE_PKCS11
1.333     markus   2000:        if (options.pkcs11_provider != NULL &&
1.167     markus   2001:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   2002:            (pkcs11_init(!options.batch_mode) == 0) &&
                   2003:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
                   2004:            &keys)) > 0) {
                   2005:                for (i = 0; i < nkeys; i++) {
1.335     djm      2006:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1.483     markus   2007:                                sshkey_free(keys[i]);
1.335     djm      2008:                                continue;
                   2009:                        }
                   2010:                        identity_keys[n_ids] = keys[i];
                   2011:                        identity_files[n_ids] =
1.333     markus   2012:                            xstrdup(options.pkcs11_provider); /* XXX */
1.335     djm      2013:                        n_ids++;
1.167     markus   2014:                }
1.378     djm      2015:                free(keys);
1.127     markus   2016:        }
1.333     markus   2017: #endif /* ENABLE_PKCS11 */
1.335     djm      2018:        for (i = 0; i < options.num_identity_files; i++) {
1.373     djm      2019:                if (n_ids >= SSH_MAX_IDENTITY_FILES ||
                   2020:                    strcasecmp(options.identity_files[i], "none") == 0) {
1.378     djm      2021:                        free(options.identity_files[i]);
1.426     djm      2022:                        options.identity_files[i] = NULL;
1.335     djm      2023:                        continue;
                   2024:                }
1.490     dtucker  2025:                cp = tilde_expand_filename(options.identity_files[i], getuid());
1.466     djm      2026:                filename = percent_expand(cp, "d", pw->pw_dir,
                   2027:                    "u", pw->pw_name, "l", thishost, "h", host,
1.275     djm      2028:                    "r", options.user, (char *)NULL);
1.378     djm      2029:                free(cp);
1.483     markus   2030:                check_load(sshkey_load_public(filename, &public, NULL),
                   2031:                    filename, "pubkey");
1.131     millert  2032:                debug("identity file %s type %d", filename,
                   2033:                    public ? public->type : -1);
1.378     djm      2034:                free(options.identity_files[i]);
1.335     djm      2035:                identity_files[n_ids] = filename;
                   2036:                identity_keys[n_ids] = public;
1.484     djm      2037:                identity_file_userprovided[n_ids] =
                   2038:                    options.identity_file_userprovided[i];
1.335     djm      2039:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
                   2040:                        continue;
                   2041:
1.426     djm      2042:                /*
                   2043:                 * If no certificates have been explicitly listed then try
                   2044:                 * to add the default certificate variant too.
                   2045:                 */
                   2046:                if (options.num_certificate_files != 0)
                   2047:                        continue;
1.335     djm      2048:                xasprintf(&cp, "%s-cert", filename);
1.483     markus   2049:                check_load(sshkey_load_public(cp, &public, NULL),
                   2050:                    filename, "pubkey");
1.335     djm      2051:                debug("identity file %s type %d", cp,
                   2052:                    public ? public->type : -1);
                   2053:                if (public == NULL) {
1.378     djm      2054:                        free(cp);
1.335     djm      2055:                        continue;
                   2056:                }
1.483     markus   2057:                if (!sshkey_is_cert(public)) {
1.335     djm      2058:                        debug("%s: key %s type %s is not a certificate",
1.483     markus   2059:                            __func__, cp, sshkey_type(public));
                   2060:                        sshkey_free(public);
1.378     djm      2061:                        free(cp);
1.335     djm      2062:                        continue;
                   2063:                }
1.448     djm      2064:                /* NB. leave filename pointing to private key */
                   2065:                identity_files[n_ids] = xstrdup(filename);
1.335     djm      2066:                identity_keys[n_ids] = public;
1.484     djm      2067:                identity_file_userprovided[n_ids] =
                   2068:                    options.identity_file_userprovided[i];
1.335     djm      2069:                n_ids++;
                   2070:        }
1.426     djm      2071:
                   2072:        if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
                   2073:                fatal("%s: too many certificates", __func__);
                   2074:        for (i = 0; i < options.num_certificate_files; i++) {
                   2075:                cp = tilde_expand_filename(options.certificate_files[i],
1.490     dtucker  2076:                    getuid());
1.479     djm      2077:                filename = percent_expand(cp,
                   2078:                    "d", pw->pw_dir,
                   2079:                    "h", host,
1.481     djm      2080:                    "i", uidstr,
1.479     djm      2081:                    "l", thishost,
                   2082:                    "r", options.user,
                   2083:                    "u", pw->pw_name,
                   2084:                    (char *)NULL);
1.426     djm      2085:                free(cp);
                   2086:
1.483     markus   2087:                check_load(sshkey_load_public(filename, &public, NULL),
                   2088:                    filename, "certificate");
1.426     djm      2089:                debug("certificate file %s type %d", filename,
                   2090:                    public ? public->type : -1);
                   2091:                free(options.certificate_files[i]);
                   2092:                options.certificate_files[i] = NULL;
                   2093:                if (public == NULL) {
                   2094:                        free(filename);
                   2095:                        continue;
                   2096:                }
1.483     markus   2097:                if (!sshkey_is_cert(public)) {
1.426     djm      2098:                        debug("%s: key %s type %s is not a certificate",
1.483     markus   2099:                            __func__, filename, sshkey_type(public));
                   2100:                        sshkey_free(public);
1.426     djm      2101:                        free(filename);
                   2102:                        continue;
                   2103:                }
                   2104:                certificate_files[n_certs] = filename;
                   2105:                certificates[n_certs] = public;
1.484     djm      2106:                certificate_file_userprovided[n_certs] =
                   2107:                    options.certificate_file_userprovided[i];
1.426     djm      2108:                ++n_certs;
                   2109:        }
                   2110:
1.335     djm      2111:        options.num_identity_files = n_ids;
                   2112:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
                   2113:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1.484     djm      2114:        memcpy(options.identity_file_userprovided,
                   2115:            identity_file_userprovided, sizeof(identity_file_userprovided));
1.426     djm      2116:
                   2117:        options.num_certificate_files = n_certs;
                   2118:        memcpy(options.certificate_files,
                   2119:            certificate_files, sizeof(certificate_files));
                   2120:        memcpy(options.certificates, certificates, sizeof(certificates));
1.484     djm      2121:        memcpy(options.certificate_file_userprovided,
                   2122:            certificate_file_userprovided,
                   2123:            sizeof(certificate_file_userprovided));
1.214     djm      2124: }
1.352     djm      2125:
                   2126: static void
                   2127: main_sigchld_handler(int sig)
                   2128: {
                   2129:        int save_errno = errno;
                   2130:        pid_t pid;
                   2131:        int status;
                   2132:
                   2133:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                   2134:            (pid < 0 && errno == EINTR))
                   2135:                ;
                   2136:        errno = save_errno;
                   2137: }