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

1.343   ! djm         1: /* $OpenBSD: ssh.c,v 1.342 2010/07/12 22:38:52 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:
1.343   ! djm       667:        if (options.hostname != NULL) {
        !           668:                host = percent_expand(options.hostname,
        !           669:                    "h", host, (char *)NULL);
        !           670:        }
        !           671:
1.317     dtucker   672:        if (options.local_command != NULL) {
                    673:                char thishost[NI_MAXHOST];
                    674:
                    675:                if (gethostname(thishost, sizeof(thishost)) == -1)
                    676:                        fatal("gethostname: %s", strerror(errno));
                    677:                snprintf(buf, sizeof(buf), "%d", options.port);
                    678:                debug3("expanding LocalCommand: %s", options.local_command);
                    679:                cp = options.local_command;
                    680:                options.local_command = percent_expand(cp, "d", pw->pw_dir,
1.343   ! djm       681:                    "h", host, "l", thishost, "n", host, "r", options.user,
        !           682:                    "p", buf, "u", pw->pw_name, (char *)NULL);
1.317     dtucker   683:                debug3("expanded LocalCommand: %s", options.local_command);
                    684:                xfree(cp);
                    685:        }
1.195     markus    686:
                    687:        /* force lowercase for hostkey matching */
                    688:        if (options.host_key_alias != NULL) {
                    689:                for (p = options.host_key_alias; *p; p++)
                    690:                        if (isupper(*p))
1.271     deraadt   691:                                *p = (char)tolower(*p);
1.246     djm       692:        }
                    693:
1.190     markus    694:        if (options.proxy_command != NULL &&
1.304     dtucker   695:            strcmp(options.proxy_command, "none") == 0) {
                    696:                xfree(options.proxy_command);
1.190     markus    697:                options.proxy_command = NULL;
1.304     dtucker   698:        }
1.245     djm       699:        if (options.control_path != NULL &&
1.304     dtucker   700:            strcmp(options.control_path, "none") == 0) {
                    701:                xfree(options.control_path);
1.245     djm       702:                options.control_path = NULL;
1.304     dtucker   703:        }
1.31      markus    704:
1.214     djm       705:        if (options.control_path != NULL) {
1.275     djm       706:                char thishost[NI_MAXHOST];
1.261     djm       707:
1.275     djm       708:                if (gethostname(thishost, sizeof(thishost)) == -1)
1.261     djm       709:                        fatal("gethostname: %s", strerror(errno));
1.241     djm       710:                snprintf(buf, sizeof(buf), "%d", options.port);
                    711:                cp = tilde_expand_filename(options.control_path,
                    712:                    original_real_uid);
1.304     dtucker   713:                xfree(options.control_path);
1.241     djm       714:                options.control_path = percent_expand(cp, "p", buf, "h", host,
1.275     djm       715:                    "r", options.user, "l", thishost, (char *)NULL);
1.241     djm       716:                xfree(cp);
1.214     djm       717:        }
1.312     djm       718:        if (muxclient_command != 0 && options.control_path == NULL)
1.240     djm       719:                fatal("No ControlPath specified for \"-O\" command");
1.242     djm       720:        if (options.control_path != NULL)
1.312     djm       721:                muxclient(options.control_path);
1.214     djm       722:
1.303     djm       723:        timeout_ms = options.connection_timeout * 1000;
                    724:
1.77      markus    725:        /* Open a connection to the remote host. */
1.203     djm       726:        if (ssh_connect(host, &hostaddr, options.port,
1.303     djm       727:            options.address_family, options.connection_attempts, &timeout_ms,
                    728:            options.tcp_keep_alive,
1.177     markus    729:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    730:            options.proxy_command) != 0)
1.257     dtucker   731:                exit(255);
1.31      markus    732:
1.303     djm       733:        if (timeout_ms > 0)
                    734:                debug3("timeout: %d ms remain after connect", timeout_ms);
                    735:
1.33      markus    736:        /*
                    737:         * If we successfully made the connection, load the host private key
                    738:         * in case we will need it later for combined rsa-rhosts
                    739:         * authentication. This must be done before releasing extra
                    740:         * privileges, because the file is only readable by root.
1.174     markus    741:         * If we cannot access the private keys, load the public keys
                    742:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    743:         */
