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

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