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

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.242   ! djm        43: RCSID("$OpenBSD: ssh.c,v 1.241 2005/06/06 11:20:36 djm 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.229     djm       147: /* Multiplexing control command */
1.240     djm       148: static u_int mux_command = 0;
1.229     djm       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.230     jmc       160: "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
1.233     jmc       161: "           [-D port] [-e escape_char] [-F configfile]\n"
                    162: "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
1.232     djm       163: "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
1.233     jmc       164: "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
1.230     jmc       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.232     djm       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.229     djm       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.229     djm       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.231     otto      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.227     deraadt   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.242   ! djm       384:                        if (options.control_master == SSHCTL_MASTER_YES)
        !           385:                                options.control_master = SSHCTL_MASTER_ASK;
        !           386:                        else
        !           387:                                options.control_master = SSHCTL_MASTER_YES;
1.214     djm       388:                        break;
1.31      markus    389:                case 'p':
1.113     stevesk   390:                        options.port = a2port(optarg);
                    391:                        if (options.port == 0) {
1.109     markus    392:                                fprintf(stderr, "Bad port '%s'\n", optarg);
                    393:                                exit(1);
                    394:                        }
1.31      markus    395:                        break;
                    396:                case 'l':
                    397:                        options.user = optarg;
                    398:                        break;
1.141     stevesk   399:
                    400:                case 'L':
1.232     djm       401:                        if (parse_forward(&fwd, optarg))
                    402:                                add_local_forward(&options, &fwd);
                    403:                        else {
1.128     fgsch     404:                                fprintf(stderr,
1.232     djm       405:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     406:                                    optarg);
1.232     djm       407:                                exit(1);
1.31      markus    408:                        }
1.232     djm       409:                        break;
                    410:
                    411:                case 'R':
                    412:                        if (parse_forward(&fwd, optarg)) {
                    413:                                add_remote_forward(&options, &fwd);
                    414:                        } else {
1.128     fgsch     415:                                fprintf(stderr,
1.232     djm       416:                                    "Bad remote forwarding specification "
                    417:                                    "'%s'\n", optarg);
1.141     stevesk   418:                                exit(1);
1.31      markus    419:                        }
                    420:                        break;
1.108     markus    421:
                    422:                case 'D':
1.232     djm       423:                        cp = p = xstrdup(optarg);
                    424:                        memset(&fwd, '\0', sizeof(fwd));
                    425:                        fwd.connect_host = "socks";
                    426:                        if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
                    427:                                fprintf(stderr, "Bad dynamic forwarding "
                    428:                                    "specification '%.100s'\n", optarg);
                    429:                                exit(1);
                    430:                        }
                    431:                        if (cp != NULL) {
                    432:                                fwd.listen_port = a2port(cp);
                    433:                                fwd.listen_host = cleanhostname(fwd.listen_host);
                    434:                        } else {
                    435:                                fwd.listen_port = a2port(fwd.listen_host);
                    436:                                fwd.listen_host = "";
                    437:                        }
                    438:
                    439:                        if (fwd.listen_port == 0) {
1.128     fgsch     440:                                fprintf(stderr, "Bad dynamic port '%s'\n",
                    441:                                    optarg);
1.109     markus    442:                                exit(1);
                    443:                        }
1.232     djm       444:                        add_local_forward(&options, &fwd);
                    445:                        xfree(p);
1.108     markus    446:                        break;
                    447:
1.31      markus    448:                case 'C':
                    449:                        options.compression = 1;
                    450:                        break;
1.45      markus    451:                case 'N':
                    452:                        no_shell_flag = 1;
                    453:                        no_tty_flag = 1;
                    454:                        break;
                    455:                case 'T':
                    456:                        no_tty_flag = 1;
                    457:                        break;
1.31      markus    458:                case 'o':
                    459:                        dummy = 1;
1.205     markus    460:                        line = xstrdup(optarg);
1.128     fgsch     461:                        if (process_config_line(&options, host ? host : "",
1.205     markus    462:                            line, "command-line", 0, &dummy) != 0)
1.31      markus    463:                                exit(1);
1.205     markus    464:                        xfree(line);
1.31      markus    465:                        break;
1.85      djm       466:                case 's':
                    467:                        subsystem_flag = 1;
1.117     markus    468:                        break;
1.214     djm       469:                case 'S':
                    470:                        if (options.control_path != NULL)
                    471:                                free(options.control_path);
                    472:                        options.control_path = xstrdup(optarg);
                    473:                        break;
1.117     markus    474:                case 'b':
                    475:                        options.bind_address = optarg;
1.85      djm       476:                        break;
1.139     markus    477:                case 'F':
                    478:                        config = optarg;
                    479:                        break;
1.31      markus    480:                default:
                    481:                        usage();
1.1       deraadt   482:                }
1.31      markus    483:        }
                    484:
1.128     fgsch     485:        ac -= optind;
                    486:        av += optind;
                    487:
                    488:        if (ac > 0 && !host && **av != '-') {
1.188     markus    489:                if (strrchr(*av, '@')) {
1.128     fgsch     490:                        p = xstrdup(*av);
1.188     markus    491:                        cp = strrchr(p, '@');
1.128     fgsch     492:                        if (cp == NULL || cp == p)
                    493:                                usage();
                    494:                        options.user = p;
                    495:                        *cp = '\0';
                    496:                        host = ++cp;
                    497:                } else
                    498:                        host = *av;
1.189     millert   499:                if (ac > 1) {
                    500:                        optind = optreset = 1;
1.128     fgsch     501:                        goto again;
                    502:                }
1.189     millert   503:                ac--, av++;
1.128     fgsch     504:        }
                    505:
1.31      markus    506:        /* Check that we got a host name. */
                    507:        if (!host)
                    508:                usage();
                    509:
1.54      markus    510:        SSLeay_add_all_algorithms();
1.72      markus    511:        ERR_load_crypto_strings();
1.31      markus    512:
                    513:        /* Initialize the command to execute on remote host. */
                    514:        buffer_init(&command);
