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

1.340   ! djm         1: /* $OpenBSD: ssh.c,v 1.339 2010/06/25 23:10:30 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.258     stevesk    52:
1.265     stevesk    53: #include <ctype.h>
1.285     stevesk    54: #include <errno.h>
1.281     stevesk    55: #include <fcntl.h>
1.286     stevesk    56: #include <netdb.h>
1.258     stevesk    57: #include <paths.h>
1.279     stevesk    58: #include <pwd.h>
1.263     stevesk    59: #include <signal.h>
1.287     stevesk    60: #include <stddef.h>
1.291     stevesk    61: #include <stdio.h>
1.290     stevesk    62: #include <stdlib.h>
1.289     stevesk    63: #include <string.h>
1.288     stevesk    64: #include <unistd.h>
1.49      markus     65:
                     66: #include <openssl/evp.h>
1.72      markus     67: #include <openssl/err.h>
1.1       deraadt    68:
1.293     deraadt    69: #include "xmalloc.h"
1.84      markus     70: #include "ssh.h"
                     71: #include "ssh1.h"
                     72: #include "ssh2.h"
                     73: #include "compat.h"
                     74: #include "cipher.h"
1.1       deraadt    75: #include "packet.h"
                     76: #include "buffer.h"
1.123     markus     77: #include "channels.h"
1.49      markus     78: #include "key.h"
1.58      markus     79: #include "authfd.h"
1.49      markus     80: #include "authfile.h"
1.83      markus     81: #include "pathnames.h"
1.214     djm        82: #include "dispatch.h"
1.81      markus     83: #include "clientloop.h"
1.84      markus     84: #include "log.h"
                     85: #include "readconf.h"
                     86: #include "sshconnect.h"
                     87: #include "misc.h"
1.95      markus     88: #include "kex.h"
                     89: #include "mac.h"
1.213     deraadt    90: #include "sshpty.h"
1.212     djm        91: #include "match.h"
1.214     djm        92: #include "msg.h"
1.225     dtucker    93: #include "uidswap.h"
1.327     andreas    94: #include "roaming.h"
1.278     stevesk    95: #include "version.h"
1.49      markus     96:
1.333     markus     97: #ifdef ENABLE_PKCS11
                     98: #include "ssh-pkcs11.h"
1.137     jakob      99: #endif
1.127     markus    100:
1.49      markus    101: extern char *__progname;
1.1       deraadt   102:
1.316     djm       103: /* Flag indicating whether debug mode is on.  May be set on the command line. */
1.1       deraadt   104: int debug_flag = 0;
                    105:
1.46      markus    106: /* Flag indicating whether a tty should be allocated */
1.1       deraadt   107: int tty_flag = 0;
1.79      markus    108: int no_tty_flag = 0;
                    109: int force_tty_flag = 0;
1.1       deraadt   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: /*
                    121:  * Flag indicating that ssh should fork after authentication.  This is useful
1.172     deraadt   122:  * so that the passphrase can be entered manually, and then ssh goes to the
1.33      markus    123:  * background.
                    124:  */
1.1       deraadt   125: int fork_after_authentication_flag = 0;
                    126:
1.331     dtucker   127: /* forward stdio to remote host and port */
                    128: char *stdio_forward_host = NULL;
                    129: int stdio_forward_port = 0;
                    130:
1.33      markus    131: /*
                    132:  * General data structure for command line options and options configurable
                    133:  * in configuration files.  See readconf.h.
                    134:  */
1.1       deraadt   135: Options options;
                    136:
1.139     markus    137: /* optional user configfile */
                    138: char *config = NULL;
                    139:
1.33      markus    140: /*
                    141:  * Name of the host we are connecting to.  This is the name given on the
                    142:  * command line, or the HostName specified for the user-supplied name in a
                    143:  * configuration file.
                    144:  */
1.1       deraadt   145: char *host;
                    146:
1.22      provos    147: /* socket address the host resolves to */
1.37      markus    148: struct sockaddr_storage hostaddr;
1.1       deraadt   149:
1.112     markus    150: /* Private host keys. */
1.173     markus    151: Sensitive sensitive_data;
1.1       deraadt   152:
1.10      dugsong   153: /* Original real UID. */
                    154: uid_t original_real_uid;
1.177     markus    155: uid_t original_effective_uid;
1.1       deraadt   156:
1.45      markus    157: /* command to be executed */
                    158: Buffer command;
                    159:
1.85      djm       160: /* Should we execute a command or invoke a subsystem? */
                    161: int subsystem_flag = 0;
                    162:
1.170     markus    163: /* # of replies received for global requests */
1.315     djm       164: static int remote_forward_confirms_received = 0;
1.170     markus    165:
1.186     djm       166: /* pid of proxycommand child process */
                    167: pid_t proxy_command_pid = 0;
1.313     djm       168:
                    169: /* mux.c */
                    170: extern int muxserver_sock;
                    171: extern u_int muxclient_command;
                    172:
1.186     djm       173:
1.1       deraadt   174: /* Prints a help message to the user.  This function never returns. */
                    175:
1.126     itojun    176: static void
1.93      itojun    177: usage(void)
1.1       deraadt   178: {
1.208     markus    179:        fprintf(stderr,
1.321     jmc       180: "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
1.251     jmc       181: "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
1.334     jmc       182: "           [-I pkcs11] [-i identity_file]\n"
                    183: "           [-L [bind_address:]port:host:hostport]\n"
1.232     djm       184: "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
1.233     jmc       185: "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
1.331     dtucker   186: "           [-W host:port] [-w local_tun[:remote_tun]]\n"
                    187: "           [user@]hostname [command]\n"
1.208     markus    188:        );
1.257     dtucker   189:        exit(255);
1.1       deraadt   190: }
                    191:
1.126     itojun    192: static int ssh_session(void);
                    193: static int ssh_session2(void);
                    194: static void load_public_identity_files(void);
1.312     djm       195:
                    196: /* from muxclient.c */
                    197: void muxclient(const char *);
                    198: void muxserver_listen(void);
1.45      markus    199:
1.32      deraadt   200: /*
                    201:  * Main program for the ssh client.
                    202:  */
1.2       provos    203: int
                    204: main(int ac, char **av)
