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

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