1.1       deraadt   515:
1.33      markus    516:        /*
                    517:         * Save the command to execute on the remote host in a buffer. There
                    518:         * is no limit on the length of the command, except by the maximum
                    519:         * packet size.  Also sets the tty flag if there is no command.
                    520:         */
1.128     fgsch     521:        if (!ac) {
1.31      markus    522:                /* No command specified - execute shell on a tty. */
                    523:                tty_flag = 1;
1.85      djm       524:                if (subsystem_flag) {
1.128     fgsch     525:                        fprintf(stderr,
                    526:                            "You must specify a subsystem to invoke.\n");
1.85      djm       527:                        usage();
                    528:                }
1.31      markus    529:        } else {
1.128     fgsch     530:                /* A command has been specified.  Store it into the buffer. */
                    531:                for (i = 0; i < ac; i++) {
                    532:                        if (i)
1.31      markus    533:                                buffer_append(&command, " ", 1);
                    534:                        buffer_append(&command, av[i], strlen(av[i]));
                    535:                }
                    536:        }
                    537:
                    538:        /* Cannot fork to background if no command. */
1.63      markus    539:        if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
1.31      markus    540:                fatal("Cannot fork into background without a command to execute.");
                    541:
                    542:        /* Allocate a tty by default if no command specified. */
                    543:        if (buffer_len(&command) == 0)
                    544:                tty_flag = 1;
                    545:
1.180     deraadt   546:        /* Force no tty */
1.75      markus    547:        if (no_tty_flag)
                    548:                tty_flag = 0;
1.31      markus    549:        /* Do not allocate a tty if stdin is not a tty. */
1.236     djm       550:        if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
1.31      markus    551:                if (tty_flag)
1.191     itojun    552:                        logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
1.31      markus    553:                tty_flag = 0;
                    554:        }
1.45      markus    555:
1.101     markus    556:        /*
                    557:         * Initialize "log" output.  Since we are the client all output
                    558:         * actually goes to stderr.
                    559:         */
1.111     markus    560:        log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
                    561:            SYSLOG_FACILITY_USER, 1);
1.31      markus    562:
1.139     markus    563:        /*
                    564:         * Read per-user configuration file.  Ignore the system wide config
                    565:         * file if the user specifies a config file on the command line.
                    566:         */
                    567:        if (config != NULL) {
1.211     djm       568:                if (!read_config_file(config, host, &options, 0))
1.142     stevesk   569:                        fatal("Can't open user config file %.100s: "
                    570:                            "%.100s", config, strerror(errno));
1.139     markus    571:        } else  {
                    572:                snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
                    573:                    _PATH_SSH_USER_CONFFILE);
1.210     djm       574:                (void)read_config_file(buf, host, &options, 1);
1.139     markus    575:
1.145     markus    576:                /* Read systemwide configuration file after use config. */
1.223     deraadt   577:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
1.210     djm       578:                    &options, 0);
1.139     markus    579:        }
1.31      markus    580:
                    581:        /* Fill configuration defaults. */
                    582:        fill_default_options(&options);
                    583:
1.196     djm       584:        channel_set_af(options.address_family);
                    585:
1.31      markus    586:        /* reinit */
1.101     markus    587:        log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
1.31      markus    588:
                    589:        if (options.user == NULL)
                    590:                options.user = xstrdup(pw->pw_name);
                    591:
                    592:        if (options.hostname != NULL)
                    593:                host = options.hostname;
1.195     markus    594:
                    595:        /* force lowercase for hostkey matching */
                    596:        if (options.host_key_alias != NULL) {
                    597:                for (p = options.host_key_alias; *p; p++)
                    598:                        if (isupper(*p))
                    599:                                *p = tolower(*p);
                    600:        }
1.190     markus    601:
                    602:        if (options.proxy_command != NULL &&
                    603:            strcmp(options.proxy_command, "none") == 0)
                    604:                options.proxy_command = NULL;
1.31      markus    605:
1.214     djm       606:        if (options.control_path != NULL) {
1.241     djm       607:                snprintf(buf, sizeof(buf), "%d", options.port);
                    608:                cp = tilde_expand_filename(options.control_path,
                    609:                    original_real_uid);
                    610:                options.control_path = percent_expand(cp, "p", buf, "h", host,
                    611:                    "r", options.user, (char *)NULL);
                    612:                xfree(cp);
1.214     djm       613:        }
1.240     djm       614:        if (mux_command != 0 && options.control_path == NULL)
                    615:                fatal("No ControlPath specified for \"-O\" command");
1.242   ! djm       616:        if (options.control_path != NULL)
1.237     jakob     617:                control_client(options.control_path);
1.214     djm       618:
1.77      markus    619:        /* Open a connection to the remote host. */
1.203     djm       620:        if (ssh_connect(host, &hostaddr, options.port,
1.196     djm       621:            options.address_family, options.connection_attempts,
1.177     markus    622:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    623:            options.proxy_command) != 0)
1.178     markus    624:                exit(1);
1.31      markus    625:
1.33      markus    626:        /*
                    627:         * If we successfully made the connection, load the host private key
                    628:         * in case we will need it later for combined rsa-rhosts
                    629:         * authentication. This must be done before releasing extra
                    630:         * privileges, because the file is only readable by root.
1.174     markus    631:         * If we cannot access the private keys, load the public keys
                    632:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    633:         */
1.112     markus    634:        sensitive_data.nkeys = 0;
                    635:        sensitive_data.keys = NULL;
1.173     markus    636:        sensitive_data.external_keysign = 0;
1.178     markus    637:        if (options.rhosts_rsa_authentication ||
                    638:            options.hostbased_authentication) {
1.112     markus    639:                sensitive_data.nkeys = 3;
1.180     deraadt   640:                sensitive_data.keys = xmalloc(sensitive_data.nkeys *
                    641:                    sizeof(Key));
1.177     markus    642:
                    643:                PRIV_START;
1.112     markus    644:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.105     markus    645:                    _PATH_HOST_KEY_FILE, "", NULL);
1.112     markus    646:                sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
                    647:                    _PATH_HOST_DSA_KEY_FILE, "", NULL);
                    648:                sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
                    649:                    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1.177     markus    650:                PRIV_END;