1.1       deraadt   205: {
1.326     dtucker   206:        int i, r, opt, exit_status, use_syslog;
                    207:        char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
1.31      markus    208:        struct stat st;
1.98      markus    209:        struct passwd *pw;
1.303     djm       210:        int dummy, timeout_ms;
1.144     stevesk   211:        extern int optind, optreset;
                    212:        extern char *optarg;
1.244     djm       213:        struct servent *sp;
1.232     djm       214:        Forward fwd;
1.250     djm       215:
                    216:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    217:        sanitise_stdfd();
1.31      markus    218:
1.33      markus    219:        /*
                    220:         * Save the original real uid.  It will be needed later (uid-swapping
                    221:         * may clobber the real uid).
                    222:         */
1.31      markus    223:        original_real_uid = getuid();
                    224:        original_effective_uid = geteuid();
                    225:
1.184     stevesk   226:        /*
                    227:         * Use uid-swapping to give up root privileges for the duration of
                    228:         * option processing.  We will re-instantiate the rights when we are
                    229:         * ready to create the privileged port, and will permanently drop
                    230:         * them when the port has been created (actually, when the connection
                    231:         * has been made, as we may need to create the port several times).
                    232:         */
                    233:        PRIV_END;
                    234:
1.31      markus    235:        /* If we are installed setuid root be careful to not drop core. */
                    236:        if (original_real_uid != original_effective_uid) {
                    237:                struct rlimit rlim;
                    238:                rlim.rlim_cur = rlim.rlim_max = 0;
                    239:                if (setrlimit(RLIMIT_CORE, &rlim) < 0)
                    240:                        fatal("setrlimit failed: %.100s", strerror(errno));
1.1       deraadt   241:        }
1.107     markus    242:        /* Get user data. */
                    243:        pw = getpwuid(original_real_uid);
                    244:        if (!pw) {
1.191     itojun    245:                logit("You don't exist, go away!");
1.257     dtucker   246:                exit(255);
1.107     markus    247:        }
                    248:        /* Take a copy of the returned structure. */
                    249:        pw = pwcopy(pw);
1.31      markus    250:
1.33      markus    251:        /*
                    252:         * Set our umask to something reasonable, as some files are created
                    253:         * with the default umask.  This will make them world-readable but
                    254:         * writable only by the owner, which is ok for all files for which we
                    255:         * don't set the modes explicitly.
                    256:         */
1.31      markus    257:        umask(022);
                    258:
1.316     djm       259:        /*
                    260:         * Initialize option structure to indicate that no values have been
                    261:         * set.
                    262:         */
1.31      markus    263:        initialize_options(&options);
                    264:
                    265:        /* Parse command-line arguments. */
                    266:        host = NULL;
1.320     djm       267:        use_syslog = 0;
1.325     markus    268:        argv0 = av[0];
1.31      markus    269:
1.266     djm       270:  again:
1.316     djm       271:        while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
1.331     dtucker   272:            "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
1.31      markus    273:                switch (opt) {
1.91      jakob     274:                case '1':
                    275:                        options.protocol = SSH_PROTO_1;
                    276:                        break;
1.47      markus    277:                case '2':
                    278:                        options.protocol = SSH_PROTO_2;
                    279:                        break;
1.37      markus    280:                case '4':
1.196     djm       281:                        options.address_family = AF_INET;
1.37      markus    282:                        break;
                    283:                case '6':
1.196     djm       284:                        options.address_family = AF_INET6;
1.37      markus    285:                        break;
1.31      markus    286:                case 'n':
                    287:                        stdin_null_flag = 1;
                    288:                        break;
                    289:                case 'f':
                    290:                        fork_after_authentication_flag = 1;
                    291:                        stdin_null_flag = 1;
                    292:                        break;
                    293:                case 'x':
                    294:                        options.forward_x11 = 0;
                    295:                        break;
                    296:                case 'X':
                    297:                        options.forward_x11 = 1;
                    298:                        break;
1.320     djm       299:                case 'y':
                    300:                        use_syslog = 1;
                    301:                        break;
1.202     markus    302:                case 'Y':
                    303:                        options.forward_x11 = 1;
                    304:                        options.forward_x11_trusted = 1;
                    305:                        break;
1.31      markus    306:                case 'g':
                    307:                        options.gateway_ports = 1;
                    308:                        break;
1.229     djm       309:                case 'O':
1.332     djm       310:                        if (stdio_forward_host != NULL)
                    311:                                fatal("Cannot specify multiplexing "
                    312:                                    "command with -W");
                    313:                        else if (muxclient_command != 0)
                    314:                                fatal("Multiplexing command already specified");
1.229     djm       315:                        if (strcmp(optarg, "check") == 0)
1.312     djm       316:                                muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
1.338     markus    317:                        else if (strcmp(optarg, "forward") == 0)
                    318:                                muxclient_command = SSHMUX_COMMAND_FORWARD;
1.229     djm       319:                        else if (strcmp(optarg, "exit") == 0)
1.312     djm       320:                                muxclient_command = SSHMUX_COMMAND_TERMINATE;
1.229     djm       321:                        else
                    322:                                fatal("Invalid multiplex command.");
                    323:                        break;
1.183     stevesk   324:                case 'P':       /* deprecated */
1.31      markus    325:                        options.use_privileged_port = 0;
                    326:                        break;
                    327:                case 'a':
                    328:                        options.forward_agent = 0;
1.53      markus    329:                        break;
                    330:                case 'A':
                    331:                        options.forward_agent = 1;
1.31      markus    332:                        break;
                    333:                case 'k':
1.204     dtucker   334:                        options.gss_deleg_creds = 0;
1.297     djm       335:                        break;
                    336:                case 'K':
                    337:                        options.gss_authentication = 1;
                    338:                        options.gss_deleg_creds = 1;
1.31      markus    339:                        break;
                    340:                case 'i':
                    341:                        if (stat(optarg, &st) < 0) {
1.128     fgsch     342:                                fprintf(stderr, "Warning: Identity file %s "
1.231     otto      343:                                    "not accessible: %s.\n", optarg,
                    344:                                    strerror(errno));
1.31      markus    345:                                break;
                    346:                        }
1.128     fgsch     347:                        if (options.num_identity_files >=
                    348:                            SSH_MAX_IDENTITY_FILES)
                    349:                                fatal("Too many identity files specified "
                    350:                                    "(max %d)", SSH_MAX_IDENTITY_FILES);
                    351:                        options.identity_files[options.num_identity_files++] =
                    352:                            xstrdup(optarg);
1.31      markus    353:                        break;
1.127     markus    354:                case 'I':
1.333     markus    355: #ifdef ENABLE_PKCS11
                    356:                        options.pkcs11_provider = xstrdup(optarg);
1.137     jakob     357: #else
1.333     markus    358:                        fprintf(stderr, "no support for PKCS#11.\n");
1.137     jakob     359: #endif
1.127     markus    360:                        break;
1.31      markus    361:                case 't':
1.79      markus    362:                        if (tty_flag)
                    363:                                force_tty_flag = 1;
1.31      markus    364:                        tty_flag = 1;
                    365:                        break;
                    366:                case 'v':
1.197     markus    367:                        if (debug_flag == 0) {
1.66      markus    368:                                debug_flag = 1;
                    369:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    370:                        } else {
                    371:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3)
                    372:                                        options.log_level++;
1.66      markus    373:                                break;
1.197     markus    374:                        }
1.227     deraadt   375:                        /* FALLTHROUGH */
1.31      markus    376:                case 'V':
1.209     markus    377:                        fprintf(stderr, "%s, %s\n",
                    378:                            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.31      markus    379:                        if (opt == 'V')
                    380:                                exit(0);
                    381:                        break;
1.255     reyk      382:                case 'w':
1.256     reyk      383:                        if (options.tun_open == -1)
                    384:                                options.tun_open = SSH_TUNMODE_DEFAULT;
1.255     reyk      385:                        options.tun_local = a2tun(optarg, &options.tun_remote);
1.256     reyk      386:                        if (options.tun_local == SSH_TUNID_ERR) {
1.316     djm       387:                                fprintf(stderr,
                    388:                                    "Bad tun device '%s'\n", optarg);
1.257     dtucker   389:                                exit(255);
1.255     reyk      390:                        }
                    391:                        break;
1.331     dtucker   392:                case 'W':
1.332     djm       393:                        if (stdio_forward_host != NULL)
                    394:                                fatal("stdio forward already specified");
                    395:                        if (muxclient_command != 0)
                    396:                                fatal("Cannot specify stdio forward with -O");
1.331     dtucker   397:                        if (parse_forward(&fwd, optarg, 1, 0)) {
                    398:                                stdio_forward_host = fwd.listen_host;
                    399:                                stdio_forward_port = fwd.listen_port;
                    400:                                xfree(fwd.connect_host);
                    401:                        } else {
                    402:                                fprintf(stderr,
                    403:                                    "Bad stdio forwarding specification '%s'\n",
                    404:                                    optarg);
                    405:                                exit(255);
                    406:                        }
                    407:                        no_tty_flag = 1;
                    408:                        no_shell_flag = 1;
                    409:                        options.clear_forwardings = 1;
                    410:                        options.exit_on_forward_failure = 1;
                    411:                        break;
1.31      markus    412:                case 'q':
                    413:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    414:                        break;
                    415:                case 'e':
                    416:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     417:                            (u_char) optarg[1] >= 64 &&
                    418:                            (u_char) optarg[1] < 128)
1.78      markus    419:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    420:                        else if (strlen(optarg) == 1)
1.78      markus    421:                                options.escape_char = (u_char) optarg[0];
1.31      markus    422:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   423:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    424:                        else {
1.128     fgsch     425:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    426:                                    optarg);
1.257     dtucker   427:                                exit(255);
1.31      markus    428:                        }
                    429:                        break;
                    430:                case 'c':
