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

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