1.173     markus    651:
1.181     markus    652:                if (options.hostbased_authentication == 1 &&
                    653:                    sensitive_data.keys[0] == NULL &&
1.173     markus    654:                    sensitive_data.keys[1] == NULL &&
                    655:                    sensitive_data.keys[2] == NULL) {
                    656:                        sensitive_data.keys[1] = key_load_public(
                    657:                            _PATH_HOST_DSA_KEY_FILE, NULL);
                    658:                        sensitive_data.keys[2] = key_load_public(
                    659:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    660:                        sensitive_data.external_keysign = 1;
                    661:                }
1.31      markus    662:        }
1.33      markus    663:        /*
                    664:         * Get rid of any extra privileges that we may have.  We will no
                    665:         * longer need them.  Also, extra privileges could make it very hard
                    666:         * to read identity files and other non-world-readable files from the
                    667:         * user's home directory if it happens to be on a NFS volume where
                    668:         * root is mapped to nobody.
                    669:         */
1.225     dtucker   670:        if (original_effective_uid == 0) {
                    671:                PRIV_START;
                    672:                permanently_set_uid(pw);
                    673:        }
1.31      markus    674:
1.33      markus    675:        /*
                    676:         * Now that we are back to our own permissions, create ~/.ssh
                    677:         * directory if it doesn\'t already exist.
                    678:         */
1.138     jakob     679:        snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1.31      markus    680:        if (stat(buf, &st) < 0)
1.57      djm       681:                if (mkdir(buf, 0700) < 0)
1.31      markus    682:                        error("Could not create directory '%.200s'.", buf);
                    683:
1.104     markus    684:        /* load options.identity_files */
                    685:        load_public_identity_files();
                    686:
                    687:        /* Expand ~ in known host file names. */
                    688:        /* XXX mem-leaks: */
1.72      markus    689:        options.system_hostfile =
                    690:            tilde_expand_filename(options.system_hostfile, original_real_uid);
                    691:        options.user_hostfile =
                    692:            tilde_expand_filename(options.user_hostfile, original_real_uid);
                    693:        options.system_hostfile2 =
                    694:            tilde_expand_filename(options.system_hostfile2, original_real_uid);
                    695:        options.user_hostfile2 =
                    696:            tilde_expand_filename(options.user_hostfile2, original_real_uid);
1.149     markus    697:
                    698:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.31      markus    699:
                    700:        /* Log into the remote system.  This never returns if the login fails. */
1.173     markus    701:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
1.31      markus    702:
1.112     markus    703:        /* We no longer need the private host keys.  Clear them now. */
                    704:        if (sensitive_data.nkeys != 0) {
                    705:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    706:                        if (sensitive_data.keys[i] != NULL) {
                    707:                                /* Destroys contents safely */
                    708:                                debug3("clear hostkey %d", i);
                    709:                                key_free(sensitive_data.keys[i]);
                    710:                                sensitive_data.keys[i] = NULL;
                    711:                        }
                    712:                }
                    713:                xfree(sensitive_data.keys);
1.134     markus    714:        }
                    715:        for (i = 0; i < options.num_identity_files; i++) {
                    716:                if (options.identity_files[i]) {
                    717:                        xfree(options.identity_files[i]);
                    718:                        options.identity_files[i] = NULL;
                    719:                }
                    720:                if (options.identity_keys[i]) {
                    721:                        key_free(options.identity_keys[i]);
                    722:                        options.identity_keys[i] = NULL;
                    723:                }
1.112     markus    724:        }
1.31      markus    725:
1.45      markus    726:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    727:        packet_close();
1.186     djm       728:
1.214     djm       729:        if (options.control_path != NULL && control_fd != -1)
                    730:                unlink(options.control_path);
                    731:
1.186     djm       732:        /*
1.203     djm       733:         * Send SIGHUP to proxy command if used. We don't wait() in
1.186     djm       734:         * case it hangs and instead rely on init to reap the child
                    735:         */
                    736:        if (proxy_command_pid > 1)
                    737:                kill(proxy_command_pid, SIGHUP);
                    738:
1.45      markus    739:        return exit_status;
                    740: }
                    741:
1.202     markus    742: #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
                    743:
1.126     itojun    744: static void
1.150     stevesk   745: x11_get_proto(char **_proto, char **_data)
1.50      markus    746: {
1.202     markus    747:        char cmd[1024];
1.50      markus    748:        char line[512];
1.202     markus    749:        char xdisplay[512];
1.150     stevesk   750:        static char proto[512], data[512];
1.50      markus    751:        FILE *f;
1.202     markus    752:        int got_data = 0, generated = 0, do_unlink = 0, i;
                    753:        char *display, *xauthdir, *xauthfile;
1.182     stevesk   754:        struct stat st;
1.50      markus    755:
1.202     markus    756:        xauthdir = xauthfile = NULL;
1.150     stevesk   757:        *_proto = proto;
                    758:        *_data = data;
                    759:        proto[0] = data[0] = '\0';
1.202     markus    760:
1.182     stevesk   761:        if (!options.xauth_location ||
                    762:            (stat(options.xauth_location, &st) == -1)) {
                    763:                debug("No xauth program.");
                    764:        } else {
                    765:                if ((display = getenv("DISPLAY")) == NULL) {
                    766:                        debug("x11_get_proto: DISPLAY not set");
                    767:                        return;
                    768:                }
1.202     markus    769:                /*
                    770:                 * Handle FamilyLocal case where $DISPLAY does
                    771:                 * not match an authorization entry.  For this we
                    772:                 * just try "xauth list unix:displaynum.screennum".
                    773:                 * XXX: "localhost" match to determine FamilyLocal
                    774:                 *      is not perfect.
                    775:                 */
                    776:                if (strncmp(display, "localhost:", 10) == 0) {
                    777:                        snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    778:                            display + 10);
                    779:                        display = xdisplay;
                    780:                }
                    781:                if (options.forward_x11_trusted == 0) {
                    782:                        xauthdir = xmalloc(MAXPATHLEN);
                    783:                        xauthfile = xmalloc(MAXPATHLEN);
                    784:                        strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
                    785:                        if (mkdtemp(xauthdir) != NULL) {
                    786:                                do_unlink = 1;
                    787:                                snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
                    788:                                    xauthdir);
                    789:                                snprintf(cmd, sizeof(cmd),
                    790:                                    "%s -f %s generate %s " SSH_X11_PROTO
1.207     markus    791:                                    " untrusted timeout 1200 2>" _PATH_DEVNULL,
1.202     markus    792:                                    options.xauth_location, xauthfile, display);
                    793:                                debug2("x11_get_proto: %s", cmd);
                    794:                                if (system(cmd) == 0)
                    795:                                        generated = 1;
                    796:                        }
                    797:                }
                    798:                snprintf(cmd, sizeof(cmd),
                    799:                    "%s %s%s list %s . 2>" _PATH_DEVNULL,
                    800:                    options.xauth_location,
                    801:                    generated ? "-f " : "" ,
                    802:                    generated ? xauthfile : "",
                    803:                    display);
                    804:                debug2("x11_get_proto: %s", cmd);
                    805:                f = popen(cmd, "r");
1.55      markus    806:                if (f && fgets(line, sizeof(line), f) &&
1.150     stevesk   807:                    sscanf(line, "%*s %511s %511s", proto, data) == 2)
1.55      markus    808:                        got_data = 1;
                    809:                if (f)
                    810:                        pclose(f);
                    811:        }
1.202     markus    812:
                    813:        if (do_unlink) {
                    814:                unlink(xauthfile);
                    815:                rmdir(xauthdir);
                    816:        }
                    817:        if (xauthdir)
                    818:                xfree(xauthdir);
                    819:        if (xauthfile)
                    820:                xfree(xauthfile);
                    821:
1.50      markus    822:        /*
                    823:         * If we didn't get authentication data, just make up some
                    824:         * data.  The forwarding code will check the validity of the
                    825:         * response anyway, and substitute this data.  The X11
                    826:         * server, however, will ignore this fake data and use
                    827:         * whatever authentication mechanisms it was using otherwise
                    828:         * for the local connection.
                    829:         */
                    830:        if (!got_data) {
1.221     avsm      831:                u_int32_t rnd = 0;
1.50      markus    832:
1.202     markus    833:                logit("Warning: No xauth data; "
                    834:                    "using fake authentication data for X11 forwarding.");
                    835:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
1.50      markus    836:                for (i = 0; i < 16; i++) {
                    837:                        if (i % 4 == 0)
1.221     avsm      838:                                rnd = arc4random();
1.202     markus    839:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
1.221     avsm      840:                            rnd & 0xff);
                    841:                        rnd >>= 8;
1.50      markus    842:                }
                    843:        }
                    844: }
                    845:
1.126     itojun    846: static void
1.70      markus    847: ssh_init_forwarding(void)
                    848: {
1.86      markus    849:        int success = 0;
1.70      markus    850:        int i;
1.86      markus    851:
1.70      markus    852:        /* Initiate local TCP/IP port forwardings. */
                    853:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm       854:                debug("Local connections to %.200s:%d forwarded to remote "
                    855:                    "address %.200s:%d",
1.234     deraadt   856:                    (options.local_forwards[i].listen_host == NULL) ?
                    857:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       858:                    options.local_forwards[i].listen_host,
                    859:                    options.local_forwards[i].listen_port,
                    860:                    options.local_forwards[i].connect_host,
                    861:                    options.local_forwards[i].connect_port);
1.158     markus    862:                success += channel_setup_local_fwd_listener(
1.232     djm       863:                    options.local_forwards[i].listen_host,
                    864:                    options.local_forwards[i].listen_port,
                    865:                    options.local_forwards[i].connect_host,
                    866:                    options.local_forwards[i].connect_port,
1.70      markus    867:                    options.gateway_ports);
                    868:        }
1.86      markus    869:        if (i > 0 && success == 0)
                    870:                error("Could not request local forwarding.");
1.70      markus    871:
                    872:        /* Initiate remote TCP/IP port forwardings. */
                    873:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm       874:                debug("Remote connections from %.200s:%d forwarded to "
                    875:                    "local address %.200s:%d",
1.235     dtucker   876:                    (options.remote_forwards[i].listen_host == NULL) ?
                    877:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       878:                    options.remote_forwards[i].listen_host,
                    879:                    options.remote_forwards[i].listen_port,
                    880:                    options.remote_forwards[i].connect_host,
                    881:                    options.remote_forwards[i].connect_port);
1.70      markus    882:                channel_request_remote_forwarding(
1.232     djm       883:                    options.remote_forwards[i].listen_host,
                    884:                    options.remote_forwards[i].listen_port,
                    885:                    options.remote_forwards[i].connect_host,
                    886:                    options.remote_forwards[i].connect_port);
1.70      markus    887:        }
                    888: }
                    889:
1.126     itojun    890: static void
1.70      markus    891: check_agent_present(void)
                    892: {
                    893:        if (options.forward_agent) {
                    894:                /* Clear agent forwarding if we don\'t have an agent. */
1.185     stevesk   895:                if (!ssh_agent_present())
1.70      markus    896:                        options.forward_agent = 0;
                    897:        }
                    898: }
                    899:
1.126     itojun    900: static int
1.45      markus    901: ssh_session(void)
                    902: {
                    903:        int type;
                    904:        int interactive = 0;
                    905:        int have_tty = 0;
                    906:        struct winsize ws;
                    907:        char *cp;
                    908:
1.31      markus    909:        /* Enable compression if requested. */
                    910:        if (options.compression) {
                    911:                debug("Requesting compression at level %d.", options.compression_level);
                    912:
                    913:                if (options.compression_level < 1 || options.compression_level > 9)
                    914:                        fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
                    915:
                    916:                /* Send the request. */
                    917:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                    918:                packet_put_int(options.compression_level);
                    919:                packet_send();
                    920:                packet_write_wait();
1.156     markus    921:                type = packet_read();
1.31      markus    922:                if (type == SSH_SMSG_SUCCESS)
                    923:                        packet_start_compression(options.compression_level);
                    924:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun    925:                        logit("Warning: Remote host refused compression.");
1.31      markus    926:                else
                    927:                        packet_disconnect("Protocol error waiting for compression response.");
                    928:        }
                    929:        /* Allocate a pseudo tty if appropriate. */
                    930:        if (tty_flag) {
                    931:                debug("Requesting pty.");
                    932:
                    933:                /* Start the packet. */
                    934:                packet_start(SSH_CMSG_REQUEST_PTY);
                    935:
                    936:                /* Store TERM in the packet.  There is no limit on the
                    937:                   length of the string. */
                    938:                cp = getenv("TERM");
                    939:                if (!cp)
                    940:                        cp = "";
1.124     markus    941:                packet_put_cstring(cp);
1.31      markus    942:
                    943:                /* Store window size in the packet. */
                    944:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    945:                        memset(&ws, 0, sizeof(ws));
                    946:                packet_put_int(ws.ws_row);
                    947:                packet_put_int(ws.ws_col);
                    948:                packet_put_int(ws.ws_xpixel);
                    949:                packet_put_int(ws.ws_ypixel);
                    950:
                    951:                /* Store tty modes in the packet. */
1.115     stevesk   952:                tty_make_modes(fileno(stdin), NULL);
1.31      markus    953:
                    954:                /* Send the packet, and wait for it to leave. */
                    955:                packet_send();
                    956:                packet_write_wait();
                    957:
                    958:                /* Read response from the server. */
1.156     markus    959:                type = packet_read();
1.43      markus    960:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus    961:                        interactive = 1;
1.45      markus    962:                        have_tty = 1;
1.43      markus    963:                } else if (type == SSH_SMSG_FAILURE)
1.191     itojun    964:                        logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
1.31      markus    965:                else
                    966:                        packet_disconnect("Protocol error waiting for pty request response.");
                    967:        }
                    968:        /* Request X11 forwarding if enabled and DISPLAY is set. */
                    969:        if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1.150     stevesk   970:                char *proto, *data;
1.50      markus    971:                /* Get reasonable local authentication information. */
1.150     stevesk   972:                x11_get_proto(&proto, &data);
1.50      markus    973:                /* Request forwarding with authentication spoofing. */
1.31      markus    974:                debug("Requesting X11 forwarding with authentication spoofing.");
1.50      markus    975:                x11_request_forwarding_with_spoofing(0, proto, data);
1.31      markus    976:
                    977:                /* Read response from the server. */
1.156     markus    978:                type = packet_read();
1.31      markus    979:                if (type == SSH_SMSG_SUCCESS) {
                    980:                        interactive = 1;
1.50      markus    981:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun    982:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus    983:                } else {
1.31      markus    984:                        packet_disconnect("Protocol error waiting for X11 forwarding");
1.50      markus    985:                }
1.31      markus    986:        }
                    987:        /* Tell the packet module whether this is an interactive session. */
1.80      markus    988:        packet_set_interactive(interactive);
1.31      markus    989:
                    990:        /* Request authentication agent forwarding if appropriate. */
1.70      markus    991:        check_agent_present();
                    992:
1.31      markus    993:        if (options.forward_agent) {
                    994:                debug("Requesting authentication agent forwarding.");
                    995:                auth_request_forwarding();
                    996:
                    997:                /* Read response from the server. */
1.156     markus    998:                type = packet_read();
1.155     markus    999:                packet_check_eom();
1.31      markus   1000:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun   1001:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus   1002:        }
                   1003:
1.70      markus   1004:        /* Initiate port forwardings. */
                   1005:        ssh_init_forwarding();
1.34      markus   1006:
                   1007:        /* If requested, let ssh continue in the background. */
1.48      markus   1008:        if (fork_after_authentication_flag)
1.34      markus   1009:                if (daemon(1, 1) < 0)
                   1010:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus   1011:
1.33      markus   1012:        /*
                   1013:         * If a command was specified on the command line, execute the
                   1014:         * command now. Otherwise request the server to start a shell.
                   1015:         */
1.31      markus   1016:        if (buffer_len(&command) > 0) {
                   1017:                int len = buffer_len(&command);
                   1018:                if (len > 900)
                   1019:                        len = 900;
1.152     stevesk  1020:                debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1.31      markus   1021:                packet_start(SSH_CMSG_EXEC_CMD);
                   1022:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1023:                packet_send();
                   1024:                packet_write_wait();
                   1025:        } else {
                   1026:                debug("Requesting shell.");
                   1027:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1028:                packet_send();
                   1029:                packet_write_wait();
                   1030:        }
                   1031:
                   1032:        /* Enter the interactive session. */
1.119     stevesk  1033:        return client_loop(have_tty, tty_flag ?
                   1034:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.45      markus   1035: }
                   1036:
1.126     itojun   1037: static void
1.214     djm      1038: ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1.89      markus   1039: {
                   1040:        int id, len;
                   1041:
                   1042:        id = packet_get_int();
                   1043:        len = buffer_len(&command);
1.100     markus   1044:        if (len > 900)
                   1045:                len = 900;
1.155     markus   1046:        packet_check_eom();
1.89      markus   1047:        if (type == SSH2_MSG_CHANNEL_FAILURE)
                   1048:                fatal("Request for subsystem '%.*s' failed on channel %d",
1.152     stevesk  1049:                    len, (u_char *)buffer_ptr(&command), id);
1.170     markus   1050: }
                   1051:
                   1052: void