1.49      markus    431:                        if (ciphers_valid(optarg)) {
                    432:                                /* SSH2 only */
                    433:                                options.ciphers = xstrdup(optarg);
1.224     markus    434:                                options.cipher = SSH_CIPHER_INVALID;
1.49      markus    435:                        } else {
                    436:                                /* SSH1 only */
1.74      markus    437:                                options.cipher = cipher_number(optarg);
                    438:                                if (options.cipher == -1) {
1.128     fgsch     439:                                        fprintf(stderr,
                    440:                                            "Unknown cipher type '%s'\n",
                    441:                                            optarg);
1.257     dtucker   442:                                        exit(255);
1.49      markus    443:                                }
1.128     fgsch     444:                                if (options.cipher == SSH_CIPHER_3DES)
1.74      markus    445:                                        options.ciphers = "3des-cbc";
1.128     fgsch     446:                                else if (options.cipher == SSH_CIPHER_BLOWFISH)
1.74      markus    447:                                        options.ciphers = "blowfish-cbc";
1.128     fgsch     448:                                else
1.74      markus    449:                                        options.ciphers = (char *)-1;
1.95      markus    450:                        }
                    451:                        break;
                    452:                case 'm':
                    453:                        if (mac_valid(optarg))
                    454:                                options.macs = xstrdup(optarg);
                    455:                        else {
1.128     fgsch     456:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    457:                                    optarg);
1.257     dtucker   458:                                exit(255);
1.31      markus    459:                        }
                    460:                        break;
1.214     djm       461:                case 'M':
1.242     djm       462:                        if (options.control_master == SSHCTL_MASTER_YES)
                    463:                                options.control_master = SSHCTL_MASTER_ASK;
                    464:                        else
                    465:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       466:                        break;
1.31      markus    467:                case 'p':
1.113     stevesk   468:                        options.port = a2port(optarg);
1.323     djm       469:                        if (options.port <= 0) {
1.109     markus    470:                                fprintf(stderr, "Bad port '%s'\n", optarg);
1.257     dtucker   471:                                exit(255);
1.109     markus    472:                        }
1.31      markus    473:                        break;
                    474:                case 'l':
                    475:                        options.user = optarg;
                    476:                        break;
1.141     stevesk   477:
                    478:                case 'L':
1.324     djm       479:                        if (parse_forward(&fwd, optarg, 0, 0))
1.232     djm       480:                                add_local_forward(&options, &fwd);
                    481:                        else {
1.128     fgsch     482:                                fprintf(stderr,
1.232     djm       483:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     484:                                    optarg);
1.257     dtucker   485:                                exit(255);
1.31      markus    486:                        }
1.232     djm       487:                        break;
                    488:
                    489:                case 'R':
1.324     djm       490:                        if (parse_forward(&fwd, optarg, 0, 1)) {
1.232     djm       491:                                add_remote_forward(&options, &fwd);
                    492:                        } else {
1.128     fgsch     493:                                fprintf(stderr,
1.232     djm       494:                                    "Bad remote forwarding specification "
                    495:                                    "'%s'\n", optarg);
1.257     dtucker   496:                                exit(255);
1.31      markus    497:                        }
                    498:                        break;
1.108     markus    499:
                    500:                case 'D':
1.324     djm       501:                        if (parse_forward(&fwd, optarg, 1, 0)) {
1.322     stevesk   502:                                add_local_forward(&options, &fwd);
1.232     djm       503:                        } else {
1.322     stevesk   504:                                fprintf(stderr,
                    505:                                    "Bad dynamic forwarding specification "
                    506:                                    "'%s'\n", optarg);
1.257     dtucker   507:                                exit(255);
1.109     markus    508:                        }
1.108     markus    509:                        break;
                    510:
1.31      markus    511:                case 'C':
                    512:                        options.compression = 1;
                    513:                        break;
1.45      markus    514:                case 'N':
                    515:                        no_shell_flag = 1;
                    516:                        no_tty_flag = 1;
                    517:                        break;
                    518:                case 'T':
                    519:                        no_tty_flag = 1;
                    520:                        break;
1.31      markus    521:                case 'o':
                    522:                        dummy = 1;
1.205     markus    523:                        line = xstrdup(optarg);
1.128     fgsch     524:                        if (process_config_line(&options, host ? host : "",
1.205     markus    525:                            line, "command-line", 0, &dummy) != 0)
1.257     dtucker   526:                                exit(255);
1.205     markus    527:                        xfree(line);
1.31      markus    528:                        break;
1.85      djm       529:                case 's':
                    530:                        subsystem_flag = 1;
1.117     markus    531:                        break;
1.214     djm       532:                case 'S':
                    533:                        if (options.control_path != NULL)
                    534:                                free(options.control_path);
                    535:                        options.control_path = xstrdup(optarg);
                    536:                        break;
1.117     markus    537:                case 'b':
                    538:                        options.bind_address = optarg;
1.85      djm       539:                        break;
1.139     markus    540:                case 'F':
                    541:                        config = optarg;
                    542:                        break;
1.31      markus    543:                default:
                    544:                        usage();
1.1       deraadt   545:                }
1.31      markus    546:        }
                    547:
1.128     fgsch     548:        ac -= optind;
                    549:        av += optind;
                    550:
1.329     guenther  551:        if (ac > 0 && !host) {
1.188     markus    552:                if (strrchr(*av, '@')) {
1.128     fgsch     553:                        p = xstrdup(*av);
1.188     markus    554:                        cp = strrchr(p, '@');
1.128     fgsch     555:                        if (cp == NULL || cp == p)
                    556:                                usage();
                    557:                        options.user = p;
                    558:                        *cp = '\0';
                    559:                        host = ++cp;
                    560:                } else
                    561:                        host = *av;
1.189     millert   562:                if (ac > 1) {
                    563:                        optind = optreset = 1;
1.128     fgsch     564:                        goto again;
                    565:                }
1.189     millert   566:                ac--, av++;
1.128     fgsch     567:        }
                    568:
1.31      markus    569:        /* Check that we got a host name. */
                    570:        if (!host)
                    571:                usage();
                    572:
1.54      markus    573:        SSLeay_add_all_algorithms();
1.72      markus    574:        ERR_load_crypto_strings();
1.31      markus    575:
                    576:        /* Initialize the command to execute on remote host. */
                    577:        buffer_init(&command);
1.1       deraadt   578:
1.33      markus    579:        /*
                    580:         * Save the command to execute on the remote host in a buffer. There
                    581:         * is no limit on the length of the command, except by the maximum
                    582:         * packet size.  Also sets the tty flag if there is no command.
                    583:         */
1.128     fgsch     584:        if (!ac) {
1.31      markus    585:                /* No command specified - execute shell on a tty. */
                    586:                tty_flag = 1;
1.85      djm       587:                if (subsystem_flag) {
1.128     fgsch     588:                        fprintf(stderr,
                    589:                            "You must specify a subsystem to invoke.\n");
1.85      djm       590:                        usage();
                    591:                }
1.31      markus    592:        } else {
1.128     fgsch     593:                /* A command has been specified.  Store it into the buffer. */
                    594:                for (i = 0; i < ac; i++) {
                    595:                        if (i)
1.31      markus    596:                                buffer_append(&command, " ", 1);
                    597:                        buffer_append(&command, av[i], strlen(av[i]));
                    598:                }
                    599:        }
                    600:
                    601:        /* Cannot fork to background if no command. */
1.316     djm       602:        if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
                    603:            !no_shell_flag)
                    604:                fatal("Cannot fork into background without a command "
                    605:                    "to execute.");
1.31      markus    606:
                    607:        /* Allocate a tty by default if no command specified. */
                    608:        if (buffer_len(&command) == 0)
                    609:                tty_flag = 1;
                    610:
1.180     deraadt   611:        /* Force no tty */
1.336     djm       612:        if (no_tty_flag || muxclient_command != 0)
1.75      markus    613:                tty_flag = 0;
1.31      markus    614:        /* Do not allocate a tty if stdin is not a tty. */
1.236     djm       615:        if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
1.31      markus    616:                if (tty_flag)
1.316     djm       617:                        logit("Pseudo-terminal will not be allocated because "
                    618:                            "stdin is not a terminal.");
1.31      markus    619:                tty_flag = 0;
                    620:        }
1.45      markus    621:
1.101     markus    622:        /*
                    623:         * Initialize "log" output.  Since we are the client all output
                    624:         * actually goes to stderr.
                    625:         */
1.325     markus    626:        log_init(argv0,
1.316     djm       627:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1.320     djm       628:            SYSLOG_FACILITY_USER, !use_syslog);
1.31      markus    629:
1.139     markus    630:        /*
                    631:         * Read per-user configuration file.  Ignore the system wide config
                    632:         * file if the user specifies a config file on the command line.
                    633:         */
                    634:        if (config != NULL) {
1.211     djm       635:                if (!read_config_file(config, host, &options, 0))
1.142     stevesk   636:                        fatal("Can't open user config file %.100s: "
                    637:                            "%.100s", config, strerror(errno));
1.295     stevesk   638:        } else {
1.326     dtucker   639:                r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
1.139     markus    640:                    _PATH_SSH_USER_CONFFILE);
1.326     dtucker   641:                if (r > 0 && (size_t)r < sizeof(buf))
                    642:                        (void)read_config_file(buf, host, &options, 1);
1.139     markus    643:
1.145     markus    644:                /* Read systemwide configuration file after use config. */
1.223     deraadt   645:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
1.210     djm       646:                    &options, 0);
1.139     markus    647:        }
1.31      markus    648:
                    649:        /* Fill configuration defaults. */
                    650:        fill_default_options(&options);
                    651:
1.196     djm       652:        channel_set_af(options.address_family);
                    653:
1.31      markus    654:        /* reinit */
1.325     markus    655:        log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1.31      markus    656:
                    657:        if (options.user == NULL)
                    658:                options.user = xstrdup(pw->pw_name);
                    659:
1.317     dtucker   660:        /* Get default port if port has not been set. */
                    661:        if (options.port == 0) {
                    662:                sp = getservbyname(SSH_SERVICE_NAME, "tcp");
                    663:                options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
                    664:        }
                    665:
                    666:        if (options.local_command != NULL) {
                    667:                char thishost[NI_MAXHOST];
                    668:
                    669:                if (gethostname(thishost, sizeof(thishost)) == -1)
                    670:                        fatal("gethostname: %s", strerror(errno));
                    671:                snprintf(buf, sizeof(buf), "%d", options.port);
                    672:                debug3("expanding LocalCommand: %s", options.local_command);
                    673:                cp = options.local_command;
                    674:                options.local_command = percent_expand(cp, "d", pw->pw_dir,
                    675:                    "h", options.hostname? options.hostname : host,
                    676:                     "l", thishost, "n", host, "r", options.user, "p", buf,
                    677:                     "u", pw->pw_name, (char *)NULL);
                    678:                debug3("expanded LocalCommand: %s", options.local_command);
                    679:                xfree(cp);
                    680:        }
                    681:
1.31      markus    682:        if (options.hostname != NULL)
                    683:                host = options.hostname;
1.195     markus    684:
                    685:        /* force lowercase for hostkey matching */
                    686:        if (options.host_key_alias != NULL) {
                    687:                for (p = options.host_key_alias; *p; p++)
                    688:                        if (isupper(*p))
1.271     deraadt   689:                                *p = (char)tolower(*p);
1.246     djm       690:        }
                    691:
1.190     markus    692:        if (options.proxy_command != NULL &&
1.304     dtucker   693:            strcmp(options.proxy_command, "none") == 0) {
                    694:                xfree(options.proxy_command);
1.190     markus    695:                options.proxy_command = NULL;
1.304     dtucker   696:        }
1.245     djm       697:        if (options.control_path != NULL &&
1.304     dtucker   698:            strcmp(options.control_path, "none") == 0) {
                    699:                xfree(options.control_path);
1.245     djm       700:                options.control_path = NULL;
1.304     dtucker   701:        }
1.31      markus    702:
1.214     djm       703:        if (options.control_path != NULL) {
1.275     djm       704:                char thishost[NI_MAXHOST];
1.261     djm       705:
1.275     djm       706:                if (gethostname(thishost, sizeof(thishost)) == -1)
1.261     djm       707:                        fatal("gethostname: %s", strerror(errno));
1.241     djm       708:                snprintf(buf, sizeof(buf), "%d", options.port);
                    709:                cp = tilde_expand_filename(options.control_path,
                    710:                    original_real_uid);
1.304     dtucker   711:                xfree(options.control_path);
1.241     djm       712:                options.control_path = percent_expand(cp, "p", buf, "h", host,
1.275     djm       713:                    "r", options.user, "l", thishost, (char *)NULL);
1.241     djm       714:                xfree(cp);
1.214     djm       715:        }
1.312     djm       716:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm       717:                fatal("No ControlPath specified for \"-O\" command");
1.242     djm       718:        if (options.control_path != NULL)
1.312     djm       719:                muxclient(options.control_path);
1.214     djm       720:
1.303     djm       721:        timeout_ms = options.connection_timeout * 1000;
                    722:
1.77      markus    723:        /* Open a connection to the remote host. */
1.203     djm       724:        if (ssh_connect(host, &hostaddr, options.port,
1.303     djm       725:            options.address_family, options.connection_attempts, &timeout_ms,
                    726:            options.tcp_keep_alive,
1.177     markus    727:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    728:            options.proxy_command) != 0)
1.257     dtucker   729:                exit(255);
1.31      markus    730:
1.303     djm       731:        if (timeout_ms > 0)
                    732:                debug3("timeout: %d ms remain after connect", timeout_ms);
                    733:
1.33      markus    734:        /*
                    735:         * If we successfully made the connection, load the host private key
                    736:         * in case we will need it later for combined rsa-rhosts
                    737:         * authentication. This must be done before releasing extra
                    738:         * privileges, because the file is only readable by root.
1.174     markus    739:         * If we cannot access the private keys, load the public keys
                    740:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    741:         */
1.112     markus    742:        sensitive_data.nkeys = 0;
                    743:        sensitive_data.keys = NULL;
1.173     markus    744:        sensitive_data.external_keysign = 0;
1.178     markus    745:        if (options.rhosts_rsa_authentication ||
                    746:            options.hostbased_authentication) {
1.112     markus    747:                sensitive_data.nkeys = 3;
1.274     deraadt   748:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180     deraadt   749:                    sizeof(Key));
1.177     markus    750:
                    751:                PRIV_START;
1.112     markus    752:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276     dtucker   753:                    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.112     markus    754:                sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
1.276     dtucker   755:                    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.112     markus    756:                sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
1.276     dtucker   757:                    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.177     markus    758:                PRIV_END;
1.173     markus    759:
1.181     markus    760:                if (options.hostbased_authentication == 1 &&
                    761:                    sensitive_data.keys[0] == NULL &&
1.173     markus    762:                    sensitive_data.keys[1] == NULL &&
                    763:                    sensitive_data.keys[2] == NULL) {
                    764:                        sensitive_data.keys[1] = key_load_public(
                    765:                            _PATH_HOST_DSA_KEY_FILE, NULL);
                    766:                        sensitive_data.keys[2] = key_load_public(
                    767:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    768:                        sensitive_data.external_keysign = 1;
                    769:                }
1.31      markus    770:        }
1.33      markus    771:        /*
                    772:         * Get rid of any extra privileges that we may have.  We will no
                    773:         * longer need them.  Also, extra privileges could make it very hard
                    774:         * to read identity files and other non-world-readable files from the
                    775:         * user's home directory if it happens to be on a NFS volume where
                    776:         * root is mapped to nobody.
                    777:         */
1.225     dtucker   778:        if (original_effective_uid == 0) {
                    779:                PRIV_START;
                    780:                permanently_set_uid(pw);
                    781:        }
1.31      markus    782:
1.33      markus    783:        /*
                    784:         * Now that we are back to our own permissions, create ~/.ssh
1.254     djm       785:         * directory if it doesn't already exist.
1.33      markus    786:         */
1.326     dtucker   787:        r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1.316     djm       788:            strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1.326     dtucker   789:        if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
1.57      djm       790:                if (mkdir(buf, 0700) < 0)
1.31      markus    791:                        error("Could not create directory '%.200s'.", buf);
                    792:
1.104     markus    793:        /* load options.identity_files */
                    794:        load_public_identity_files();
                    795:
                    796:        /* Expand ~ in known host file names. */
                    797:        /* XXX mem-leaks: */
1.72      markus    798:        options.system_hostfile =
                    799:            tilde_expand_filename(options.system_hostfile, original_real_uid);
                    800:        options.user_hostfile =
                    801:            tilde_expand_filename(options.user_hostfile, original_real_uid);
                    802:        options.system_hostfile2 =
                    803:            tilde_expand_filename(options.system_hostfile2, original_real_uid);
                    804:        options.user_hostfile2 =
                    805:            tilde_expand_filename(options.user_hostfile2, original_real_uid);
1.149     markus    806:
                    807:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.31      markus    808:
1.316     djm       809:        /* Log into the remote system.  Never returns if the login fails. */
1.303     djm       810:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
                    811:            pw, timeout_ms);
1.339     djm       812:
                    813:        if (packet_connection_is_on_socket()) {
                    814:                verbose("Authenticated to %s ([%s]:%d).", host,
                    815:                    get_remote_ipaddr(), get_remote_port());
                    816:        } else {
                    817:                verbose("Authenticated to %s (via proxy).", host);
                    818:        }
1.31      markus    819:
1.112     markus    820:        /* We no longer need the private host keys.  Clear them now. */
                    821:        if (sensitive_data.nkeys != 0) {
                    822:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    823:                        if (sensitive_data.keys[i] != NULL) {
                    824:                                /* Destroys contents safely */
                    825:                                debug3("clear hostkey %d", i);
                    826:                                key_free(sensitive_data.keys[i]);
                    827:                                sensitive_data.keys[i] = NULL;
                    828:                        }
                    829:                }
                    830:                xfree(sensitive_data.keys);
1.134     markus    831:        }
                    832:        for (i = 0; i < options.num_identity_files; i++) {
                    833:                if (options.identity_files[i]) {
                    834:                        xfree(options.identity_files[i]);
                    835:                        options.identity_files[i] = NULL;
                    836:                }
                    837:                if (options.identity_keys[i]) {
                    838:                        key_free(options.identity_keys[i]);
                    839:                        options.identity_keys[i] = NULL;
                    840:                }
1.112     markus    841:        }
1.31      markus    842:
1.45      markus    843:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    844:        packet_close();
1.186     djm       845:
1.312     djm       846:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm       847:                unlink(options.control_path);
                    848:
1.186     djm       849:        /*
1.203     djm       850:         * Send SIGHUP to proxy command if used. We don't wait() in
1.186     djm       851:         * case it hangs and instead rely on init to reap the child
                    852:         */
                    853:        if (proxy_command_pid > 1)
                    854:                kill(proxy_command_pid, SIGHUP);
                    855:
1.45      markus    856:        return exit_status;
                    857: }
                    858:
1.315     djm       859: /* Callback for remote forward global requests */
                    860: static void
                    861: ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
                    862: {
                    863:        Forward *rfwd = (Forward *)ctxt;
                    864:
1.324     djm       865:        /* XXX verbose() on failure? */
1.315     djm       866:        debug("remote forward %s for: listen %d, connect %s:%d",
                    867:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
                    868:            rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1.324     djm       869:        if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
1.338     markus    870:                rfwd->allocated_port = packet_get_int();
1.324     djm       871:                logit("Allocated port %u for remote forward to %s:%d",
1.338     markus    872:                    rfwd->allocated_port,
                    873:                    rfwd->connect_host, rfwd->connect_port);
1.324     djm       874:        }
                    875:
1.315     djm       876:        if (type == SSH2_MSG_REQUEST_FAILURE) {
                    877:                if (options.exit_on_forward_failure)
                    878:                        fatal("Error: remote port forwarding failed for "
                    879:                            "listen port %d", rfwd->listen_port);
                    880:                else
                    881:                        logit("Warning: remote port forwarding failed for "
                    882:                            "listen port %d", rfwd->listen_port);
                    883:        }
1.318     djm       884:        if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315     djm       885:                debug("All remote forwarding requests processed");
1.318     djm       886:                if (fork_after_authentication_flag) {
                    887:                        fork_after_authentication_flag = 0;
                    888:                        if (daemon(1, 1) < 0)
                    889:                                fatal("daemon() failed: %.200s",
                    890:                                    strerror(errno));
                    891:                }
                    892:        }
