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

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