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

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