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

1.384   ! djm         1: /* $OpenBSD: ssh.c,v 1.383 2013/10/14 23:28:23 djm Exp $ */
1.1       deraadt     2: /*
1.32      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
                      6:  * Ssh client program.  This program can be used to log into a remote machine.
                      7:  * The software supports strong authentication, encryption, and forwarding
                      8:  * of X11, TCP/IP, and authentication connections.
                      9:  *
1.64      deraadt    10:  * As far as I am concerned, the code I have written for this software
                     11:  * can be used freely for any purpose.  Any derived versions of this
                     12:  * software must be clearly marked as such, and if the derived work is
                     13:  * incompatible with the protocol description in the RFC file, it must be
                     14:  * called by a name other than "ssh" or "Secure Shell".
                     15:  *
                     16:  * Copyright (c) 1999 Niels Provos.  All rights reserved.
1.202     markus     17:  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
1.64      deraadt    18:  *
                     19:  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
                     20:  * in Canada (German citizen).
                     21:  *
                     22:  * Redistribution and use in source and binary forms, with or without
                     23:  * modification, are permitted provided that the following conditions
                     24:  * are met:
                     25:  * 1. Redistributions of source code must retain the above copyright
                     26:  *    notice, this list of conditions and the following disclaimer.
                     27:  * 2. Redistributions in binary form must reproduce the above copyright
                     28:  *    notice, this list of conditions and the following disclaimer in the
                     29:  *    documentation and/or other materials provided with the distribution.
                     30:  *
                     31:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     32:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     33:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     34:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     35:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     36:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     37:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     38:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     39:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     40:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.32      deraadt    41:  */
1.1       deraadt    42:
1.293     deraadt    43: #include <sys/types.h>
1.312     djm        44: #include <sys/ioctl.h>
1.326     dtucker    45: #include <sys/param.h>
1.312     djm        46: #include <sys/queue.h>
1.259     stevesk    47: #include <sys/resource.h>
1.280     stevesk    48: #include <sys/socket.h>
1.264     stevesk    49: #include <sys/stat.h>
1.312     djm        50: #include <sys/types.h>
                     51: #include <sys/time.h>
1.352     djm        52: #include <sys/wait.h>
1.258     stevesk    53:
1.265     stevesk    54: #include <ctype.h>
1.285     stevesk    55: #include <errno.h>
1.281     stevesk    56: #include <fcntl.h>
1.286     stevesk    57: #include <netdb.h>
1.258     stevesk    58: #include <paths.h>
1.279     stevesk    59: #include <pwd.h>
1.263     stevesk    60: #include <signal.h>
1.287     stevesk    61: #include <stddef.h>
1.291     stevesk    62: #include <stdio.h>
1.290     stevesk    63: #include <stdlib.h>
1.289     stevesk    64: #include <string.h>
1.288     stevesk    65: #include <unistd.h>
1.49      markus     66:
                     67: #include <openssl/evp.h>
1.72      markus     68: #include <openssl/err.h>
1.1       deraadt    69:
1.293     deraadt    70: #include "xmalloc.h"
1.84      markus     71: #include "ssh.h"
                     72: #include "ssh1.h"
                     73: #include "ssh2.h"
1.341     djm        74: #include "canohost.h"
1.84      markus     75: #include "compat.h"
                     76: #include "cipher.h"
1.1       deraadt    77: #include "packet.h"
                     78: #include "buffer.h"
1.123     markus     79: #include "channels.h"
1.49      markus     80: #include "key.h"
1.58      markus     81: #include "authfd.h"
1.49      markus     82: #include "authfile.h"
1.83      markus     83: #include "pathnames.h"
1.214     djm        84: #include "dispatch.h"
1.81      markus     85: #include "clientloop.h"
1.84      markus     86: #include "log.h"
                     87: #include "readconf.h"
                     88: #include "sshconnect.h"
                     89: #include "misc.h"
1.95      markus     90: #include "kex.h"
                     91: #include "mac.h"
1.213     deraadt    92: #include "sshpty.h"
1.212     djm        93: #include "match.h"
1.214     djm        94: #include "msg.h"
1.225     dtucker    95: #include "uidswap.h"
1.327     andreas    96: #include "roaming.h"
1.278     stevesk    97: #include "version.h"
1.49      markus     98:
1.333     markus     99: #ifdef ENABLE_PKCS11
                    100: #include "ssh-pkcs11.h"
1.137     jakob     101: #endif
1.127     markus    102:
1.49      markus    103: extern char *__progname;
1.1       deraadt   104:
1.316     djm       105: /* Flag indicating whether debug mode is on.  May be set on the command line. */
1.1       deraadt   106: int debug_flag = 0;
                    107:
1.359     djm       108: /* Flag indicating whether a tty should be requested */
1.1       deraadt   109: int tty_flag = 0;
                    110:
1.45      markus    111: /* don't exec a shell */
                    112: int no_shell_flag = 0;
                    113:
1.33      markus    114: /*
                    115:  * Flag indicating that nothing should be read from stdin.  This can be set
                    116:  * on the command line.
                    117:  */
1.1       deraadt   118: int stdin_null_flag = 0;
                    119:
1.33      markus    120: /*
1.344     djm       121:  * Flag indicating that the current process should be backgrounded and
                    122:  * a new slave launched in the foreground for ControlPersist.
                    123:  */
                    124: int need_controlpersist_detach = 0;
                    125:
                    126: /* Copies of flags for ControlPersist foreground slave */
1.359     djm       127: int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
1.344     djm       128:
                    129: /*
1.33      markus    130:  * Flag indicating that ssh should fork after authentication.  This is useful
1.172     deraadt   131:  * so that the passphrase can be entered manually, and then ssh goes to the
1.33      markus    132:  * background.
                    133:  */
1.1       deraadt   134: int fork_after_authentication_flag = 0;
                    135:
1.331     dtucker   136: /* forward stdio to remote host and port */
                    137: char *stdio_forward_host = NULL;
                    138: int stdio_forward_port = 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.186     djm       179:
1.1       deraadt   180: /* Prints a help message to the user.  This function never returns. */
                    181:
1.126     itojun    182: static void
1.93      itojun    183: usage(void)
1.1       deraadt   184: {
1.208     markus    185:        fprintf(stderr,
1.321     jmc       186: "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
1.375     dtucker   187: "           [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
                    188: "           [-F configfile] [-I pkcs11] [-i identity_file]\n"
1.377     djm       189: "           [-L [bind_address:]port:host:hostport] [-Q protocol_feature]\n"
1.232     djm       190: "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
1.233     jmc       191: "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
1.331     dtucker   192: "           [-W host:port] [-w local_tun[:remote_tun]]\n"
                    193: "           [user@]hostname [command]\n"
1.208     markus    194:        );
1.257     dtucker   195:        exit(255);
1.1       deraadt   196: }
                    197:
1.126     itojun    198: static int ssh_session(void);
                    199: static int ssh_session2(void);
                    200: static void load_public_identity_files(void);
1.352     djm       201: static void main_sigchld_handler(int);
1.312     djm       202:
                    203: /* from muxclient.c */
                    204: void muxclient(const char *);
                    205: void muxserver_listen(void);
1.45      markus    206:
1.361     djm       207: /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
                    208: static void
                    209: tilde_expand_paths(char **paths, u_int num_paths)
                    210: {
                    211:        u_int i;
                    212:        char *cp;
                    213:
                    214:        for (i = 0; i < num_paths; i++) {
                    215:                cp = tilde_expand_filename(paths[i], original_real_uid);
1.378     djm       216:                free(paths[i]);
1.361     djm       217:                paths[i] = cp;
                    218:        }
                    219: }
                    220:
1.32      deraadt   221: /*
                    222:  * Main program for the ssh client.
                    223:  */
1.2       provos    224: int
                    225: main(int ac, char **av)
