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

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