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

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