1.206     markus   1053: client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1.170     markus   1054: {
                   1055:        int i;
                   1056:
                   1057:        i = client_global_request_id++;
1.206     markus   1058:        if (i >= options.num_remote_forwards)
1.170     markus   1059:                return;
                   1060:        debug("remote forward %s for: listen %d, connect %s:%d",
                   1061:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1.232     djm      1062:            options.remote_forwards[i].listen_port,
                   1063:            options.remote_forwards[i].connect_host,
                   1064:            options.remote_forwards[i].connect_port);
1.170     markus   1065:        if (type == SSH2_MSG_REQUEST_FAILURE)
1.232     djm      1066:                logit("Warning: remote port forwarding failed for listen "
                   1067:                    "port %d", options.remote_forwards[i].listen_port);
1.89      markus   1068: }
                   1069:
1.126     itojun   1070: static void
1.214     djm      1071: ssh_control_listener(void)
1.45      markus   1072: {
1.214     djm      1073:        struct sockaddr_un addr;
                   1074:        mode_t old_umask;
1.223     deraadt  1075:
1.242   ! djm      1076:        if (options.control_path == NULL ||
        !          1077:            options.control_master == SSHCTL_MASTER_NO)
1.214     djm      1078:                return;
                   1079:
1.242   ! djm      1080:        debug("setting up multiplex master socket");
        !          1081:
1.214     djm      1082:        memset(&addr, '\0', sizeof(addr));
                   1083:        addr.sun_family = AF_UNIX;
                   1084:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1085:            strlen(options.control_path) + 1;
                   1086:
                   1087:        if (strlcpy(addr.sun_path, options.control_path,
                   1088:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1089:                fatal("ControlPath too long");
                   1090:
                   1091:        if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1092:                fatal("%s socket(): %s\n", __func__, strerror(errno));
                   1093:
                   1094:        old_umask = umask(0177);
                   1095:        if (bind(control_fd, (struct sockaddr*)&addr, addr.sun_len) == -1) {
                   1096:                control_fd = -1;
1.238     djm      1097:                if (errno == EINVAL || errno == EADDRINUSE)
1.214     djm      1098:                        fatal("ControlSocket %s already exists",
                   1099:                            options.control_path);
                   1100:                else
                   1101:                        fatal("%s bind(): %s\n", __func__, strerror(errno));
                   1102:        }
                   1103:        umask(old_umask);
1.80      markus   1104:
1.214     djm      1105:        if (listen(control_fd, 64) == -1)
                   1106:                fatal("%s listen(): %s\n", __func__, strerror(errno));
1.31      markus   1107:
1.214     djm      1108:        set_nonblock(control_fd);
                   1109: }
1.45      markus   1110:
1.214     djm      1111: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1112: static void
                   1113: ssh_session2_setup(int id, void *arg)
                   1114: {
1.215     djm      1115:        extern char **environ;
                   1116:
1.214     djm      1117:        int interactive = tty_flag;
                   1118:        if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1.150     stevesk  1119:                char *proto, *data;
1.50      markus   1120:                /* Get reasonable local authentication information. */
1.150     stevesk  1121:                x11_get_proto(&proto, &data);
1.50      markus   1122:                /* Request forwarding with authentication spoofing. */
                   1123:                debug("Requesting X11 forwarding with authentication spoofing.");
                   1124:                x11_request_forwarding_with_spoofing(id, proto, data);
1.80      markus   1125:                interactive = 1;
1.50      markus   1126:                /* XXX wait for reply */
                   1127:        }
                   1128:
1.70      markus   1129:        check_agent_present();
                   1130:        if (options.forward_agent) {
                   1131:                debug("Requesting authentication agent forwarding.");
                   1132:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1133:                packet_send();
1.212     djm      1134:        }
                   1135:
1.214     djm      1136:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.215     djm      1137:            NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1.90      markus   1138:
1.80      markus   1139:        packet_set_interactive(interactive);
1.45      markus   1140: }
                   1141:
1.143     markus   1142: /* open new channel for a session */
1.126     itojun   1143: static int
1.143     markus   1144: ssh_session2_open(void)
1.45      markus   1145: {
1.118     markus   1146:        Channel *c;
                   1147:        int window, packetmax, in, out, err;
1.60      markus   1148:
1.62      markus   1149:        if (stdin_null_flag) {
1.93      itojun   1150:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1151:        } else {
                   1152:                in = dup(STDIN_FILENO);
                   1153:        }
1.60      markus   1154:        out = dup(STDOUT_FILENO);
                   1155:        err = dup(STDERR_FILENO);
1.45      markus   1156:
                   1157:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1158:                fatal("dup() in/out/err failed");
1.45      markus   1159:
1.69      markus   1160:        /* enable nonblocking unless tty */
                   1161:        if (!isatty(in))
                   1162:                set_nonblock(in);
                   1163:        if (!isatty(out))
                   1164:                set_nonblock(out);
                   1165:        if (!isatty(err))
                   1166:                set_nonblock(err);
                   1167:
1.65      markus   1168:        window = CHAN_SES_WINDOW_DEFAULT;
                   1169:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1170:        if (tty_flag) {
                   1171:                window >>= 1;
                   1172:                packetmax >>= 1;
1.45      markus   1173:        }
1.118     markus   1174:        c = channel_new(
1.45      markus   1175:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1176:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1177:            "client-session", /*nonblock*/0);
1.45      markus   1178:
1.143     markus   1179:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1180:
1.122     markus   1181:        channel_send_open(c->self);
1.143     markus   1182:        if (!no_shell_flag)
1.214     djm      1183:                channel_register_confirm(c->self, ssh_session2_setup, NULL);
1.106     markus   1184:
1.118     markus   1185:        return c->self;
1.106     markus   1186: }
                   1187:
1.126     itojun   1188: static int
1.106     markus   1189: ssh_session2(void)
                   1190: {
1.143     markus   1191:        int id = -1;
1.106     markus   1192:
                   1193:        /* XXX should be pre-session */
                   1194:        ssh_init_forwarding();
1.214     djm      1195:        ssh_control_listener();
1.106     markus   1196:
1.143     markus   1197:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1198:                id = ssh_session2_open();
1.106     markus   1199:
                   1200:        /* If requested, let ssh continue in the background. */
                   1201:        if (fork_after_authentication_flag)
                   1202:                if (daemon(1, 1) < 0)
                   1203:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus   1204:
1.119     stevesk  1205:        return client_loop(tty_flag, tty_flag ?
                   1206:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1207: }
                   1208:
1.126     itojun   1209: static void
1.104     markus   1210: load_public_identity_files(void)
                   1211: {
                   1212:        char *filename;
1.167     markus   1213:        int i = 0;
1.104     markus   1214:        Key *public;
1.167     markus   1215: #ifdef SMARTCARD
                   1216:        Key **keys;
1.104     markus   1217:
1.133     markus   1218:        if (options.smartcard_device != NULL &&
1.167     markus   1219:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
                   1220:            (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
                   1221:                int count = 0;
                   1222:                for (i = 0; keys[i] != NULL; i++) {
                   1223:                        count++;
                   1224:                        memmove(&options.identity_files[1], &options.identity_files[0],
                   1225:                            sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
                   1226:                        memmove(&options.identity_keys[1], &options.identity_keys[0],
                   1227:                            sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
                   1228:                        options.num_identity_files++;
                   1229:                        options.identity_keys[0] = keys[i];
1.194     markus   1230:                        options.identity_files[0] = sc_get_key_label(keys[i]);
1.167     markus   1231:                }
1.168     markus   1232:                if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
                   1233:                        options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1.167     markus   1234:                i = count;
                   1235:                xfree(keys);
1.127     markus   1236:        }
1.136     jakob    1237: #endif /* SMARTCARD */
1.131     millert  1238:        for (; i < options.num_identity_files; i++) {
                   1239:                filename = tilde_expand_filename(options.identity_files[i],
                   1240:                    original_real_uid);
                   1241:                public = key_load_public(filename, NULL);
                   1242:                debug("identity file %s type %d", filename,
                   1243:                    public ? public->type : -1);
                   1244:                xfree(options.identity_files[i]);
                   1245:                options.identity_files[i] = filename;
                   1246:                options.identity_keys[i] = public;
                   1247:        }
1.214     djm      1248: }
                   1249:
                   1250: static void
                   1251: control_client_sighandler(int signo)
                   1252: {
                   1253:        control_client_terminate = signo;
                   1254: }
                   1255:
                   1256: static void
                   1257: control_client_sigrelay(int signo)
                   1258: {
                   1259:        if (control_server_pid > 1)
                   1260:                kill(control_server_pid, signo);
                   1261: }
                   1262:
1.220     djm      1263: static int
                   1264: env_permitted(char *env)
                   1265: {
                   1266:        int i;
                   1267:        char name[1024], *cp;
                   1268:
                   1269:        strlcpy(name, env, sizeof(name));
                   1270:        if ((cp = strchr(name, '=')) == NULL)
                   1271:                return (0);
                   1272:
                   1273:        *cp = '\0';
                   1274:
                   1275:        for (i = 0; i < options.num_send_env; i++)
                   1276:                if (match_pattern(name, options.send_env[i]))
                   1277:                        return (1);
                   1278:
                   1279:        return (0);
                   1280: }
                   1281:
1.214     djm      1282: static void
                   1283: control_client(const char *path)
                   1284: {
                   1285:        struct sockaddr_un addr;
1.228     djm      1286:        int i, r, fd, sock, exitval, num_env;
1.214     djm      1287:        Buffer m;
1.229     djm      1288:        char *term;
1.215     djm      1289:        extern char **environ;
1.229     djm      1290:        u_int  flags;
1.242   ! djm      1291:
        !          1292:        if (mux_command == 0)
        !          1293:                mux_command = SSHMUX_COMMAND_OPEN;
        !          1294:
        !          1295:        switch (options.control_master) {
        !          1296:        case SSHCTL_MASTER_AUTO:
        !          1297:        case SSHCTL_MASTER_AUTO_ASK:
        !          1298:                debug("auto-mux: Trying existing master");
        !          1299:                /* FALLTHROUGH */
        !          1300:        case SSHCTL_MASTER_NO:
        !          1301:                break;
        !          1302:        default:
        !          1303:                return;
        !          1304:        }
1.228     djm      1305:
1.214     djm      1306:        memset(&addr, '\0', sizeof(addr));
                   1307:        addr.sun_family = AF_UNIX;
                   1308:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1309:            strlen(path) + 1;
                   1310:
                   1311:        if (strlcpy(addr.sun_path, path,
                   1312:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1313:                fatal("ControlPath too long");
                   1314:
                   1315:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1316:                fatal("%s socket(): %s", __func__, strerror(errno));
                   1317:
1.237     jakob    1318:        if (connect(sock, (struct sockaddr*)&addr, addr.sun_len) == -1) {
1.240     djm      1319:                if (mux_command != SSHMUX_COMMAND_OPEN) {
                   1320:                        fatal("Control socket connect(%.100s): %s", path,
                   1321:                            strerror(errno));
                   1322:                }
1.239     djm      1323:                if (errno == ENOENT)
                   1324:                        debug("Control socket \"%.100s\" does not exist", path);
                   1325:                else {
                   1326:                        error("Control socket connect(%.100s): %s", path,
                   1327:                            strerror(errno));
                   1328:                }
1.237     jakob    1329:                close(sock);
                   1330:                return;
                   1331:        }
                   1332:
                   1333:        if (stdin_null_flag) {
                   1334:                if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1335:                        fatal("open(/dev/null): %s", strerror(errno));
                   1336:                if (dup2(fd, STDIN_FILENO) == -1)
                   1337:                        fatal("dup2: %s", strerror(errno));
                   1338:                if (fd > STDERR_FILENO)
                   1339:                        close(fd);
                   1340:        }
                   1341:
1.229     djm      1342:        if ((term = getenv("TERM")) == NULL)
                   1343:                term = "";
                   1344:
                   1345:        flags = 0;
                   1346:        if (tty_flag)
                   1347:                flags |= SSHMUX_FLAG_TTY;
                   1348:        if (subsystem_flag)
                   1349:                flags |= SSHMUX_FLAG_SUBSYS;
1.214     djm      1350:
                   1351:        buffer_init(&m);
                   1352:
1.229     djm      1353:        /* Send our command to server */
                   1354:        buffer_put_int(&m, mux_command);
                   1355:        buffer_put_int(&m, flags);
                   1356:        if (ssh_msg_send(sock, /* version */1, &m) == -1)
                   1357:                fatal("%s: msg_send", __func__);
                   1358:        buffer_clear(&m);
                   1359:
                   1360:        /* Get authorisation status and PID of controlee */
1.214     djm      1361:        if (ssh_msg_recv(sock, &m) == -1)
                   1362:                fatal("%s: msg_recv", __func__);
1.229     djm      1363:        if (buffer_get_char(&m) != 1)
1.214     djm      1364:                fatal("%s: wrong version", __func__);
1.216     djm      1365:        if (buffer_get_int(&m) != 1)
                   1366:                fatal("Connection to master denied");
1.214     djm      1367:        control_server_pid = buffer_get_int(&m);
                   1368:
                   1369:        buffer_clear(&m);
                   1370:
1.229     djm      1371:        switch (mux_command) {
                   1372:        case SSHMUX_COMMAND_ALIVE_CHECK:
1.234     deraadt  1373:                fprintf(stderr, "Master running (pid=%d)\r\n",
1.229     djm      1374:                    control_server_pid);
                   1375:                exit(0);
                   1376:        case SSHMUX_COMMAND_TERMINATE:
                   1377:                fprintf(stderr, "Exit request sent.\r\n");
                   1378:                exit(0);
                   1379:        case SSHMUX_COMMAND_OPEN:
                   1380:                /* continue below */
                   1381:                break;
                   1382:        default:
                   1383:                fatal("silly mux_command %d", mux_command);
                   1384:        }
                   1385:
                   1386:        /* SSHMUX_COMMAND_OPEN */
                   1387:        buffer_put_cstring(&m, term);
1.214     djm      1388:        buffer_append(&command, "\0", 1);
                   1389:        buffer_put_cstring(&m, buffer_ptr(&command));
1.215     djm      1390:
1.220     djm      1391:        if (options.num_send_env == 0 || environ == NULL) {
                   1392:                buffer_put_int(&m, 0);
1.223     deraadt  1393:        } else {
1.220     djm      1394:                /* Pass environment */
                   1395:                num_env = 0;
                   1396:                for (i = 0; environ[i] != NULL; i++)
                   1397:                        if (env_permitted(environ[i]))
                   1398:                                num_env++; /* Count */
1.223     deraadt  1399:
1.220     djm      1400:                buffer_put_int(&m, num_env);
                   1401:
1.222     dtucker  1402:                for (i = 0; environ[i] != NULL && num_env >= 0; i++)
                   1403:                        if (env_permitted(environ[i])) {
                   1404:                                num_env--;
1.220     djm      1405:                                buffer_put_cstring(&m, environ[i]);
1.222     dtucker  1406:                        }
1.220     djm      1407:        }
1.214     djm      1408:
1.229     djm      1409:        if (ssh_msg_send(sock, /* version */1, &m) == -1)
1.214     djm      1410:                fatal("%s: msg_send", __func__);
                   1411:
                   1412:        mm_send_fd(sock, STDIN_FILENO);
                   1413:        mm_send_fd(sock, STDOUT_FILENO);
                   1414:        mm_send_fd(sock, STDERR_FILENO);
                   1415:
                   1416:        /* Wait for reply, so master has a chance to gather ttymodes */
                   1417:        buffer_clear(&m);
                   1418:        if (ssh_msg_recv(sock, &m) == -1)
                   1419:                fatal("%s: msg_recv", __func__);
1.229     djm      1420:        if (buffer_get_char(&m) != 1)
                   1421:                fatal("%s: wrong version", __func__);
1.214     djm      1422:        buffer_free(&m);
1.218     djm      1423:
1.226     djm      1424:        signal(SIGHUP, control_client_sighandler);
1.218     djm      1425:        signal(SIGINT, control_client_sighandler);
                   1426:        signal(SIGTERM, control_client_sighandler);
                   1427:        signal(SIGWINCH, control_client_sigrelay);
1.214     djm      1428:
                   1429:        if (tty_flag)
                   1430:                enter_raw_mode();
                   1431:
                   1432:        /* Stick around until the controlee closes the client_fd */
                   1433:        exitval = 0;
                   1434:        for (;!control_client_terminate;) {
                   1435:                r = read(sock, &exitval, sizeof(exitval));
                   1436:                if (r == 0) {
                   1437:                        debug2("Received EOF from master");
                   1438:                        break;
                   1439:                }
                   1440:                if (r > 0)
                   1441:                        debug2("Received exit status from master %d", exitval);
                   1442:                if (r == -1 && errno != EINTR)
                   1443:                        fatal("%s: read %s", __func__, strerror(errno));
                   1444:        }
                   1445:
                   1446:        if (control_client_terminate)
                   1447:                debug2("Exiting on signal %d", control_client_terminate);
                   1448:
                   1449:        close(sock);
                   1450:
                   1451:        leave_raw_mode();
                   1452:
                   1453:        if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
                   1454:                fprintf(stderr, "Connection to master closed.\r\n");
                   1455:
                   1456:        exit(exitval);
1.1       deraadt  1457: }