1.112     markus    744:        sensitive_data.nkeys = 0;
                    745:        sensitive_data.keys = NULL;
1.173     markus    746:        sensitive_data.external_keysign = 0;
1.178     markus    747:        if (options.rhosts_rsa_authentication ||
                    748:            options.hostbased_authentication) {
1.112     markus    749:                sensitive_data.nkeys = 3;
1.274     deraadt   750:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180     deraadt   751:                    sizeof(Key));
1.177     markus    752:
                    753:                PRIV_START;
1.112     markus    754:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276     dtucker   755:                    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.112     markus    756:                sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
1.276     dtucker   757:                    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.112     markus    758:                sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
1.276     dtucker   759:                    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.177     markus    760:                PRIV_END;
1.173     markus    761:
1.181     markus    762:                if (options.hostbased_authentication == 1 &&
                    763:                    sensitive_data.keys[0] == NULL &&
1.173     markus    764:                    sensitive_data.keys[1] == NULL &&
                    765:                    sensitive_data.keys[2] == NULL) {
                    766:                        sensitive_data.keys[1] = key_load_public(
                    767:                            _PATH_HOST_DSA_KEY_FILE, NULL);
                    768:                        sensitive_data.keys[2] = key_load_public(
                    769:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    770:                        sensitive_data.external_keysign = 1;
                    771:                }
1.31      markus    772:        }
1.33      markus    773:        /*
                    774:         * Get rid of any extra privileges that we may have.  We will no
                    775:         * longer need them.  Also, extra privileges could make it very hard
                    776:         * to read identity files and other non-world-readable files from the
                    777:         * user's home directory if it happens to be on a NFS volume where
                    778:         * root is mapped to nobody.
                    779:         */
1.225     dtucker   780:        if (original_effective_uid == 0) {
                    781:                PRIV_START;
                    782:                permanently_set_uid(pw);
                    783:        }
1.31      markus    784:
1.33      markus    785:        /*
                    786:         * Now that we are back to our own permissions, create ~/.ssh
1.254     djm       787:         * directory if it doesn't already exist.
1.33      markus    788:         */
1.326     dtucker   789:        r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1.316     djm       790:            strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1.326     dtucker   791:        if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
1.57      djm       792:                if (mkdir(buf, 0700) < 0)
1.31      markus    793:                        error("Could not create directory '%.200s'.", buf);
                    794:
1.104     markus    795:        /* load options.identity_files */
                    796:        load_public_identity_files();
                    797:
                    798:        /* Expand ~ in known host file names. */
                    799:        /* XXX mem-leaks: */
1.72      markus    800:        options.system_hostfile =
                    801:            tilde_expand_filename(options.system_hostfile, original_real_uid);
                    802:        options.user_hostfile =
                    803:            tilde_expand_filename(options.user_hostfile, original_real_uid);
                    804:        options.system_hostfile2 =
                    805:            tilde_expand_filename(options.system_hostfile2, original_real_uid);
                    806:        options.user_hostfile2 =
                    807:            tilde_expand_filename(options.user_hostfile2, original_real_uid);
1.149     markus    808:
                    809:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.31      markus    810:
1.316     djm       811:        /* Log into the remote system.  Never returns if the login fails. */
1.303     djm       812:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
                    813:            pw, timeout_ms);
1.339     djm       814:
                    815:        if (packet_connection_is_on_socket()) {
                    816:                verbose("Authenticated to %s ([%s]:%d).", host,
                    817:                    get_remote_ipaddr(), get_remote_port());
                    818:        } else {
                    819:                verbose("Authenticated to %s (via proxy).", host);
                    820:        }
1.31      markus    821:
1.112     markus    822:        /* We no longer need the private host keys.  Clear them now. */
                    823:        if (sensitive_data.nkeys != 0) {
                    824:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    825:                        if (sensitive_data.keys[i] != NULL) {
                    826:                                /* Destroys contents safely */
                    827:                                debug3("clear hostkey %d", i);
                    828:                                key_free(sensitive_data.keys[i]);
                    829:                                sensitive_data.keys[i] = NULL;
                    830:                        }
                    831:                }
                    832:                xfree(sensitive_data.keys);
