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

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