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

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