1.134     markus    833:        }
                    834:        for (i = 0; i < options.num_identity_files; i++) {
                    835:                if (options.identity_files[i]) {
                    836:                        xfree(options.identity_files[i]);
                    837:                        options.identity_files[i] = NULL;
                    838:                }
                    839:                if (options.identity_keys[i]) {
                    840:                        key_free(options.identity_keys[i]);
                    841:                        options.identity_keys[i] = NULL;
                    842:                }
1.112     markus    843:        }
1.31      markus    844:
1.45      markus    845:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    846:        packet_close();
1.186     djm       847:
1.312     djm       848:        if (options.control_path != NULL && muxserver_sock != -1)
1.214     djm       849:                unlink(options.control_path);
                    850:
1.186     djm       851:        /*
1.203     djm       852:         * Send SIGHUP to proxy command if used. We don't wait() in
1.186     djm       853:         * case it hangs and instead rely on init to reap the child
                    854:         */
                    855:        if (proxy_command_pid > 1)
                    856:                kill(proxy_command_pid, SIGHUP);
                    857:
1.45      markus    858:        return exit_status;
                    859: }
                    860:
1.315     djm       861: /* Callback for remote forward global requests */
                    862: static void
                    863: ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
                    864: {
                    865:        Forward *rfwd = (Forward *)ctxt;
                    866:
1.324     djm       867:        /* XXX verbose() on failure? */
1.315     djm       868:        debug("remote forward %s for: listen %d, connect %s:%d",
                    869:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
                    870:            rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1.324     djm       871:        if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
1.338     markus    872:                rfwd->allocated_port = packet_get_int();
1.324     djm       873:                logit("Allocated port %u for remote forward to %s:%d",
1.338     markus    874:                    rfwd->allocated_port,
                    875:                    rfwd->connect_host, rfwd->connect_port);
1.324     djm       876:        }
                    877:
1.315     djm       878:        if (type == SSH2_MSG_REQUEST_FAILURE) {
                    879:                if (options.exit_on_forward_failure)
                    880:                        fatal("Error: remote port forwarding failed for "
                    881:                            "listen port %d", rfwd->listen_port);
                    882:                else
                    883:                        logit("Warning: remote port forwarding failed for "
                    884:                            "listen port %d", rfwd->listen_port);
                    885:        }
1.318     djm       886:        if (++remote_forward_confirms_received == options.num_remote_forwards) {
1.315     djm       887:                debug("All remote forwarding requests processed");
1.318     djm       888:                if (fork_after_authentication_flag) {
                    889:                        fork_after_authentication_flag = 0;
                    890:                        if (daemon(1, 1) < 0)
                    891:                                fatal("daemon() failed: %.200s",
                    892:                                    strerror(errno));
                    893:                }
                    894:        }
1.315     djm       895: }
                    896:
1.126     itojun    897: static void
1.331     dtucker   898: client_cleanup_stdio_fwd(int id, void *arg)
                    899: {
                    900:        debug("stdio forwarding: done");
                    901:        cleanup_exit(0);
                    902: }
                    903:
                    904: static int
                    905: client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
                    906: {
                    907:        Channel *c;
1.332     djm       908:        int in, out;
1.331     dtucker   909:
                    910:        debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
                    911:            port_to_connect);
1.332     djm       912:
                    913:        in = dup(STDIN_FILENO);
                    914:        out = dup(STDOUT_FILENO);
                    915:        if (in < 0 || out < 0)
                    916:                fatal("channel_connect_stdio_fwd: dup() in/out failed");
                    917:
                    918:        if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
                    919:            in, out)) == NULL)
1.331     dtucker   920:                return 0;
                    921:        channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
                    922:        return 1;
                    923: }
                    924:
                    925: static void
