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

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