1.1       deraadt   226: {
1.326     dtucker   227:        int i, r, opt, exit_status, use_syslog;
1.375     dtucker   228:        char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
1.358     djm       229:        char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
1.31      markus    230:        struct stat st;
1.98      markus    231:        struct passwd *pw;
1.382     djm       232:        int timeout_ms;
1.144     stevesk   233:        extern int optind, optreset;
                    234:        extern char *optarg;
1.232     djm       235:        Forward fwd;
1.250     djm       236:
                    237:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    238:        sanitise_stdfd();
1.31      markus    239:
1.33      markus    240:        /*
1.346     djm       241:         * Discard other fds that are hanging around. These can cause problem
                    242:         * with backgrounded ssh processes started by ControlPersist.
                    243:         */
                    244:        closefrom(STDERR_FILENO + 1);
                    245:
                    246:        /*
1.33      markus    247:         * Save the original real uid.  It will be needed later (uid-swapping
                    248:         * may clobber the real uid).
                    249:         */
1.31      markus    250:        original_real_uid = getuid();
                    251:        original_effective_uid = geteuid();
                    252:
1.184     stevesk   253:        /*
                    254:         * Use uid-swapping to give up root privileges for the duration of
                    255:         * option processing.  We will re-instantiate the rights when we are
                    256:         * ready to create the privileged port, and will permanently drop
                    257:         * them when the port has been created (actually, when the connection
                    258:         * has been made, as we may need to create the port several times).
                    259:         */
                    260:        PRIV_END;
                    261:
1.31      markus    262:        /* If we are installed setuid root be careful to not drop core. */
                    263:        if (original_real_uid != original_effective_uid) {
                    264:                struct rlimit rlim;
                    265:                rlim.rlim_cur = rlim.rlim_max = 0;
                    266:                if (setrlimit(RLIMIT_CORE, &rlim) < 0)
                    267:                        fatal("setrlimit failed: %.100s", strerror(errno));
1.1       deraadt   268:        }
1.107     markus    269:        /* Get user data. */
                    270:        pw = getpwuid(original_real_uid);
                    271:        if (!pw) {
1.380     djm       272:                logit("No user exists for uid %lu", (u_long)original_real_uid);
1.257     dtucker   273:                exit(255);
1.107     markus    274:        }
                    275:        /* Take a copy of the returned structure. */
                    276:        pw = pwcopy(pw);
1.31      markus    277:
1.33      markus    278:        /*
                    279:         * Set our umask to something reasonable, as some files are created
                    280:         * with the default umask.  This will make them world-readable but
                    281:         * writable only by the owner, which is ok for all files for which we
                    282:         * don't set the modes explicitly.
                    283:         */
1.31      markus    284:        umask(022);
                    285:
1.316     djm       286:        /*
                    287:         * Initialize option structure to indicate that no values have been
                    288:         * set.
                    289:         */
1.31      markus    290:        initialize_options(&options);
                    291:
                    292:        /* Parse command-line arguments. */
                    293:        host = NULL;
1.320     djm       294:        use_syslog = 0;
1.375     dtucker   295:        logfile = NULL;
1.325     markus    296:        argv0 = av[0];
1.31      markus    297:
1.266     djm       298:  again:
1.316     djm       299:        while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
1.376     djm       300:            "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
1.31      markus    301:                switch (opt) {
1.91      jakob     302:                case '1':
                    303:                        options.protocol = SSH_PROTO_1;
                    304:                        break;
1.47      markus    305:                case '2':
                    306:                        options.protocol = SSH_PROTO_2;
                    307:                        break;
1.37      markus    308:                case '4':
1.196     djm       309:                        options.address_family = AF_INET;
1.37      markus    310:                        break;
                    311:                case '6':
1.196     djm       312:                        options.address_family = AF_INET6;
1.37      markus    313:                        break;
1.31      markus    314:                case 'n':
                    315:                        stdin_null_flag = 1;
                    316:                        break;
                    317:                case 'f':
                    318:                        fork_after_authentication_flag = 1;
                    319:                        stdin_null_flag = 1;
                    320:                        break;
                    321:                case 'x':
                    322:                        options.forward_x11 = 0;
                    323:                        break;
                    324:                case 'X':
                    325:                        options.forward_x11 = 1;
                    326:                        break;
1.320     djm       327:                case 'y':
                    328:                        use_syslog = 1;
                    329:                        break;
1.375     dtucker   330:                case 'E':
                    331:                        logfile = xstrdup(optarg);
                    332:                        break;
1.202     markus    333:                case 'Y':
                    334:                        options.forward_x11 = 1;
                    335:                        options.forward_x11_trusted = 1;
                    336:                        break;
1.31      markus    337:                case 'g':
                    338:                        options.gateway_ports = 1;
                    339:                        break;
1.229     djm       340:                case 'O':
1.332     djm       341:                        if (stdio_forward_host != NULL)
                    342:                                fatal("Cannot specify multiplexing "
                    343:                                    "command with -W");
                    344:                        else if (muxclient_command != 0)
                    345:                                fatal("Multiplexing command already specified");
1.229     djm       346:                        if (strcmp(optarg, "check") == 0)
1.312     djm       347:                                muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
1.338     markus    348:                        else if (strcmp(optarg, "forward") == 0)
                    349:                                muxclient_command = SSHMUX_COMMAND_FORWARD;
1.229     djm       350:                        else if (strcmp(optarg, "exit") == 0)
1.312     djm       351:                                muxclient_command = SSHMUX_COMMAND_TERMINATE;
1.357     djm       352:                        else if (strcmp(optarg, "stop") == 0)
                    353:                                muxclient_command = SSHMUX_COMMAND_STOP;
1.365     djm       354:                        else if (strcmp(optarg, "cancel") == 0)
                    355:                                muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
1.229     djm       356:                        else
                    357:                                fatal("Invalid multiplex command.");
                    358:                        break;
1.183     stevesk   359:                case 'P':       /* deprecated */
1.31      markus    360:                        options.use_privileged_port = 0;
1.376     djm       361:                        break;
                    362:                case 'Q':       /* deprecated */
                    363:                        cp = NULL;
                    364:                        if (strcasecmp(optarg, "cipher") == 0)
                    365:                                cp = cipher_alg_list();
                    366:                        else if (strcasecmp(optarg, "mac") == 0)
                    367:                                cp = mac_alg_list();
                    368:                        else if (strcasecmp(optarg, "kex") == 0)
                    369:                                cp = kex_alg_list();
                    370:                        else if (strcasecmp(optarg, "key") == 0)
                    371:                                cp = key_alg_list();
                    372:                        if (cp == NULL)
                    373:                                fatal("Unsupported query \"%s\"", optarg);
                    374:                        printf("%s\n", cp);
                    375:                        free(cp);
                    376:                        exit(0);
1.31      markus    377:                        break;
                    378:                case 'a':
                    379:                        options.forward_agent = 0;
1.53      markus    380:                        break;
                    381:                case 'A':
                    382:                        options.forward_agent = 1;
1.31      markus    383:                        break;
                    384:                case 'k':
1.204     dtucker   385:                        options.gss_deleg_creds = 0;
1.297     djm       386:                        break;
                    387:                case 'K':
                    388:                        options.gss_authentication = 1;
                    389:                        options.gss_deleg_creds = 1;
1.31      markus    390:                        break;
                    391:                case 'i':
                    392:                        if (stat(optarg, &st) < 0) {
1.128     fgsch     393:                                fprintf(stderr, "Warning: Identity file %s "
1.231     otto      394:                                    "not accessible: %s.\n", optarg,
                    395:                                    strerror(errno));
1.31      markus    396:                                break;
                    397:                        }
1.371     dtucker   398:                        add_identity_file(&options, NULL, optarg, 1);
1.31      markus    399:                        break;
1.127     markus    400:                case 'I':
1.333     markus    401: #ifdef ENABLE_PKCS11
                    402:                        options.pkcs11_provider = xstrdup(optarg);
1.137     jakob     403: #else
1.333     markus    404:                        fprintf(stderr, "no support for PKCS#11.\n");
1.137     jakob     405: #endif
1.127     markus    406:                        break;
1.31      markus    407:                case 't':
1.359     djm       408:                        if (options.request_tty == REQUEST_TTY_YES)
                    409:                                options.request_tty = REQUEST_TTY_FORCE;
                    410:                        else
                    411:                                options.request_tty = REQUEST_TTY_YES;
1.31      markus    412:                        break;
                    413:                case 'v':
1.197     markus    414:                        if (debug_flag == 0) {
1.66      markus    415:                                debug_flag = 1;
                    416:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    417:                        } else {
                    418:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3)
                    419:                                        options.log_level++;
                    420:                        }
1.375     dtucker   421:                        break;
1.31      markus    422:                case 'V':
1.209     markus    423:                        fprintf(stderr, "%s, %s\n",
                    424:                            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.31      markus    425:                        if (opt == 'V')
                    426:                                exit(0);
                    427:                        break;
1.255     reyk      428:                case 'w':
1.256     reyk      429:                        if (options.tun_open == -1)
                    430:                                options.tun_open = SSH_TUNMODE_DEFAULT;
1.255     reyk      431:                        options.tun_local = a2tun(optarg, &options.tun_remote);
1.256     reyk      432:                        if (options.tun_local == SSH_TUNID_ERR) {
1.316     djm       433:                                fprintf(stderr,
                    434:                                    "Bad tun device '%s'\n", optarg);
1.257     dtucker   435:                                exit(255);
1.255     reyk      436:                        }
                    437:                        break;
1.331     dtucker   438:                case 'W':
1.332     djm       439:                        if (stdio_forward_host != NULL)
                    440:                                fatal("stdio forward already specified");
                    441:                        if (muxclient_command != 0)
                    442:                                fatal("Cannot specify stdio forward with -O");
1.331     dtucker   443:                        if (parse_forward(&fwd, optarg, 1, 0)) {
                    444:                                stdio_forward_host = fwd.listen_host;
                    445:                                stdio_forward_port = fwd.listen_port;
1.378     djm       446:                                free(fwd.connect_host);
1.331     dtucker   447:                        } else {
                    448:                                fprintf(stderr,
                    449:                                    "Bad stdio forwarding specification '%s'\n",
                    450:                                    optarg);
                    451:                                exit(255);
                    452:                        }
1.359     djm       453:                        options.request_tty = REQUEST_TTY_NO;
1.331     dtucker   454:                        no_shell_flag = 1;
                    455:                        options.clear_forwardings = 1;
                    456:                        options.exit_on_forward_failure = 1;
                    457:                        break;
1.31      markus    458:                case 'q':
                    459:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    460:                        break;
                    461:                case 'e':
                    462:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     463:                            (u_char) optarg[1] >= 64 &&
                    464:                            (u_char) optarg[1] < 128)
1.78      markus    465:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    466:                        else if (strlen(optarg) == 1)
1.78      markus    467:                                options.escape_char = (u_char) optarg[0];
1.31      markus    468:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   469:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    470:                        else {
1.128     fgsch     471:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    472:                                    optarg);
1.257     dtucker   473:                                exit(255);
1.31      markus    474:                        }
                    475:                        break;
                    476:                case 'c':