1.70      markus    926: ssh_init_forwarding(void)
                    927: {
1.86      markus    928:        int success = 0;
1.70      markus    929:        int i;
1.331     dtucker   930:
                    931:        if (stdio_forward_host != NULL) {
                    932:                if (!compat20) {
                    933:                        fatal("stdio forwarding require Protocol 2");
                    934:                }
                    935:                if (!client_setup_stdio_fwd(stdio_forward_host,
                    936:                    stdio_forward_port))
                    937:                        fatal("Failed to connect in stdio forward mode.");
                    938:        }
1.86      markus    939:
1.70      markus    940:        /* Initiate local TCP/IP port forwardings. */
                    941:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm       942:                debug("Local connections to %.200s:%d forwarded to remote "
                    943:                    "address %.200s:%d",
1.234     deraadt   944:                    (options.local_forwards[i].listen_host == NULL) ?
                    945:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       946:                    options.local_forwards[i].listen_host,
                    947:                    options.local_forwards[i].listen_port,
                    948:                    options.local_forwards[i].connect_host,
                    949:                    options.local_forwards[i].connect_port);
1.158     markus    950:                success += channel_setup_local_fwd_listener(
1.232     djm       951:                    options.local_forwards[i].listen_host,
                    952:                    options.local_forwards[i].listen_port,
                    953:                    options.local_forwards[i].connect_host,
                    954:                    options.local_forwards[i].connect_port,
1.70      markus    955:                    options.gateway_ports);
                    956:        }
1.283     markus    957:        if (i > 0 && success != i && options.exit_on_forward_failure)
                    958:                fatal("Could not request local forwarding.");
1.86      markus    959:        if (i > 0 && success == 0)
                    960:                error("Could not request local forwarding.");
1.70      markus    961:
                    962:        /* Initiate remote TCP/IP port forwardings. */
                    963:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm       964:                debug("Remote connections from %.200s:%d forwarded to "
                    965:                    "local address %.200s:%d",
1.248     djm       966:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm       967:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm       968:                    options.remote_forwards[i].listen_port,
                    969:                    options.remote_forwards[i].connect_host,
                    970:                    options.remote_forwards[i].connect_port);
1.283     markus    971:                if (channel_request_remote_forwarding(
1.232     djm       972:                    options.remote_forwards[i].listen_host,
                    973:                    options.remote_forwards[i].listen_port,
                    974:                    options.remote_forwards[i].connect_host,
1.283     markus    975:                    options.remote_forwards[i].connect_port) < 0) {
                    976:                        if (options.exit_on_forward_failure)
                    977:                                fatal("Could not request remote forwarding.");
                    978:                        else
                    979:                                logit("Warning: Could not request remote "
                    980:                                    "forwarding.");
                    981:                }
1.315     djm       982:                client_register_global_confirm(ssh_confirm_remote_forward,
                    983:                    &options.remote_forwards[i]);
1.70      markus    984:        }
1.301     djm       985:
                    986:        /* Initiate tunnel forwarding. */
                    987:        if (options.tun_open != SSH_TUNMODE_NO) {
                    988:                if (client_request_tun_fwd(options.tun_open,
                    989:                    options.tun_local, options.tun_remote) == -1) {
                    990:                        if (options.exit_on_forward_failure)
                    991:                                fatal("Could not request tunnel forwarding.");
                    992:                        else
                    993:                                error("Could not request tunnel forwarding.");
                    994:                }
                    995:        }
1.70      markus    996: }
                    997:
1.126     itojun    998: static void
1.70      markus    999: check_agent_present(void)
                   1000: {
                   1001:        if (options.forward_agent) {
1.254     djm      1002:                /* Clear agent forwarding if we don't have an agent. */
1.185     stevesk  1003:                if (!ssh_agent_present())
1.70      markus   1004:                        options.forward_agent = 0;
                   1005:        }
                   1006: }
                   1007:
1.126     itojun   1008: static int
1.45      markus   1009: ssh_session(void)
                   1010: {
                   1011:        int type;
                   1012:        int interactive = 0;
                   1013:        int have_tty = 0;
                   1014:        struct winsize ws;
                   1015:        char *cp;
1.243     djm      1016:        const char *display;
1.45      markus   1017:
1.31      markus   1018:        /* Enable compression if requested. */
                   1019:        if (options.compression) {
1.316     djm      1020:                debug("Requesting compression at level %d.",
                   1021:                    options.compression_level);
1.31      markus   1022:
1.316     djm      1023:                if (options.compression_level < 1 ||
                   1024:                    options.compression_level > 9)
                   1025:                        fatal("Compression level must be from 1 (fast) to "
                   1026:                            "9 (slow, best).");
1.31      markus   1027:
                   1028:                /* Send the request. */
                   1029:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                   1030:                packet_put_int(options.compression_level);
                   1031:                packet_send();
                   1032:                packet_write_wait();
1.156     markus   1033:                type = packet_read();
1.31      markus   1034:                if (type == SSH_SMSG_SUCCESS)
                   1035:                        packet_start_compression(options.compression_level);
                   1036:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun   1037:                        logit("Warning: Remote host refused compression.");
1.31      markus   1038:                else
1.316     djm      1039:                        packet_disconnect("Protocol error waiting for "
                   1040:                            "compression response.");
1.31      markus   1041:        }
                   1042:        /* Allocate a pseudo tty if appropriate. */
                   1043:        if (tty_flag) {
                   1044:                debug("Requesting pty.");
                   1045:
                   1046:                /* Start the packet. */
                   1047:                packet_start(SSH_CMSG_REQUEST_PTY);
                   1048:
                   1049:                /* Store TERM in the packet.  There is no limit on the
                   1050:                   length of the string. */
                   1051:                cp = getenv("TERM");
                   1052:                if (!cp)
                   1053:                        cp = "";
1.124     markus   1054:                packet_put_cstring(cp);
1.31      markus   1055:
                   1056:                /* Store window size in the packet. */
                   1057:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                   1058:                        memset(&ws, 0, sizeof(ws));
1.269     deraadt  1059:                packet_put_int((u_int)ws.ws_row);
                   1060:                packet_put_int((u_int)ws.ws_col);
                   1061:                packet_put_int((u_int)ws.ws_xpixel);
                   1062:                packet_put_int((u_int)ws.ws_ypixel);
1.31      markus   1063:
                   1064:                /* Store tty modes in the packet. */
1.115     stevesk  1065:                tty_make_modes(fileno(stdin), NULL);
1.31      markus   1066:
                   1067:                /* Send the packet, and wait for it to leave. */
                   1068:                packet_send();
                   1069:                packet_write_wait();
                   1070:
                   1071:                /* Read response from the server. */
1.156     markus   1072:                type = packet_read();
1.43      markus   1073:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus   1074:                        interactive = 1;
1.45      markus   1075:                        have_tty = 1;
1.43      markus   1076:                } else if (type == SSH_SMSG_FAILURE)
1.316     djm      1077:                        logit("Warning: Remote host failed or refused to "
                   1078:                            "allocate a pseudo tty.");
1.31      markus   1079:                else
1.316     djm      1080:                        packet_disconnect("Protocol error waiting for pty "
                   1081:                            "request response.");
1.31      markus   1082:        }
                   1083:        /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243     djm      1084:        display = getenv("DISPLAY");
                   1085:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1086:                char *proto, *data;
1.50      markus   1087:                /* Get reasonable local authentication information. */
1.243     djm      1088:                client_x11_get_proto(display, options.xauth_location,
1.340     djm      1089:                    options.forward_x11_trusted,
                   1090:                    options.forward_x11_timeout,
                   1091:                    &proto, &data);
1.50      markus   1092:                /* Request forwarding with authentication spoofing. */
1.316     djm      1093:                debug("Requesting X11 forwarding with authentication "
                   1094:                    "spoofing.");
1.243     djm      1095:                x11_request_forwarding_with_spoofing(0, display, proto, data);
1.31      markus   1096:
                   1097:                /* Read response from the server. */
1.156     markus   1098:                type = packet_read();
1.31      markus   1099:                if (type == SSH_SMSG_SUCCESS) {
                   1100:                        interactive = 1;
1.50      markus   1101:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun   1102:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus   1103:                } else {
1.316     djm      1104:                        packet_disconnect("Protocol error waiting for X11 "
                   1105:                            "forwarding");
1.50      markus   1106:                }
1.31      markus   1107:        }
                   1108:        /* Tell the packet module whether this is an interactive session. */
1.80      markus   1109:        packet_set_interactive(interactive);
1.31      markus   1110:
                   1111:        /* Request authentication agent forwarding if appropriate. */
1.70      markus   1112:        check_agent_present();
                   1113:
1.31      markus   1114:        if (options.forward_agent) {
                   1115:                debug("Requesting authentication agent forwarding.");
                   1116:                auth_request_forwarding();
                   1117:
                   1118:                /* Read response from the server. */
1.156     markus   1119:                type = packet_read();
1.155     markus   1120:                packet_check_eom();
1.31      markus   1121:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun   1122:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus   1123:        }
                   1124:
1.70      markus   1125:        /* Initiate port forwardings. */
                   1126:        ssh_init_forwarding();
1.305     dtucker  1127:
                   1128:        /* Execute a local command */
                   1129:        if (options.local_command != NULL &&
                   1130:            options.permit_local_command)
                   1131:                ssh_local_cmd(options.local_command);
1.34      markus   1132:
1.318     djm      1133:        /*
                   1134:         * If requested and we are not interested in replies to remote
                   1135:         * forwarding requests, then let ssh continue in the background.
                   1136:         */
                   1137:        if (fork_after_authentication_flag &&
                   1138:            (!options.exit_on_forward_failure ||
                   1139:            options.num_remote_forwards == 0)) {
                   1140:                fork_after_authentication_flag = 0;
1.34      markus   1141:                if (daemon(1, 1) < 0)
                   1142:                        fatal("daemon() failed: %.200s", strerror(errno));
1.318     djm      1143:        }
1.31      markus   1144:
1.33      markus   1145:        /*
                   1146:         * If a command was specified on the command line, execute the
                   1147:         * command now. Otherwise request the server to start a shell.
                   1148:         */
1.31      markus   1149:        if (buffer_len(&command) > 0) {
                   1150:                int len = buffer_len(&command);
                   1151:                if (len > 900)
                   1152:                        len = 900;
1.316     djm      1153:                debug("Sending command: %.*s", len,
                   1154:                    (u_char *)buffer_ptr(&command));
1.31      markus   1155:                packet_start(SSH_CMSG_EXEC_CMD);
                   1156:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1157:                packet_send();
                   1158:                packet_write_wait();
                   1159:        } else {
                   1160:                debug("Requesting shell.");
                   1161:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1162:                packet_send();
                   1163:                packet_write_wait();
                   1164:        }
                   1165:
                   1166:        /* Enter the interactive session. */
1.119     stevesk  1167:        return client_loop(have_tty, tty_flag ?
                   1168:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.89      markus   1169: }
                   1170:
1.214     djm      1171: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1172: static void
1.337     djm      1173: ssh_session2_setup(int id, int success, void *arg)
1.214     djm      1174: {
1.215     djm      1175:        extern char **environ;
1.243     djm      1176:        const char *display;
                   1177:        int interactive = tty_flag;
1.337     djm      1178:
                   1179:        if (!success)
                   1180:                return; /* No need for error message, channels code sens one */
1.215     djm      1181:
1.248     djm      1182:        display = getenv("DISPLAY");
1.243     djm      1183:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1184:                char *proto, *data;
1.50      markus   1185:                /* Get reasonable local authentication information. */
1.243     djm      1186:                client_x11_get_proto(display, options.xauth_location,
1.340     djm      1187:                    options.forward_x11_trusted,
                   1188:                    options.forward_x11_timeout, &proto, &data);
1.50      markus   1189:                /* Request forwarding with authentication spoofing. */
1.316     djm      1190:                debug("Requesting X11 forwarding with authentication "
                   1191:                    "spoofing.");
1.243     djm      1192:                x11_request_forwarding_with_spoofing(id, display, proto, data);
1.80      markus   1193:                interactive = 1;
1.50      markus   1194:                /* XXX wait for reply */
                   1195:        }
                   1196:
1.70      markus   1197:        check_agent_present();
                   1198:        if (options.forward_agent) {
                   1199:                debug("Requesting authentication agent forwarding.");
                   1200:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1201:                packet_send();
1.212     djm      1202:        }
                   1203:
1.214     djm      1204:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.311     djm      1205:            NULL, fileno(stdin), &command, environ);
1.90      markus   1206:
1.80      markus   1207:        packet_set_interactive(interactive);
1.45      markus   1208: }
                   1209:
1.143     markus   1210: /* open new channel for a session */
1.126     itojun   1211: static int
1.143     markus   1212: ssh_session2_open(void)
1.45      markus   1213: {
1.118     markus   1214:        Channel *c;
                   1215:        int window, packetmax, in, out, err;
1.60      markus   1216:
1.62      markus   1217:        if (stdin_null_flag) {
1.93      itojun   1218:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1219:        } else {
                   1220:                in = dup(STDIN_FILENO);
                   1221:        }
1.60      markus   1222:        out = dup(STDOUT_FILENO);
                   1223:        err = dup(STDERR_FILENO);
1.45      markus   1224:
                   1225:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1226:                fatal("dup() in/out/err failed");
1.45      markus   1227:
1.69      markus   1228:        /* enable nonblocking unless tty */
                   1229:        if (!isatty(in))
                   1230:                set_nonblock(in);
                   1231:        if (!isatty(out))
                   1232:                set_nonblock(out);
                   1233:        if (!isatty(err))
                   1234:                set_nonblock(err);
                   1235:
1.65      markus   1236:        window = CHAN_SES_WINDOW_DEFAULT;
                   1237:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1238:        if (tty_flag) {
                   1239:                window >>= 1;
                   1240:                packetmax >>= 1;
1.45      markus   1241:        }
1.118     markus   1242:        c = channel_new(
1.45      markus   1243:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1244:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1245:            "client-session", /*nonblock*/0);
1.45      markus   1246:
1.143     markus   1247:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1248:
1.122     markus   1249:        channel_send_open(c->self);
1.143     markus   1250:        if (!no_shell_flag)
1.310     djm      1251:                channel_register_open_confirm(c->self,
                   1252:                    ssh_session2_setup, NULL);
1.106     markus   1253:
1.118     markus   1254:        return c->self;
1.106     markus   1255: }
                   1256:
1.126     itojun   1257: static int
1.106     markus   1258: ssh_session2(void)
                   1259: {
1.143     markus   1260:        int id = -1;
1.106     markus   1261:
                   1262:        /* XXX should be pre-session */
                   1263:        ssh_init_forwarding();
                   1264:
1.143     markus   1265:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1266:                id = ssh_session2_open();
1.314     djm      1267:
                   1268:        /* If we don't expect to open a new session, then disallow it */
1.319     markus   1269:        if (options.control_master == SSHCTL_MASTER_NO &&
                   1270:            (datafellows & SSH_NEW_OPENSSH)) {
1.314     djm      1271:                debug("Requesting no-more-sessions@openssh.com");
                   1272:                packet_start(SSH2_MSG_GLOBAL_REQUEST);
                   1273:                packet_put_cstring("no-more-sessions@openssh.com");
                   1274:                packet_put_char(0);
                   1275:                packet_send();
                   1276:        }
1.255     reyk     1277:
                   1278:        /* Execute a local command */
                   1279:        if (options.local_command != NULL &&
                   1280:            options.permit_local_command)
                   1281:                ssh_local_cmd(options.local_command);
1.301     djm      1282:
                   1283:        /* Start listening for multiplex clients */
1.312     djm      1284:        muxserver_listen();
1.106     markus   1285:
1.342     djm      1286:        /*
                   1287:         * If requested and we are not interested in replies to remote
                   1288:         * forwarding requests, then let ssh continue in the background.
                   1289:         */
                   1290:        if (fork_after_authentication_flag &&
                   1291:            (!options.exit_on_forward_failure ||
                   1292:            options.num_remote_forwards == 0)) {
1.318     djm      1293:                fork_after_authentication_flag = 0;
1.106     markus   1294:                if (daemon(1, 1) < 0)
                   1295:                        fatal("daemon() failed: %.200s", strerror(errno));
1.318     djm      1296:        }
1.327     andreas  1297:
                   1298:        if (options.use_roaming)
                   1299:                request_roaming();
1.31      markus   1300:
1.119     stevesk  1301:        return client_loop(tty_flag, tty_flag ?
                   1302:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1303: }
                   1304:
1.126     itojun   1305: static void
1.104     markus   1306: load_public_identity_files(void)
                   1307: {
1.275     djm      1308:        char *filename, *cp, thishost[NI_MAXHOST];
1.306     deraadt  1309:        char *pwdir = NULL, *pwname = NULL;
1.167     markus   1310:        int i = 0;
1.104     markus   1311:        Key *public;
1.275     djm      1312:        struct passwd *pw;
1.335     djm      1313:        u_int n_ids;
                   1314:        char *identity_files[SSH_MAX_IDENTITY_FILES];
                   1315:        Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1.333     markus   1316: #ifdef ENABLE_PKCS11
1.167     markus   1317:        Key **keys;
1.333     markus   1318:        int nkeys;
1.335     djm      1319: #endif /* PKCS11 */
1.104     markus   1320:
1.335     djm      1321:        n_ids = 0;
                   1322:        bzero(identity_files, sizeof(identity_files));
                   1323:        bzero(identity_keys, sizeof(identity_keys));
                   1324:
                   1325: #ifdef ENABLE_PKCS11
1.333     markus   1326:        if (options.pkcs11_provider != NULL &&
1.167     markus   1327:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.333     markus   1328:            (pkcs11_init(!options.batch_mode) == 0) &&
                   1329:            (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
                   1330:            &keys)) > 0) {
                   1331:                for (i = 0; i < nkeys; i++) {
1.335     djm      1332:                        if (n_ids >= SSH_MAX_IDENTITY_FILES) {
                   1333:                                key_free(keys[i]);
                   1334:                                continue;
                   1335:                        }
                   1336:                        identity_keys[n_ids] = keys[i];
                   1337:                        identity_files[n_ids] =
1.333     markus   1338:                            xstrdup(options.pkcs11_provider); /* XXX */
1.335     djm      1339:                        n_ids++;
1.167     markus   1340:                }
                   1341:                xfree(keys);
1.127     markus   1342:        }
1.333     markus   1343: #endif /* ENABLE_PKCS11 */
1.275     djm      1344:        if ((pw = getpwuid(original_real_uid)) == NULL)
                   1345:                fatal("load_public_identity_files: getpwuid failed");
1.307     dtucker  1346:        pwname = xstrdup(pw->pw_name);
                   1347:        pwdir = xstrdup(pw->pw_dir);
1.275     djm      1348:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1349:                fatal("load_public_identity_files: gethostname: %s",
                   1350:                    strerror(errno));
1.335     djm      1351:        for (i = 0; i < options.num_identity_files; i++) {
                   1352:                if (n_ids >= SSH_MAX_IDENTITY_FILES) {
                   1353:                        xfree(options.identity_files[i]);
                   1354:                        continue;
                   1355:                }
1.275     djm      1356:                cp = tilde_expand_filename(options.identity_files[i],
1.131     millert  1357:                    original_real_uid);
1.306     deraadt  1358:                filename = percent_expand(cp, "d", pwdir,
                   1359:                    "u", pwname, "l", thishost, "h", host,
1.275     djm      1360:                    "r", options.user, (char *)NULL);
                   1361:                xfree(cp);
1.131     millert  1362:                public = key_load_public(filename, NULL);
                   1363:                debug("identity file %s type %d", filename,
                   1364:                    public ? public->type : -1);
                   1365:                xfree(options.identity_files[i]);
1.335     djm      1366:                identity_files[n_ids] = filename;
                   1367:                identity_keys[n_ids] = public;
                   1368:
                   1369:                if (++n_ids >= SSH_MAX_IDENTITY_FILES)
                   1370:                        continue;
                   1371:
                   1372:                /* Try to add the certificate variant too */
                   1373:                xasprintf(&cp, "%s-cert", filename);
                   1374:                public = key_load_public(cp, NULL);
                   1375:                debug("identity file %s type %d", cp,
                   1376:                    public ? public->type : -1);
                   1377:                if (public == NULL) {
                   1378:                        xfree(cp);
                   1379:                        continue;
                   1380:                }
                   1381:                if (!key_is_cert(public)) {
                   1382:                        debug("%s: key %s type %s is not a certificate",
                   1383:                            __func__, cp, key_type(public));
                   1384:                        key_free(public);
                   1385:                        xfree(cp);
                   1386:                        continue;
                   1387:                }
                   1388:                identity_keys[n_ids] = public;
                   1389:                /* point to the original path, most likely the private key */
                   1390:                identity_files[n_ids] = xstrdup(filename);
                   1391:                n_ids++;
                   1392:        }
                   1393:        options.num_identity_files = n_ids;
                   1394:        memcpy(options.identity_files, identity_files, sizeof(identity_files));
                   1395:        memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
                   1396:
1.306     deraadt  1397:        bzero(pwname, strlen(pwname));
1.307     dtucker  1398:        xfree(pwname);
1.306     deraadt  1399:        bzero(pwdir, strlen(pwdir));
1.307     dtucker  1400:        xfree(pwdir);
1.214     djm      1401: }