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

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