1.49      markus    477:                        if (ciphers_valid(optarg)) {
                    478:                                /* SSH2 only */
                    479:                                options.ciphers = xstrdup(optarg);
1.224     markus    480:                                options.cipher = SSH_CIPHER_INVALID;
1.49      markus    481:                        } else {
                    482:                                /* SSH1 only */
1.74      markus    483:                                options.cipher = cipher_number(optarg);
                    484:                                if (options.cipher == -1) {
1.128     fgsch     485:                                        fprintf(stderr,
                    486:                                            "Unknown cipher type '%s'\n",
                    487:                                            optarg);
1.257     dtucker   488:                                        exit(255);
1.49      markus    489:                                }
1.128     fgsch     490:                                if (options.cipher == SSH_CIPHER_3DES)
1.74      markus    491:                                        options.ciphers = "3des-cbc";
1.128     fgsch     492:                                else if (options.cipher == SSH_CIPHER_BLOWFISH)
1.74      markus    493:                                        options.ciphers = "blowfish-cbc";
1.128     fgsch     494:                                else
1.74      markus    495:                                        options.ciphers = (char *)-1;
1.95      markus    496:                        }
                    497:                        break;
                    498:                case 'm':
                    499:                        if (mac_valid(optarg))
                    500:                                options.macs = xstrdup(optarg);
                    501:                        else {
1.128     fgsch     502:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    503:                                    optarg);
1.257     dtucker   504:                                exit(255);
1.31      markus    505:                        }
                    506:                        break;
1.214     djm       507:                case 'M':
1.242     djm       508:                        if (options.control_master == SSHCTL_MASTER_YES)
                    509:                                options.control_master = SSHCTL_MASTER_ASK;
                    510:                        else
                    511:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       512:                        break;
1.31      markus    513:                case 'p':
1.113     stevesk   514:                        options.port = a2port(optarg);
1.323     djm       515:                        if (options.port <= 0) {
1.109     markus    516:                                fprintf(stderr, "Bad port '%s'\n", optarg);
1.257     dtucker   517:                                exit(255);
1.109     markus    518:                        }
1.31      markus    519:                        break;
                    520:                case 'l':
                    521:                        options.user = optarg;
                    522:                        break;
1.141     stevesk   523:
                    524:                case 'L':
1.324     djm       525:                        if (parse_forward(&fwd, optarg, 0, 0))
1.232     djm       526:                                add_local_forward(&options, &fwd);
                    527:                        else {
1.128     fgsch     528:                                fprintf(stderr,
1.232     djm       529:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     530:                                    optarg);
1.257     dtucker   531:                                exit(255);
1.31      markus    532:                        }
1.232     djm       533:                        break;
                    534:
                    535:                case 'R':
1.324     djm       536:                        if (parse_forward(&fwd, optarg, 0, 1)) {
1.232     djm       537:                                add_remote_forward(&options, &fwd);
                    538:                        } else {
1.128     fgsch     539:                                fprintf(stderr,
1.232     djm       540:                                    "Bad remote forwarding specification "
                    541:                                    "'%s'\n", optarg);
1.257     dtucker   542:                                exit(255);
1.31      markus    543:                        }
                    544:                        break;
1.108     markus    545:
                    546:                case 'D':
1.324     djm       547:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.322     stevesk   548:                                add_local_forward(&options, &fwd);
1.232     djm       549:                        } else {
1.322     stevesk   550:                                fprintf(stderr,
                    551:                                    "Bad dynamic forwarding specification "
                    552:                                    "'%s'\n", optarg);
1.257     dtucker   553:                                exit(255);
1.109     markus    554:                        }
1.108     markus    555:                        break;
                    556:
1.31      markus    557:                case 'C':
                    558:                        options.compression = 1;
                    559:                        break;
1.45      markus    560:                case 'N':
                    561:                        no_shell_flag = 1;
1.359     djm       562:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus    563:                        break;
                    564:                case 'T':
1.359     djm       565:                        options.request_tty = REQUEST_TTY_NO;
1.45      markus    566:                        break;
1.31      markus    567:                case 'o':
1.205     markus    568:                        line = xstrdup(optarg);
1.382     djm       569:                        if (process_config_line(&options, pw, host ? host : "",
                    570:                            line, "command-line", 0, NULL, SSHCONF_USERCONF)
1.372     dtucker   571:                            != 0)
1.257     dtucker   572:                                exit(255);
1.378     djm       573:                        free(line);
1.31      markus    574:                        break;
1.85      djm       575:                case 's':
                    576:                        subsystem_flag = 1;
1.117     markus    577:                        break;
1.214     djm       578:                case 'S':
                    579:                        if (options.control_path != NULL)
                    580:                                free(options.control_path);
                    581:                        options.control_path = xstrdup(optarg);
                    582:                        break;
1.117     markus    583:                case 'b':
                    584:                        options.bind_address = optarg;
1.85      djm       585:                        break;
1.139     markus    586:                case 'F':
                    587:                        config = optarg;
                    588:                        break;
1.31      markus    589:                default:
                    590:                        usage();
1.1       deraadt   591:                }
1.31      markus    592:        }
                    593:
1.128     fgsch     594:        ac -= optind;
                    595:        av += optind;
                    596:
1.329     guenther  597:        if (ac > 0 && !host) {
1.188     markus    598:                if (strrchr(*av, '@')) {
1.128     fgsch     599:                        p = xstrdup(*av);
1.188     markus    600:                        cp = strrchr(p, '@');
1.128     fgsch     601:                        if (cp == NULL || cp == p)
                    602:                                usage();
                    603:                        options.user = p;
                    604:                        *cp = '\0';
                    605:                        host = ++cp;
                    606:                } else
                    607:                        host = *av;
1.189     millert   608:                if (ac > 1) {
                    609:                        optind = optreset = 1;
1.128     fgsch     610:                        goto again;
                    611:                }
1.189     millert   612:                ac--, av++;
1.128     fgsch     613:        }
                    614:
1.31      markus    615:        /* Check that we got a host name. */
                    616:        if (!host)
                    617:                usage();
                    618:
1.350     djm       619:        OpenSSL_add_all_algorithms();
1.72      markus    620:        ERR_load_crypto_strings();
1.31      markus    621:
                    622:        /* Initialize the command to execute on remote host. */
                    623:        buffer_init(&command);
1.1       deraadt   624:
1.33      markus    625:        /*
                    626:         * Save the command to execute on the remote host in a buffer. There
                    627:         * is no limit on the length of the command, except by the maximum
                    628:         * packet size.  Also sets the tty flag if there is no command.
                    629:         */