1.315     djm       893: }
                    894:
1.126     itojun    895: static void
1.331     dtucker   896: client_cleanup_stdio_fwd(int id, void *arg)
                    897: {
                    898:        debug("stdio forwarding: done");
                    899:        cleanup_exit(0);
                    900: }
                    901:
                    902: static int
                    903: client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
                    904: {
                    905:        Channel *c;
1.332     djm       906:        int in, out;
1.331     dtucker   907:
                    908:        debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
                    909:            port_to_connect);
1.332     djm       910:
                    911:        in = dup(STDIN_FILENO);
                    912:        out = dup(STDOUT_FILENO);
                    913:        if (in < 0 || out < 0)
                    914:                fatal("channel_connect_stdio_fwd: dup() in/out failed");
                    915:
                    916:        if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
                    917:            in, out)) == NULL)
1.331     dtucker   918:                return 0;
                    919:        channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
                    920:        return 1;
                    921: }
                    922:
                    923: static void
1.70      markus    924: ssh_init_forwarding(void)
                    925: {
1.86      markus    926:        int success = 0;
1.70      markus    927:        int i;
1.331     dtucker   928:
                    929:        if (stdio_forward_host != NULL) {
                    930:                if (!compat20) {
                    931:                        fatal("stdio forwarding require Protocol 2");
                    932:                }
                    933:                if (!client_setup_stdio_fwd(stdio_forward_host,
                    934:                    stdio_forward_port))
                    935:                        fatal("Failed to connect in stdio forward mode.");
                    936:        }
1.86      markus    937:
1.70      markus    938:        /* Initiate local TCP/IP port forwardings. */
                    939:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm       940:                debug("Local connections to %.200s:%d forwarded to remote "
                    941:                    "address %.200s:%d",
1.234     deraadt   942:                    (options.local_forwards[i].listen_host == NULL) ?
                    943:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       944:                    options.local_forwards[i].listen_host,
                    945:                    options.local_forwards[i].listen_port,
                    946:                    options.local_forwards[i].connect_host,
                    947:                    options.local_forwards[i].connect_port);
1.158     markus    948:                success += channel_setup_local_fwd_listener(
1.232     djm       949:                    options.local_forwards[i].listen_host,
                    950:                    options.local_forwards[i].listen_port,
                    951:                    options.local_forwards[i].connect_host,
                    952:                    options.local_forwards[i].connect_port,
1.70      markus    953:                    options.gateway_ports);
                    954:        }
1.283     markus    955:        if (i > 0 && success != i && options.exit_on_forward_failure)
                    956:                fatal("Could not request local forwarding.");
1.86      markus    957:        if (i > 0 && success == 0)
                    958:                error("Could not request local forwarding.");
1.70      markus    959:
                    960:        /* Initiate remote TCP/IP port forwardings. */
                    961:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm       962:                debug("Remote connections from %.200s:%d forwarded to "
                    963:                    "local address %.200s:%d",
1.248     djm       964:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm       965:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm       966:                    options.remote_forwards[i].listen_port,
                    967:                    options.remote_forwards[i].connect_host,
                    968:                    options.remote_forwards[i].connect_port);
1.283     markus    969:                if (channel_request_remote_forwarding(
1.232     djm       970:                    options.remote_forwards[i].listen_host,
                    971:                    options.remote_forwards[i].listen_port,
                    972:                    options.remote_forwards[i].connect_host,
1.283     markus    973:                    options.remote_forwards[i].connect_port) < 0) {
                    974:                        if (options.exit_on_forward_failure)
                    975:                                fatal("Could not request remote forwarding.");
                    976:                        else
                    977:                                logit("Warning: Could not request remote "
                    978:                                    "forwarding.");
                    979:                }
1.315     djm       980:                client_register_global_confirm(ssh_confirm_remote_forward,
                    981:                    &options.remote_forwards[i]);
1.70      markus    982:        }
1.301     djm       983:
                    984:        /* Initiate tunnel forwarding. */
                    985:        if (options.tun_open != SSH_TUNMODE_NO) {
                    986:                if (client_request_tun_fwd(options.tun_open,
                    987:                    options.tun_local, options.tun_remote) == -1) {
                    988:                        if (options.exit_on_forward_failure)
                    989:                                fatal("Could not request tunnel forwarding.");
                    990:                        else
                    991:                                error("Could not request tunnel forwarding.");
                    992:                }
                    993:        }
1.70      markus    994: }
                    995:
1.126     itojun    996: static void
1.70      markus    997: check_agent_present(void)
                    998: {
                    999:        if (options.forward_agent) {
1.254     djm      1000:                /* Clear agent forwarding if we don't have an agent. */
1.185     stevesk  1001:                if (!ssh_agent_present())
1.70      markus   1002:                        options.forward_agent = 0;
                   1003:        }
                   1004: }
                   1005:
1.126     itojun   1006: static int
1.45      markus   1007: ssh_session(void)
                   1008: {
                   1009:        int type;
                   1010:        int interactive = 0;
                   1011:        int have_tty = 0;
                   1012:        struct winsize ws;
                   1013:        char *cp;
1.243     djm      1014:        const char *display;
1.45      markus   1015:
1.31      markus   1016:        /* Enable compression if requested. */
                   1017:        if (options.compression) {
1.316     djm      1018:                debug("Requesting compression at level %d.",
                   1019:                    options.compression_level);
1.31      markus   1020:
1.316     djm      1021:                if (options.compression_level < 1 ||
                   1022:                    options.compression_level > 9)
                   1023:                        fatal("Compression level must be from 1 (fast) to "
                   1024:                            "9 (slow, best).");
1.31      markus   1025:
                   1026:                /* Send the request. */
                   1027:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                   1028:                packet_put_int(options.compression_level);
                   1029:                packet_send();
                   1030:                packet_write_wait();
1.156     markus   1031:                type = packet_read();
1.31      markus   1032:                if (type == SSH_SMSG_SUCCESS)
                   1033:                        packet_start_compression(options.compression_level);
                   1034:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun   1035:                        logit("Warning: Remote host refused compression.");
1.31      markus   1036:                else
1.316     djm      1037:                        packet_disconnect("Protocol error waiting for "
                   1038:                            "compression response.");
1.31      markus   1039:        }
                   1040:        /* Allocate a pseudo tty if appropriate. */
                   1041:        if (tty_flag) {
                   1042:                debug("Requesting pty.");
                   1043:
                   1044:                /* Start the packet. */
                   1045:                packet_start(SSH_CMSG_REQUEST_PTY);
                   1046:
                   1047:                /* Store TERM in the packet.  There is no limit on the
                   1048:                   length of the string. */
                   1049:                cp = getenv("TERM");
                   1050:                if (!cp)
                   1051:                        cp = "";
1.124     markus   1052:                packet_put_cstring(cp);
1.31      markus   1053:
                   1054:                /* Store window size in the packet. */
                   1055:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                   1056:                        memset(&ws, 0, sizeof(ws));
1.269     deraadt  1057:                packet_put_int((u_int)ws.ws_row);
                   1058:                packet_put_int((u_int)ws.ws_col);
                   1059:                packet_put_int((u_int)ws.ws_xpixel);
                   1060:                packet_put_int((u_int)ws.ws_ypixel);
1.31      markus   1061:
                   1062:                /* Store tty modes in the packet. */
1.115     stevesk  1063:                tty_make_modes(fileno(stdin), NULL);
1.31      markus   1064:
                   1065:                /* Send the packet, and wait for it to leave. */
                   1066:                packet_send();
                   1067:                packet_write_wait();
                   1068:
                   1069:                /* Read response from the server. */
1.156     markus   1070:                type = packet_read();
1.43      markus   1071:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus   1072:                        interactive = 1;
1.45      markus   1073:                        have_tty = 1;
1.43      markus   1074:                } else if (type == SSH_SMSG_FAILURE)
1.316     djm      1075:                        logit("Warning: Remote host failed or refused to "
                   1076:                            "allocate a pseudo tty.");
1.31      markus   1077:                else
1.316     djm      1078:                        packet_disconnect("Protocol error waiting for pty "
                   1079:                            "request response.");
1.31      markus   1080:        }
                   1081:        /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243     djm      1082:        display = getenv("DISPLAY");
                   1083:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1084:                char *proto, *data;
