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

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