1.128     fgsch     630:        if (!ac) {
1.31      markus    631:                /* No command specified - execute shell on a tty. */
1.85      djm       632:                if (subsystem_flag) {
1.128     fgsch     633:                        fprintf(stderr,
                    634:                            "You must specify a subsystem to invoke.\n");
1.85      djm       635:                        usage();
                    636:                }
1.31      markus    637:        } else {
1.128     fgsch     638:                /* A command has been specified.  Store it into the buffer. */
                    639:                for (i = 0; i < ac; i++) {
                    640:                        if (i)
1.31      markus    641:                                buffer_append(&command, " ", 1);
                    642:                        buffer_append(&command, av[i], strlen(av[i]));
                    643:                }
                    644:        }
                    645:
                    646:        /* Cannot fork to background if no command. */
1.316     djm       647:        if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
                    648:            !no_shell_flag)
                    649:                fatal("Cannot fork into background without a command "
                    650:                    "to execute.");
1.31      markus    651:
1.101     markus    652:        /*
                    653:         * Initialize "log" output.  Since we are the client all output
1.375     dtucker   654:         * goes to stderr unless otherwise specified by -y or -E.
1.101     markus    655:         */
1.375     dtucker   656:        if (use_syslog && logfile != NULL)
                    657:                fatal("Can't specify both -y and -E");
                    658:        if (logfile != NULL) {
                    659:                log_redirect_stderr_to(logfile);
1.378     djm       660:                free(logfile);
1.375     dtucker   661:        }
1.325     markus    662:        log_init(argv0,
1.316     djm       663:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1.320     djm       664:            SYSLOG_FACILITY_USER, !use_syslog);
1.375     dtucker   665:
                    666:        if (debug_flag)
                    667:                logit("%s, %s", SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.31      markus    668:
1.139     markus    669:        /*
                    670:         * Read per-user configuration file.  Ignore the system wide config
                    671:         * file if the user specifies a config file on the command line.
                    672:         */
                    673:        if (config != NULL) {
1.374     djm       674:                if (strcasecmp(config, "none") != 0 &&
1.382     djm       675:                    !read_config_file(config, pw, host, &options,
                    676:                    SSHCONF_USERCONF))
1.142     stevesk   677:                        fatal("Can't open user config file %.100s: "
                    678:                            "%.100s", config, strerror(errno));
1.295     stevesk   679:        } else {
1.326     dtucker   680:                r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
1.139     markus    681:                    _PATH_SSH_USER_CONFFILE);
1.326     dtucker   682:                if (r > 0 && (size_t)r < sizeof(buf))
1.382     djm       683:                        (void)read_config_file(buf, pw, host, &options,
1.372     dtucker   684:                             SSHCONF_CHECKPERM|SSHCONF_USERCONF);
1.139     markus    685:
1.364     djm       686:                /* Read systemwide configuration file after user config. */
1.382     djm       687:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
1.210     djm       688:                    &options, 0);
1.139     markus    689:        }
1.31      markus    690:
                    691:        /* Fill configuration defaults. */
                    692:        fill_default_options(&options);
                    693:
1.196     djm       694:        channel_set_af(options.address_family);
                    695:
1.383     djm       696:        /* Tidy and check options */
                    697:        if (options.host_key_alias != NULL)
                    698:                lowercase(options.host_key_alias);
                    699:        if (options.proxy_command != NULL &&
                    700:            strcmp(options.proxy_command, "-") == 0 &&
                    701:            options.proxy_use_fdpass)
                    702:                fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
                    703:
1.31      markus    704:        /* reinit */
1.325     markus    705:        log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1.370     djm       706:
                    707:        if (options.request_tty == REQUEST_TTY_YES ||
                    708:            options.request_tty == REQUEST_TTY_FORCE)
                    709:                tty_flag = 1;
                    710:
                    711:        /* Allocate a tty by default if no command specified. */
                    712:        if (buffer_len(&command) == 0)
                    713:                tty_flag = options.request_tty != REQUEST_TTY_NO;
                    714:
                    715:        /* Force no tty */
                    716:        if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
                    717:                tty_flag = 0;
                    718:        /* Do not allocate a tty if stdin is not a tty. */
                    719:        if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
                    720:            options.request_tty != REQUEST_TTY_FORCE) {
                    721:                if (tty_flag)
                    722:                        logit("Pseudo-terminal will not be allocated because "
                    723:                            "stdin is not a terminal.");
                    724:                tty_flag = 0;
                    725:        }
1.31      markus    726:
                    727:        if (options.user == NULL)
                    728:                options.user = xstrdup(pw->pw_name);
                    729:
1.317     dtucker   730:        /* Get default port if port has not been set. */
1.382     djm       731:        if (options.port == 0)
                    732:                options.port = default_ssh_port();
1.317     dtucker   733:
1.356     djm       734:        /* preserve host name given on command line for %n expansion */
                    735:        host_arg = host;
1.343     djm       736:        if (options.hostname != NULL) {
                    737:                host = percent_expand(options.hostname,
                    738:                    "h", host, (char *)NULL);
                    739:        }
                    740:
1.358     djm       741:        if (gethostname(thishost, sizeof(thishost)) == -1)
                    742:                fatal("gethostname: %s", strerror(errno));
                    743:        strlcpy(shorthost, thishost, sizeof(shorthost));
                    744:        shorthost[strcspn(thishost, ".")] = '\0';
                    745:        snprintf(portstr, sizeof(portstr), "%d", options.port);
                    746:
1.317     dtucker   747:        if (options.local_command != NULL) {
                    748:                debug3("expanding LocalCommand: %s", options.local_command);
                    749:                cp = options.local_command;
                    750:                options.local_command = percent_expand(cp, "d", pw->pw_dir,
1.356     djm       751:                    "h", host, "l", thishost, "n", host_arg, "r", options.user,
1.358     djm       752:                    "p", portstr, "u", pw->pw_name, "L", shorthost,
                    753:                    (char *)NULL);
1.317     dtucker   754:                debug3("expanded LocalCommand: %s", options.local_command);
1.378     djm       755:                free(cp);
1.304     dtucker   756:        }
1.31      markus    757:
1.214     djm       758:        if (options.control_path != NULL) {
1.241     djm       759:                cp = tilde_expand_filename(options.control_path,
                    760:                    original_real_uid);
1.378     djm       761:                free(options.control_path);
1.358     djm       762:                options.control_path = percent_expand(cp, "h", host,
                    763:                    "l", thishost, "n", host_arg, "r", options.user,
                    764:                    "p", portstr, "u", pw->pw_name, "L", shorthost,
                    765:                    (char *)NULL);
1.378     djm       766:                free(cp);
1.214     djm       767:        }
1.312     djm       768:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm       769:                fatal("No ControlPath specified for \"-O\" command");
1.242     djm       770:        if (options.control_path != NULL)
1.312     djm       771:                muxclient(options.control_path);
1.214     djm       772:
1.303     djm       773:        timeout_ms = options.connection_timeout * 1000;
                    774:
1.77      markus    775:        /* Open a connection to the remote host. */
1.203     djm       776:        if (ssh_connect(host, &hostaddr, options.port,
1.303     djm       777:            options.address_family, options.connection_attempts, &timeout_ms,
1.384   ! djm       778:            options.tcp_keep_alive,
1.177     markus    779:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    780:            options.proxy_command) != 0)
1.257     dtucker   781:                exit(255);
1.31      markus    782:
1.303     djm       783:        if (timeout_ms > 0)
                    784:                debug3("timeout: %d ms remain after connect", timeout_ms);
                    785:
1.33      markus    786:        /*
                    787:         * If we successfully made the connection, load the host private key
                    788:         * in case we will need it later for combined rsa-rhosts
                    789:         * authentication. This must be done before releasing extra
                    790:         * privileges, because the file is only readable by root.
1.174     markus    791:         * If we cannot access the private keys, load the public keys
                    792:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    793:         */
1.112     markus    794:        sensitive_data.nkeys = 0;
                    795:        sensitive_data.keys = NULL;
1.173     markus    796:        sensitive_data.external_keysign = 0;
1.178     markus    797:        if (options.rhosts_rsa_authentication ||
                    798:            options.hostbased_authentication) {
1.349     djm       799:                sensitive_data.nkeys = 7;
1.274     deraadt   800:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180     deraadt   801:                    sizeof(Key));
1.177     markus    802:
                    803:                PRIV_START;
1.112     markus    804:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276     dtucker   805:                    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.345     djm       806:                sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
                    807:                    _PATH_HOST_DSA_KEY_FILE, "", NULL);
1.349     djm       808:                sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
                    809:                    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
                    810:                sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1.345     djm       811:                    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1.349     djm       812:                sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
