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

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