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

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