1.50      markus   1085:                /* Get reasonable local authentication information. */
1.243     djm      1086:                client_x11_get_proto(display, options.xauth_location,
1.340   ! djm      1087:                    options.forward_x11_trusted,
        !          1088:                    options.forward_x11_timeout,
        !          1089:                    &proto, &data);
1.50      markus   1090:                /* Request forwarding with authentication spoofing. */
1.316     djm      1091:                debug("Requesting X11 forwarding with authentication "
                   1092:                    "spoofing.");
1.243     djm      1093:                x11_request_forwarding_with_spoofing(0, display, proto, data);
1.31      markus   1094:
                   1095:                /* Read response from the server. */
1.156     markus   1096:                type = packet_read();
1.31      markus   1097:                if (type == SSH_SMSG_SUCCESS) {
                   1098:                        interactive = 1;
1.50      markus   1099:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun   1100:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus   1101:                } else {
1.316     djm      1102:                        packet_disconnect("Protocol error waiting for X11 "
                   1103:                            "forwarding");
1.50      markus   1104:                }
1.31      markus   1105:        }
                   1106:        /* Tell the packet module whether this is an interactive session. */
1.80      markus   1107:        packet_set_interactive(interactive);
1.31      markus   1108:
                   1109:        /* Request authentication agent forwarding if appropriate. */
1.70      markus   1110:        check_agent_present();
                   1111:
1.31      markus   1112:        if (options.forward_agent) {
                   1113:                debug("Requesting authentication agent forwarding.");
                   1114:                auth_request_forwarding();
                   1115:
                   1116:                /* Read response from the server. */
1.156     markus   1117:                type = packet_read();
1.155     markus   1118:                packet_check_eom();
1.31      markus   1119:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun   1120:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus   1121:        }
                   1122:
1.70      markus   1123:        /* Initiate port forwardings. */
                   1124:        ssh_init_forwarding();
1.305     dtucker  1125:
                   1126:        /* Execute a local command */
                   1127:        if (options.local_command != NULL &&
                   1128:            options.permit_local_command)
                   1129:                ssh_local_cmd(options.local_command);
1.34      markus   1130:
1.318     djm      1131:        /*
                   1132:         * If requested and we are not interested in replies to remote
                   1133:         * forwarding requests, then let ssh continue in the background.
                   1134:         */
                   1135:        if (fork_after_authentication_flag &&
                   1136:            (!options.exit_on_forward_failure ||
                   1137:            options.num_remote_forwards == 0)) {
                   1138:                fork_after_authentication_flag = 0;
1.34      markus   1139:                if (daemon(1, 1) < 0)
                   1140:                        fatal("daemon() failed: %.200s", strerror(errno));
1.318     djm      1141:        }
1.31      markus   1142:
1.33      markus   1143:        /*
                   1144:         * If a command was specified on the command line, execute the
                   1145:         * command now. Otherwise request the server to start a shell.
                   1146:         */
1.31      markus   1147:        if (buffer_len(&command) > 0) {
                   1148:                int len = buffer_len(&command);
                   1149:                if (len > 900)
                   1150:                        len = 900;
1.316     djm      1151:                debug("Sending command: %.*s", len,
                   1152:                    (u_char *)buffer_ptr(&command));
1.31      markus   1153:                packet_start(SSH_CMSG_EXEC_CMD);
                   1154:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1155:                packet_send();
                   1156:                packet_write_wait();
                   1157:        } else {
                   1158:                debug("Requesting shell.");
                   1159:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1160:                packet_send();
                   1161:                packet_write_wait();
                   1162:        }
                   1163:
                   1164:        /* Enter the interactive session. */
1.119     stevesk  1165:        return client_loop(have_tty, tty_flag ?
                   1166:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.89      markus   1167: }
                   1168:
1.214     djm      1169: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1170: static void
1.337     djm      1171: ssh_session2_setup(int id, int success, void *arg)
1.214     djm      1172: {
1.215     djm      1173:        extern char **environ;
1.243     djm      1174:        const char *display;
                   1175:        int interactive = tty_flag;
1.337     djm      1176:
                   1177:        if (!success)
                   1178:                return; /* No need for error message, channels code sens one */
1.215     djm      1179:
1.248     djm      1180:        display = getenv("DISPLAY");
1.243     djm      1181:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1182:                char *proto, *data;
1.50      markus   1183:                /* Get reasonable local authentication information. */
1.243     djm      1184:                client_x11_get_proto(display, options.xauth_location,
1.340   ! djm      1185:                    options.forward_x11_trusted,
        !          1186:                    options.forward_x11_timeout, &proto, &data);
1.50      markus   1187:                /* Request forwarding with authentication spoofing. */
1.316     djm      1188:                debug("Requesting X11 forwarding with authentication "
                   1189:                    "spoofing.");
1.243     djm      1190:                x11_request_forwarding_with_spoofing(id, display, proto, data);
1.80      markus   1191:                interactive = 1;
1.50      markus   1192:                /* XXX wait for reply */
                   1193:        }
                   1194:
1.70      markus   1195:        check_agent_present();
                   1196:        if (options.forward_agent) {
                   1197:                debug("Requesting authentication agent forwarding.");
                   1198:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1199:                packet_send();
1.212     djm      1200:        }
                   1201:
1.214     djm      1202:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.311     djm      1203:            NULL, fileno(stdin), &command, environ);
1.90      markus   1204:
1.80      markus   1205:        packet_set_interactive(interactive);
1.45      markus   1206: }
                   1207:
1.143     markus   1208: /* open new channel for a session */
1.126     itojun   1209: static int
1.143     markus   1210: ssh_session2_open(void)
1.45      markus   1211: {
1.118     markus   1212:        Channel *c;
                   1213:        int window, packetmax, in, out, err;
1.60      markus   1214:
1.62      markus   1215:        if (stdin_null_flag) {
1.93      itojun   1216:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1217:        } else {
                   1218:                in = dup(STDIN_FILENO);
                   1219:        }
1.60      markus   1220:        out = dup(STDOUT_FILENO);
                   1221:        err = dup(STDERR_FILENO);
1.45      markus   1222:
                   1223:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1224:                fatal("dup() in/out/err failed");
1.45      markus   1225:
1.69      markus   1226:        /* enable nonblocking unless tty */
                   1227:        if (!isatty(in))
                   1228:                set_nonblock(in);
                   1229:        if (!isatty(out))
                   1230:                set_nonblock(out);
                   1231:        if (!isatty(err))
                   1232:                set_nonblock(err);
                   1233:
1.65      markus   1234:        window = CHAN_SES_WINDOW_DEFAULT;
                   1235:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1236:        if (tty_flag) {
                   1237:                window >>= 1;
                   1238:                packetmax >>= 1;
1.45      markus   1239:        }
1.118     markus   1240:        c = channel_new(
1.45      markus   1241:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1242:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1243:            "client-session", /*nonblock*/0);
1.45      markus   1244:
1.143     markus   1245:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1246:
1.122     markus   1247:        channel_send_open(c->self);
1.143     markus   1248:        if (!no_shell_flag)
1.310     djm      1249:                channel_register_open_confirm(c->self,
                   1250:                    ssh_session2_setup, NULL);
1.106     markus   1251:
1.118     markus   1252:        return c->self;
1.106     markus   1253: }
                   1254:
1.126     itojun   1255: static int
1.106     markus   1256: ssh_session2(void)
                   1257: {
1.143     markus   1258:        int id = -1;
1.106     markus   1259:
                   1260:        /* XXX should be pre-session */
                   1261:        ssh_init_forwarding();
                   1262:
1.143     markus   1263:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1264:                id = ssh_session2_open();
1.314     djm      1265:
                   1266:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   1267:        if (options.control_master == SSHCTL_MASTER_NO &&
                   1268:            (datafellows & SSH_NEW_OPENSSH)) {
1.314     djm      1269:                debug("Requesting no-more-sessions@openssh.com");
                   1270:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1271:                packet_put_cstring("no-more-sessions@openssh.com");
                   1272:                packet_put_char(0);
                   1273:                packet_send();
                   1274:        }
1.255     reyk     1275:
                   1276:        /* Execute a local command */
                   1277:        if (options.local_command != NULL &&
                   1278:            options.permit_local_command)
                   1279:                ssh_local_cmd(options.local_command);
1.301     djm      1280:
                   1281:        /* Start listening for multiplex clients */
1.312     djm      1282:        muxserver_listen();
1.106     markus   1283:
                   1284:        /* If requested, let ssh continue in the background. */
1.318     djm      1285:        if (fork_after_authentication_flag) {
                   1286:                fork_after_authentication_flag = 0;
1.106     markus   1287:                if (daemon(1, 1) < 0)
                   1288:                        fatal("daemon() failed: %.200s", strerror(errno));
1.318     djm      1289:        }
1.327     andreas  1290:
                   1291:        if (options.use_roaming)
                   1292:                request_roaming();
1.31      markus   1293:
1.119     stevesk  1294:        return client_loop(tty_flag, tty_flag ?
                   1295:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1296: }
                   1297:
1.126     itojun   1298: static void
1.104     markus   1299: load_public_identity_files(void)
                   1300: {
1.275     djm      1301:        char *filename, *cp, thishost[NI_MAXHOST];
1.306     deraadt  1302:        char *pwdir = NULL, *pwname = NULL;
1.167     markus   1303:        int i = 0;
1.104     markus   1304:        Key *public;
1.275     djm      1305:        struct passwd *pw;
1.335     djm      1306:        u_int n_ids;
                   1307:        char *identity_files[SSH_MAX_IDENTITY_FILES];
                   1308:        Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1.333     markus   1309: #ifdef ENABLE_PKCS11
1.167     markus   1310:        Key **keys;
1.333     markus   1311:        int nkeys;
1.335     djm      1312: #endif /* PKCS11 */
1.104     markus   1313:
1.335     djm      1314:        n_ids = 0;
                   1315:        bzero(identity_files, sizeof(identity_files));
                   1316:        bzero(identity_keys, sizeof(identity_keys));
                   1317:
                   1318: #ifdef ENABLE_PKCS11
1.333     markus   1319:        if (options.pkcs11_provider != NULL &&
1.167     markus   1320:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   1321:            (pkcs11_init(!options.batch_mode) == 0) &&
                   1322:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
                   1323:            &keys)) > 0) {
                   1324:                for (i = 0; i < nkeys; i++) {
1.335     djm      1325:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
                   1326:                                key_free(keys[i]);
                   1327:                                continue;
                   1328:                        }
                   1329:                        identity_keys[n_ids] = keys[i];
                   1330:                        identity_files[n_ids] =
1.333     markus   1331:                            xstrdup(options.pkcs11_provider); /* XXX */
1.335     djm      1332:                        n_ids++;
1.167     markus   1333:                }
                   1334:                xfree(keys);
1.127     markus   1335:        }
1.333     markus   1336: #endif /* ENABLE_PKCS11 */
1.275     djm      1337:        if ((pw = getpwuid(original_real_uid)) == NULL)
                   1338:                fatal("load_public_identity_files: getpwuid failed");
1.307     dtucker  1339:        pwname = xstrdup(pw->pw_name);
                   1340:        pwdir = xstrdup(pw->pw_dir);
1.275     djm      1341:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1342:                fatal("load_public_identity_files: gethostname: %s",
                   1343:                    strerror(errno));
1.335     djm      1344:        for (i = 0; i < options.num_identity_files; i++) {
                   1345:                if (n_ids >= SSH_MAX_IDENTITY_FILES) {
                   1346:                        xfree(options.identity_files[i]);
                   1347:                        continue;
                   1348:                }
1.275     djm      1349:                cp = tilde_expand_filename(options.identity_files[i],
1.131     millert  1350:                    original_real_uid);
1.306     deraadt  1351:                filename = percent_expand(cp, "d", pwdir,
                   1352:                    "u", pwname, "l", thishost, "h", host,
1.275     djm      1353:                    "r", options.user, (char *)NULL);
                   1354:                xfree(cp);
1.131     millert  1355:                public = key_load_public(filename, NULL);
                   1356:                debug("identity file %s type %d", filename,
                   1357:                    public ? public->type : -1);
                   1358:                xfree(options.identity_files[i]);
1.335     djm      1359:                identity_files[n_ids] = filename;
                   1360:                identity_keys[n_ids] = public;
                   1361:
                   1362:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
                   1363:                        continue;
                   1364:
                   1365:                /* Try to add the certificate variant too */
                   1366:                xasprintf(&cp, "%s-cert", filename);
                   1367:                public = key_load_public(cp, NULL);
                   1368:                debug("identity file %s type %d", cp,
                   1369:                    public ? public->type : -1);
                   1370:                if (public == NULL) {
                   1371:                        xfree(cp);
                   1372:                        continue;
                   1373:                }
                   1374:                if (!key_is_cert(public)) {
                   1375:                        debug("%s: key %s type %s is not a certificate",
                   1376:                            __func__, cp, key_type(public));
                   1377:                        key_free(public);
                   1378:                        xfree(cp);
                   1379:                        continue;
                   1380:                }
                   1381:                identity_keys[n_ids] = public;
                   1382:                /* point to the original path, most likely the private key */
                   1383:                identity_files[n_ids] = xstrdup(filename);
                   1384:                n_ids++;
                   1385:        }
                   1386:        options.num_identity_files = n_ids;
                   1387:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
                   1388:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
                   1389:
1.306     deraadt  1390:        bzero(pwname, strlen(pwname));
1.307     dtucker  1391:        xfree(pwname);
1.306     deraadt  1392:        bzero(pwdir, strlen(pwdir));
1.307     dtucker  1393:        xfree(pwdir);
1.214     djm      1394: }