1.276     dtucker   813:                    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.349     djm       814:                sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
                    815:                    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
                    816:                sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
1.276     dtucker   817:                    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.177     markus    818:                PRIV_END;
1.173     markus    819:
1.181     markus    820:                if (options.hostbased_authentication == 1 &&
                    821:                    sensitive_data.keys[0] == NULL &&
1.349     djm       822:                    sensitive_data.keys[4] == NULL &&
                    823:                    sensitive_data.keys[5] == NULL &&
                    824:                    sensitive_data.keys[6] == NULL) {
1.345     djm       825:                        sensitive_data.keys[1] = key_load_cert(
                    826:                            _PATH_HOST_DSA_KEY_FILE);
                    827:                        sensitive_data.keys[2] = key_load_cert(
1.349     djm       828:                            _PATH_HOST_ECDSA_KEY_FILE);
                    829:                        sensitive_data.keys[3] = key_load_cert(
1.345     djm       830:                            _PATH_HOST_RSA_KEY_FILE);
1.349     djm       831:                        sensitive_data.keys[4] = key_load_public(
1.173     markus    832:                            _PATH_HOST_DSA_KEY_FILE, NULL);
1.349     djm       833:                        sensitive_data.keys[5] = key_load_public(
                    834:                            _PATH_HOST_ECDSA_KEY_FILE, NULL);
                    835:                        sensitive_data.keys[6] = key_load_public(
1.173     markus    836:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    837:                        sensitive_data.external_keysign = 1;
                    838:                }
1.31      markus    839:        }
1.33      markus    840:        /*
                    841:         * Get rid of any extra privileges that we may have.  We will no
                    842:         * longer need them.  Also, extra privileges could make it very hard
                    843:         * to read identity files and other non-world-readable files from the
                    844:         * user's home directory if it happens to be on a NFS volume where
                    845:         * root is mapped to nobody.
                    846:         */
1.225     dtucker   847:        if (original_effective_uid == 0) {
                    848:                PRIV_START;
                    849:                permanently_set_uid(pw);
                    850:        }
1.31      markus    851:
1.33      markus    852:        /*
                    853:         * Now that we are back to our own permissions, create ~/.ssh
1.254     djm       854:         * directory if it doesn't already exist.
1.33      markus    855:         */
1.367     djm       856:        if (config == NULL) {
                    857:                r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
                    858:                    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
                    859:                if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
                    860:                        if (mkdir(buf, 0700) < 0)
                    861:                                error("Could not create directory '%.200s'.",
                    862:                                    buf);
                    863:        }
1.31      markus    864:
1.104     markus    865:        /* load options.identity_files */
                    866:        load_public_identity_files();
                    867:
                    868:        /* Expand ~ in known host file names. */
1.361     djm       869:        tilde_expand_paths(options.system_hostfiles,
                    870:            options.num_system_hostfiles);
                    871:        tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1.149     markus    872:
                    873:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.352     djm       874:        signal(SIGCHLD, main_sigchld_handler);
1.31      markus    875:
1.316     djm       876:        /* Log into the remote system.  Never returns if the login fails. */
1.303     djm       877:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1.355     djm       878:            options.port, pw, timeout_ms);
1.339     djm       879:
                    880:        if (packet_connection_is_on_socket()) {
                    881:                verbose("Authenticated to %s ([%s]:%d).", host,
                    882:                    get_remote_ipaddr(), get_remote_port());
                    883:        } else {
                    884:                verbose("Authenticated to %s (via proxy).", host);
                    885:        }
1.31      markus    886:
1.112     markus    887:        /* We no longer need the private host keys.  Clear them now. */
                    888:        if (sensitive_data.nkeys != 0) {
                    889:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    890:                        if (sensitive_data.keys[i] != NULL) {
                    891:                                /* Destroys contents safely */
                    892:                                debug3("clear hostkey %d", i);
                    893:                                key_free(sensitive_data.keys[i]);
                    894:                                sensitive_data.keys[i] = NULL;
                    895:                        }
                    896:                }
1.378     djm       897:                free(sensitive_data.keys);
1.134     markus    898:        }
                    899:        for (i = 0; i < options.num_identity_files; i++) {
1.378     djm       900:                free(options.identity_files[i]);
                    901:                options.identity_files[i] = NULL;
1.134     markus    902:                if (options.identity_keys[i]) {
                    903:                        key_free(options.identity_keys[i]);
                    904:                        options.identity_keys[i] = NULL;
                    905:                }
1.112     markus    906:        }
1.31      markus    907:
1.45      markus    908:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    909:        packet_close();
1.186     djm       910:
1.312     djm       911:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm       912:                unlink(options.control_path);
                    913:
1.353     djm       914:        /* Kill ProxyCommand if it is running. */
                    915:        ssh_kill_proxy_command();
1.186     djm       916:
1.45      markus    917:        return exit_status;
                    918: }
                    919:
1.344     djm       920: static void
                    921: control_persist_detach(void)
                    922: {
                    923:        pid_t pid;
1.346     djm       924:        int devnull;
1.344     djm       925:
                    926:        debug("%s: backgrounding master process", __func__);
                    927:
                    928:        /*
                    929:         * master (current process) into the background, and make the
                    930:         * foreground process a client of the backgrounded master.
                    931:         */
                    932:        switch ((pid = fork())) {
                    933:        case -1:
                    934:                fatal("%s: fork: %s", __func__, strerror(errno));
                    935:        case 0:
                    936:                /* Child: master process continues mainloop */
                    937:                break;
                    938:        default:
                    939:                /* Parent: set up mux slave to connect to backgrounded master */
                    940:                debug2("%s: background process is %ld", __func__, (long)pid);
                    941:                stdin_null_flag = ostdin_null_flag;
1.359     djm       942:                options.request_tty = orequest_tty;
1.344     djm       943:                tty_flag = otty_flag;
                    944:                close(muxserver_sock);
                    945:                muxserver_sock = -1;
1.351     markus    946:                options.control_master = SSHCTL_MASTER_NO;
1.344     djm       947:                muxclient(options.control_path);
                    948:                /* muxclient() doesn't return on success. */
                    949:                fatal("Failed to connect to new control master");
                    950:        }
1.346     djm       951:        if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
                    952:                error("%s: open(\"/dev/null\"): %s", __func__,
                    953:                    strerror(errno));
                    954:        } else {
                    955:                if (dup2(devnull, STDIN_FILENO) == -1 ||
                    956:                    dup2(devnull, STDOUT_FILENO) == -1)
                    957:                        error("%s: dup2: %s", __func__, strerror(errno));
                    958:                if (devnull > STDERR_FILENO)
                    959:                        close(devnull);
                    960:        }
1.381     djm       961:        daemon(1, 1);
1.362     djm       962:        setproctitle("%s [mux]", options.control_path);
1.344     djm       963: }
                    964:
                    965: /* Do fork() after authentication. Used by "ssh -f" */
                    966: static void
                    967: fork_postauth(void)
                    968: {
                    969:        if (need_controlpersist_detach)
                    970:                control_persist_detach();
                    971:        debug("forking to background");
                    972:        fork_after_authentication_flag = 0;
                    973:        if (daemon(1, 1) < 0)
                    974:                fatal("daemon() failed: %.200s", strerror(errno));
                    975: }
                    976:
1.315     djm       977: /* Callback for remote forward global requests */
                    978: static void
                    979: ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
                    980: {
                    981:        Forward *rfwd = (Forward *)ctxt;
                    982:
1.324     djm       983:        /* XXX verbose() on failure? */
1.315     djm       984:        debug("remote forward %s for: listen %d, connect %s:%d",
                    985:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
                    986:            rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1.366     markus    987:        if (rfwd->listen_port == 0) {
                    988:                if (type == SSH2_MSG_REQUEST_SUCCESS) {
                    989:                        rfwd->allocated_port = packet_get_int();
                    990:                        logit("Allocated port %u for remote forward to %s:%d",
                    991:                            rfwd->allocated_port,
                    992:                            rfwd->connect_host, rfwd->connect_port);
                    993:                        channel_update_permitted_opens(rfwd->handle,
                    994:                            rfwd->allocated_port);
                    995:                } else {
                    996:                        channel_update_permitted_opens(rfwd->handle, -1);
                    997:                }
1.324     djm       998:        }
                    999:
1.315     djm      1000:        if (type == SSH2_MSG_REQUEST_FAILURE) {
                   1001:                if (options.exit_on_forward_failure)
                   1002:                        fatal("Error: remote port forwarding failed for "
                   1003:                            "listen port %d", rfwd->listen_port);
                   1004:                else
                   1005:                        logit("Warning: remote port forwarding failed for "
                   1006:                            "listen port %d", rfwd->listen_port);
                   1007:        }
1.318     djm      1008:        if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315     djm      1009:                debug("All remote forwarding requests processed");
1.344     djm      1010:                if (fork_after_authentication_flag)
                   1011:                        fork_postauth();
1.318     djm      1012:        }
1.315     djm      1013: }
                   1014:
1.126     itojun   1015: static void
1.331     dtucker  1016: client_cleanup_stdio_fwd(int id, void *arg)
                   1017: {
                   1018:        debug("stdio forwarding: done");
                   1019:        cleanup_exit(0);
                   1020: }
                   1021:
1.368     djm      1022: static void
                   1023: ssh_init_stdio_forwarding(void)
1.331     dtucker  1024: {
                   1025:        Channel *c;
1.332     djm      1026:        int in, out;
1.331     dtucker  1027:
1.368     djm      1028:        if (stdio_forward_host == NULL)
                   1029:                return;
1.384   ! djm      1030:        if (!compat20)
1.368     djm      1031:                fatal("stdio forwarding require Protocol 2");
                   1032:
                   1033:        debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1.332     djm      1034:
1.368     djm      1035:        if ((in = dup(STDIN_FILENO)) < 0 ||
                   1036:            (out = dup(STDOUT_FILENO)) < 0)
1.332     djm      1037:                fatal("channel_connect_stdio_fwd: dup() in/out failed");
1.368     djm      1038:        if ((c = channel_connect_stdio_fwd(stdio_forward_host,
                   1039:            stdio_forward_port, in, out)) == NULL)
                   1040:                fatal("%s: channel_connect_stdio_fwd failed", __func__);
1.331     dtucker  1041:        channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
                   1042: }
                   1043:
                   1044: static void
1.70      markus   1045: ssh_init_forwarding(void)
                   1046: {
1.86      markus   1047:        int success = 0;
1.70      markus   1048:        int i;
1.331     dtucker  1049:
1.70      markus   1050:        /* Initiate local TCP/IP port forwardings. */
                   1051:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm      1052:                debug("Local connections to %.200s:%d forwarded to remote "
                   1053:                    "address %.200s:%d",
1.234     deraadt  1054:                    (options.local_forwards[i].listen_host == NULL) ?
                   1055:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm      1056:                    options.local_forwards[i].listen_host,
                   1057:                    options.local_forwards[i].listen_port,
                   1058:                    options.local_forwards[i].connect_host,
                   1059:                    options.local_forwards[i].connect_port);
1.158     markus   1060:                success += channel_setup_local_fwd_listener(
1.232     djm      1061:                    options.local_forwards[i].listen_host,
                   1062:                    options.local_forwards[i].listen_port,
                   1063:                    options.local_forwards[i].connect_host,
                   1064:                    options.local_forwards[i].connect_port,
1.70      markus   1065:                    options.gateway_ports);
                   1066:        }
1.283     markus   1067:        if (i > 0 && success != i && options.exit_on_forward_failure)
                   1068:                fatal("Could not request local forwarding.");
1.86      markus   1069:        if (i > 0 && success == 0)
                   1070:                error("Could not request local forwarding.");
1.70      markus   1071:
                   1072:        /* Initiate remote TCP/IP port forwardings. */
                   1073:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm      1074:                debug("Remote connections from %.200s:%d forwarded to "
                   1075:                    "local address %.200s:%d",
1.248     djm      1076:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm      1077:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm      1078:                    options.remote_forwards[i].listen_port,
                   1079:                    options.remote_forwards[i].connect_host,
                   1080:                    options.remote_forwards[i].connect_port);
1.366     markus   1081:                options.remote_forwards[i].handle =
                   1082:                    channel_request_remote_forwarding(
1.232     djm      1083:                    options.remote_forwards[i].listen_host,
                   1084:                    options.remote_forwards[i].listen_port,
                   1085:                    options.remote_forwards[i].connect_host,
1.366     markus   1086:                    options.remote_forwards[i].connect_port);
                   1087:                if (options.remote_forwards[i].handle < 0) {
1.283     markus   1088:                        if (options.exit_on_forward_failure)
                   1089:                                fatal("Could not request remote forwarding.");
                   1090:                        else
                   1091:                                logit("Warning: Could not request remote "
                   1092:                                    "forwarding.");
1.366     markus   1093:                } else {
                   1094:                        client_register_global_confirm(ssh_confirm_remote_forward,
                   1095:                            &options.remote_forwards[i]);
1.283     markus   1096:                }
1.70      markus   1097:        }
1.301     djm      1098:
                   1099:        /* Initiate tunnel forwarding. */
                   1100:        if (options.tun_open != SSH_TUNMODE_NO) {
                   1101:                if (client_request_tun_fwd(options.tun_open,
                   1102:                    options.tun_local, options.tun_remote) == -1) {
                   1103:                        if (options.exit_on_forward_failure)
                   1104:                                fatal("Could not request tunnel forwarding.");
                   1105:                        else
                   1106:                                error("Could not request tunnel forwarding.");
                   1107:                }
                   1108:        }
1.70      markus   1109: }
                   1110:
1.126     itojun   1111: static void
1.70      markus   1112: check_agent_present(void)
                   1113: {
                   1114:        if (options.forward_agent) {
1.254     djm      1115:                /* Clear agent forwarding if we don't have an agent. */
1.185     stevesk  1116:                if (!ssh_agent_present())
1.70      markus   1117:                        options.forward_agent = 0;
                   1118:        }
                   1119: }
                   1120:
1.126     itojun   1121: static int
1.45      markus   1122: ssh_session(void)
                   1123: {
                   1124:        int type;
                   1125:        int interactive = 0;
                   1126:        int have_tty = 0;
                   1127:        struct winsize ws;
                   1128:        char *cp;
1.243     djm      1129:        const char *display;
1.45      markus   1130:
1.31      markus   1131:        /* Enable compression if requested. */
                   1132:        if (options.compression) {
1.316     djm      1133:                debug("Requesting compression at level %d.",
                   1134:                    options.compression_level);
1.31      markus   1135:
1.316     djm      1136:                if (options.compression_level < 1 ||
                   1137:                    options.compression_level > 9)
                   1138:                        fatal("Compression level must be from 1 (fast) to "
                   1139:                            "9 (slow, best).");
1.31      markus   1140:
                   1141:                /* Send the request. */
                   1142:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                   1143:                packet_put_int(options.compression_level);
                   1144:                packet_send();
                   1145:                packet_write_wait();
1.156     markus   1146:                type = packet_read();
1.31      markus   1147:                if (type == SSH_SMSG_SUCCESS)
                   1148:                        packet_start_compression(options.compression_level);
                   1149:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun   1150:                        logit("Warning: Remote host refused compression.");
1.31      markus   1151:                else
1.316     djm      1152:                        packet_disconnect("Protocol error waiting for "
                   1153:                            "compression response.");
1.31      markus   1154:        }
                   1155:        /* Allocate a pseudo tty if appropriate. */
                   1156:        if (tty_flag) {
                   1157:                debug("Requesting pty.");
                   1158:
                   1159:                /* Start the packet. */
                   1160:                packet_start(SSH_CMSG_REQUEST_PTY);
                   1161:
                   1162:                /* Store TERM in the packet.  There is no limit on the
                   1163:                   length of the string. */
                   1164:                cp = getenv("TERM");
                   1165:                if (!cp)
                   1166:                        cp = "";
1.124     markus   1167:                packet_put_cstring(cp);
1.31      markus   1168:
                   1169:                /* Store window size in the packet. */
                   1170:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                   1171:                        memset(&ws, 0, sizeof(ws));
1.269     deraadt  1172:                packet_put_int((u_int)ws.ws_row);
                   1173:                packet_put_int((u_int)ws.ws_col);
                   1174:                packet_put_int((u_int)ws.ws_xpixel);
                   1175:                packet_put_int((u_int)ws.ws_ypixel);
1.31      markus   1176:
                   1177:                /* Store tty modes in the packet. */
1.115     stevesk  1178:                tty_make_modes(fileno(stdin), NULL);
1.31      markus   1179:
                   1180:                /* Send the packet, and wait for it to leave. */
                   1181:                packet_send();
                   1182:                packet_write_wait();
                   1183:
                   1184:                /* Read response from the server. */
1.156     markus   1185:                type = packet_read();
1.43      markus   1186:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus   1187:                        interactive = 1;
1.45      markus   1188:                        have_tty = 1;
1.43      markus   1189:                } else if (type == SSH_SMSG_FAILURE)
1.316     djm      1190:                        logit("Warning: Remote host failed or refused to "
                   1191:                            "allocate a pseudo tty.");
1.31      markus   1192:                else
1.316     djm      1193:                        packet_disconnect("Protocol error waiting for pty "
                   1194:                            "request response.");
1.31      markus   1195:        }
                   1196:        /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243     djm      1197:        display = getenv("DISPLAY");
                   1198:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1199:                char *proto, *data;
1.50      markus   1200:                /* Get reasonable local authentication information. */
1.243     djm      1201:                client_x11_get_proto(display, options.xauth_location,
1.384   ! djm      1202:                    options.forward_x11_trusted,
1.340     djm      1203:                    options.forward_x11_timeout,
                   1204:                    &proto, &data);
1.50      markus   1205:                /* Request forwarding with authentication spoofing. */
1.316     djm      1206:                debug("Requesting X11 forwarding with authentication "
                   1207:                    "spoofing.");
1.363     djm      1208:                x11_request_forwarding_with_spoofing(0, display, proto,
                   1209:                    data, 0);
1.31      markus   1210:                /* Read response from the server. */
1.156     markus   1211:                type = packet_read();
1.31      markus   1212:                if (type == SSH_SMSG_SUCCESS) {
                   1213:                        interactive = 1;
1.50      markus   1214:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun   1215:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus   1216:                } else {
1.316     djm      1217:                        packet_disconnect("Protocol error waiting for X11 "
                   1218:                            "forwarding");
1.50      markus   1219:                }
1.31      markus   1220:        }
                   1221:        /* Tell the packet module whether this is an interactive session. */
1.354     djm      1222:        packet_set_interactive(interactive,
                   1223:            options.ip_qos_interactive, options.ip_qos_bulk);
1.31      markus   1224:
                   1225:        /* Request authentication agent forwarding if appropriate. */
1.70      markus   1226:        check_agent_present();
                   1227:
1.31      markus   1228:        if (options.forward_agent) {
                   1229:                debug("Requesting authentication agent forwarding.");
                   1230:                auth_request_forwarding();
                   1231:
                   1232:                /* Read response from the server. */
1.156     markus   1233:                type = packet_read();
1.155     markus   1234:                packet_check_eom();
1.31      markus   1235:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun   1236:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus   1237:        }
                   1238:
1.70      markus   1239:        /* Initiate port forwardings. */
1.368     djm      1240:        ssh_init_stdio_forwarding();
1.70      markus   1241:        ssh_init_forwarding();
1.305     dtucker  1242:
                   1243:        /* Execute a local command */
                   1244:        if (options.local_command != NULL &&
                   1245:            options.permit_local_command)
                   1246:                ssh_local_cmd(options.local_command);
1.34      markus   1247:
1.318     djm      1248:        /*
                   1249:         * If requested and we are not interested in replies to remote
                   1250:         * forwarding requests, then let ssh continue in the background.
                   1251:         */
1.344     djm      1252:        if (fork_after_authentication_flag) {
                   1253:                if (options.exit_on_forward_failure &&
                   1254:                    options.num_remote_forwards > 0) {
                   1255:                        debug("deferring postauth fork until remote forward "
                   1256:                            "confirmation received");
                   1257:                } else
                   1258:                        fork_postauth();
1.318     djm      1259:        }
1.31      markus   1260:
1.33      markus   1261:        /*
                   1262:         * If a command was specified on the command line, execute the
                   1263:         * command now. Otherwise request the server to start a shell.
                   1264:         */
1.31      markus   1265:        if (buffer_len(&command) > 0) {
                   1266:                int len = buffer_len(&command);
                   1267:                if (len > 900)
                   1268:                        len = 900;
1.316     djm      1269:                debug("Sending command: %.*s", len,
                   1270:                    (u_char *)buffer_ptr(&command));
1.31      markus   1271:                packet_start(SSH_CMSG_EXEC_CMD);
                   1272:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1273:                packet_send();
                   1274:                packet_write_wait();
                   1275:        } else {
                   1276:                debug("Requesting shell.");
                   1277:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1278:                packet_send();
                   1279:                packet_write_wait();
                   1280:        }
                   1281:
                   1282:        /* Enter the interactive session. */
1.119     stevesk  1283:        return client_loop(have_tty, tty_flag ?
                   1284:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.89      markus   1285: }
                   1286:
1.214     djm      1287: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1288: static void
1.337     djm      1289: ssh_session2_setup(int id, int success, void *arg)
1.214     djm      1290: {
1.215     djm      1291:        extern char **environ;
1.243     djm      1292:        const char *display;
                   1293:        int interactive = tty_flag;
1.337     djm      1294:
                   1295:        if (!success)
                   1296:                return; /* No need for error message, channels code sens one */
1.215     djm      1297:
1.248     djm      1298:        display = getenv("DISPLAY");
1.243     djm      1299:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1300:                char *proto, *data;
1.50      markus   1301:                /* Get reasonable local authentication information. */
1.243     djm      1302:                client_x11_get_proto(display, options.xauth_location,
1.340     djm      1303:                    options.forward_x11_trusted,
                   1304:                    options.forward_x11_timeout, &proto, &data);
1.50      markus   1305:                /* Request forwarding with authentication spoofing. */
1.316     djm      1306:                debug("Requesting X11 forwarding with authentication "
                   1307:                    "spoofing.");
1.363     djm      1308:                x11_request_forwarding_with_spoofing(id, display, proto,
                   1309:                    data, 1);
                   1310:                client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
                   1311:                /* XXX exit_on_forward_failure */
1.80      markus   1312:                interactive = 1;
1.50      markus   1313:        }
                   1314:
1.70      markus   1315:        check_agent_present();
                   1316:        if (options.forward_agent) {
                   1317:                debug("Requesting authentication agent forwarding.");
                   1318:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1319:                packet_send();
1.212     djm      1320:        }
1.369     dtucker  1321:
                   1322:        /* Tell the packet module whether this is an interactive session. */
                   1323:        packet_set_interactive(interactive,
                   1324:            options.ip_qos_interactive, options.ip_qos_bulk);
1.212     djm      1325:
1.214     djm      1326:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.311     djm      1327:            NULL, fileno(stdin), &command, environ);
1.45      markus   1328: }
                   1329:
1.143     markus   1330: /* open new channel for a session */
1.126     itojun   1331: static int
1.143     markus   1332: ssh_session2_open(void)
1.45      markus   1333: {
1.118     markus   1334:        Channel *c;
                   1335:        int window, packetmax, in, out, err;
1.60      markus   1336:
1.62      markus   1337:        if (stdin_null_flag) {
1.93      itojun   1338:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1339:        } else {
                   1340:                in = dup(STDIN_FILENO);
                   1341:        }
1.60      markus   1342:        out = dup(STDOUT_FILENO);
                   1343:        err = dup(STDERR_FILENO);
1.45      markus   1344:
                   1345:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1346:                fatal("dup() in/out/err failed");
1.45      markus   1347:
1.69      markus   1348:        /* enable nonblocking unless tty */
                   1349:        if (!isatty(in))
                   1350:                set_nonblock(in);
                   1351:        if (!isatty(out))
                   1352:                set_nonblock(out);
                   1353:        if (!isatty(err))
                   1354:                set_nonblock(err);
                   1355:
1.65      markus   1356:        window = CHAN_SES_WINDOW_DEFAULT;
                   1357:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1358:        if (tty_flag) {
                   1359:                window >>= 1;
                   1360:                packetmax >>= 1;
1.45      markus   1361:        }
1.118     markus   1362:        c = channel_new(
1.45      markus   1363:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1364:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1365:            "client-session", /*nonblock*/0);
1.45      markus   1366:
1.143     markus   1367:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1368:
1.122     markus   1369:        channel_send_open(c->self);
1.143     markus   1370:        if (!no_shell_flag)
1.310     djm      1371:                channel_register_open_confirm(c->self,
                   1372:                    ssh_session2_setup, NULL);
1.106     markus   1373:
1.118     markus   1374:        return c->self;
1.106     markus   1375: }
                   1376:
1.126     itojun   1377: static int
1.106     markus   1378: ssh_session2(void)
                   1379: {
1.143     markus   1380:        int id = -1;
1.106     markus   1381:
                   1382:        /* XXX should be pre-session */
1.368     djm      1383:        if (!options.control_persist)
                   1384:                ssh_init_stdio_forwarding();
1.106     markus   1385:        ssh_init_forwarding();
                   1386:
1.344     djm      1387:        /* Start listening for multiplex clients */
                   1388:        muxserver_listen();
                   1389:
                   1390:        /*
1.368     djm      1391:         * If we are in control persist mode and have a working mux listen
                   1392:         * socket, then prepare to background ourselves and have a foreground
                   1393:         * client attach as a control slave.
                   1394:         * NB. we must save copies of the flags that we override for
1.344     djm      1395:         * the backgrounding, since we defer attachment of the slave until
                   1396:         * after the connection is fully established (in particular,
                   1397:         * async rfwd replies have been received for ExitOnForwardFailure).
                   1398:         */
                   1399:        if (options.control_persist && muxserver_sock != -1) {
                   1400:                ostdin_null_flag = stdin_null_flag;
                   1401:                ono_shell_flag = no_shell_flag;
1.359     djm      1402:                orequest_tty = options.request_tty;
1.344     djm      1403:                otty_flag = tty_flag;
                   1404:                stdin_null_flag = 1;
                   1405:                no_shell_flag = 1;
                   1406:                tty_flag = 0;
                   1407:                if (!fork_after_authentication_flag)
                   1408:                        need_controlpersist_detach = 1;
                   1409:                fork_after_authentication_flag = 1;
                   1410:        }
1.368     djm      1411:        /*
                   1412:         * ControlPersist mux listen socket setup failed, attempt the
                   1413:         * stdio forward setup that we skipped earlier.
                   1414:         */
                   1415:        if (options.control_persist && muxserver_sock == -1)
                   1416:                ssh_init_stdio_forwarding();
1.344     djm      1417:
1.143     markus   1418:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1419:                id = ssh_session2_open();
1.379     djm      1420:        else {
                   1421:                packet_set_interactive(
                   1422:                    options.control_master == SSHCTL_MASTER_NO,
                   1423:                    options.ip_qos_interactive, options.ip_qos_bulk);
                   1424:        }
1.314     djm      1425:
                   1426:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   1427:        if (options.control_master == SSHCTL_MASTER_NO &&
                   1428:            (datafellows & SSH_NEW_OPENSSH)) {
1.314     djm      1429:                debug("Requesting no-more-sessions@openssh.com");
                   1430:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1431:                packet_put_cstring("no-more-sessions@openssh.com");
                   1432:                packet_put_char(0);
                   1433:                packet_send();
                   1434:        }
1.255     reyk     1435:
                   1436:        /* Execute a local command */
                   1437:        if (options.local_command != NULL &&
                   1438:            options.permit_local_command)
                   1439:                ssh_local_cmd(options.local_command);
1.301     djm      1440:
1.342     djm      1441:        /*
                   1442:         * If requested and we are not interested in replies to remote
                   1443:         * forwarding requests, then let ssh continue in the background.
                   1444:         */
1.344     djm      1445:        if (fork_after_authentication_flag) {
                   1446:                if (options.exit_on_forward_failure &&
                   1447:                    options.num_remote_forwards > 0) {
                   1448:                        debug("deferring postauth fork until remote forward "
                   1449:                            "confirmation received");
                   1450:                } else
                   1451:                        fork_postauth();
1.318     djm      1452:        }
1.327     andreas  1453:
                   1454:        if (options.use_roaming)
                   1455:                request_roaming();
1.31      markus   1456:
1.119     stevesk  1457:        return client_loop(tty_flag, tty_flag ?
                   1458:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1459: }
                   1460:
1.126     itojun   1461: static void
1.104     markus   1462: load_public_identity_files(void)
                   1463: {
1.275     djm      1464:        char *filename, *cp, thishost[NI_MAXHOST];
1.306     deraadt  1465:        char *pwdir = NULL, *pwname = NULL;
1.167     markus   1466:        int i = 0;
1.104     markus   1467:        Key *public;
1.275     djm      1468:        struct passwd *pw;
1.335     djm      1469:        u_int n_ids;
                   1470:        char *identity_files[SSH_MAX_IDENTITY_FILES];
                   1471:        Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1.333     markus   1472: #ifdef ENABLE_PKCS11
1.167     markus   1473:        Key **keys;
1.333     markus   1474:        int nkeys;
1.335     djm      1475: #endif /* PKCS11 */
1.104     markus   1476:
1.335     djm      1477:        n_ids = 0;
                   1478:        bzero(identity_files, sizeof(identity_files));
                   1479:        bzero(identity_keys, sizeof(identity_keys));
                   1480:
                   1481: #ifdef ENABLE_PKCS11
1.333     markus   1482:        if (options.pkcs11_provider != NULL &&
1.167     markus   1483:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   1484:            (pkcs11_init(!options.batch_mode) == 0) &&
                   1485:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
                   1486:            &keys)) > 0) {
                   1487:                for (i = 0; i < nkeys; i++) {
1.335     djm      1488:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
                   1489:                                key_free(keys[i]);
                   1490:                                continue;
                   1491:                        }
                   1492:                        identity_keys[n_ids] = keys[i];
                   1493:                        identity_files[n_ids] =
1.333     markus   1494:                            xstrdup(options.pkcs11_provider); /* XXX */
1.335     djm      1495:                        n_ids++;
1.167     markus   1496:                }
1.378     djm      1497:                free(keys);
1.127     markus   1498:        }
1.333     markus   1499: #endif /* ENABLE_PKCS11 */
1.275     djm      1500:        if ((pw = getpwuid(original_real_uid)) == NULL)
                   1501:                fatal("load_public_identity_files: getpwuid failed");
1.307     dtucker  1502:        pwname = xstrdup(pw->pw_name);
                   1503:        pwdir = xstrdup(pw->pw_dir);
1.275     djm      1504:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1505:                fatal("load_public_identity_files: gethostname: %s",
                   1506:                    strerror(errno));
1.335     djm      1507:        for (i = 0; i < options.num_identity_files; i++) {
1.373     djm      1508:                if (n_ids >= SSH_MAX_IDENTITY_FILES ||
                   1509:                    strcasecmp(options.identity_files[i], "none") == 0) {
1.378     djm      1510:                        free(options.identity_files[i]);
1.335     djm      1511:                        continue;
                   1512:                }
1.275     djm      1513:                cp = tilde_expand_filename(options.identity_files[i],
1.131     millert  1514:                    original_real_uid);
1.306     deraadt  1515:                filename = percent_expand(cp, "d", pwdir,
                   1516:                    "u", pwname, "l", thishost, "h", host,
1.275     djm      1517:                    "r", options.user, (char *)NULL);
1.378     djm      1518:                free(cp);
1.131     millert  1519:                public = key_load_public(filename, NULL);
                   1520:                debug("identity file %s type %d", filename,
                   1521:                    public ? public->type : -1);
1.378     djm      1522:                free(options.identity_files[i]);
1.335     djm      1523:                identity_files[n_ids] = filename;
                   1524:                identity_keys[n_ids] = public;
                   1525:
                   1526:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
                   1527:                        continue;
                   1528:
                   1529:                /* Try to add the certificate variant too */
                   1530:                xasprintf(&cp, "%s-cert", filename);
                   1531:                public = key_load_public(cp, NULL);
                   1532:                debug("identity file %s type %d", cp,
                   1533:                    public ? public->type : -1);
                   1534:                if (public == NULL) {
1.378     djm      1535:                        free(cp);
1.335     djm      1536:                        continue;
                   1537:                }
                   1538:                if (!key_is_cert(public)) {
                   1539:                        debug("%s: key %s type %s is not a certificate",
                   1540:                            __func__, cp, key_type(public));
                   1541:                        key_free(public);
1.378     djm      1542:                        free(cp);
1.335     djm      1543:                        continue;
                   1544:                }
                   1545:                identity_keys[n_ids] = public;
                   1546:                /* point to the original path, most likely the private key */
                   1547:                identity_files[n_ids] = xstrdup(filename);
                   1548:                n_ids++;
                   1549:        }
                   1550:        options.num_identity_files = n_ids;
                   1551:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
                   1552:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
                   1553:
1.306     deraadt  1554:        bzero(pwname, strlen(pwname));
1.378     djm      1555:        free(pwname);
1.306     deraadt  1556:        bzero(pwdir, strlen(pwdir));
1.378     djm      1557:        free(pwdir);
1.214     djm      1558: }
1.352     djm      1559:
                   1560: static void
                   1561: main_sigchld_handler(int sig)
                   1562: {
                   1563:        int save_errno = errno;
                   1564:        pid_t pid;
                   1565:        int status;
                   1566:
                   1567:        while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
                   1568:            (pid < 0 && errno == EINTR))
                   1569:                ;
                   1570:
                   1571:        signal(sig, main_sigchld_handler);
                   1572:        errno = save_errno;
                   1573: }
                   1574: