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

1.304   ! dtucker     1: /* $OpenBSD: ssh.c,v 1.303 2007/09/04 11:15:55 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.303     djm       205:        int dummy, timeout_ms;
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 &&
1.304   ! dtucker   646:            strcmp(options.proxy_command, "none") == 0) {
        !           647:                xfree(options.proxy_command);
1.190     markus    648:                options.proxy_command = NULL;
1.304   ! dtucker   649:        }
1.245     djm       650:        if (options.control_path != NULL &&
1.304   ! dtucker   651:            strcmp(options.control_path, "none") == 0) {
        !           652:                xfree(options.control_path);
1.245     djm       653:                options.control_path = NULL;
1.304   ! dtucker   654:        }
1.31      markus    655:
1.214     djm       656:        if (options.control_path != NULL) {
1.275     djm       657:                char thishost[NI_MAXHOST];
1.261     djm       658:
1.275     djm       659:                if (gethostname(thishost, sizeof(thishost)) == -1)
1.261     djm       660:                        fatal("gethostname: %s", strerror(errno));
1.241     djm       661:                snprintf(buf, sizeof(buf), "%d", options.port);
                    662:                cp = tilde_expand_filename(options.control_path,
                    663:                    original_real_uid);
1.304   ! dtucker   664:                xfree(options.control_path);
1.241     djm       665:                options.control_path = percent_expand(cp, "p", buf, "h", host,
1.275     djm       666:                    "r", options.user, "l", thishost, (char *)NULL);
1.241     djm       667:                xfree(cp);
1.214     djm       668:        }
1.240     djm       669:        if (mux_command != 0 && options.control_path == NULL)
                    670:                fatal("No ControlPath specified for \"-O\" command");
1.242     djm       671:        if (options.control_path != NULL)
1.237     jakob     672:                control_client(options.control_path);
1.214     djm       673:
1.303     djm       674:        timeout_ms = options.connection_timeout * 1000;
                    675:
1.77      markus    676:        /* Open a connection to the remote host. */
1.203     djm       677:        if (ssh_connect(host, &hostaddr, options.port,
1.303     djm       678:            options.address_family, options.connection_attempts, &timeout_ms,
                    679:            options.tcp_keep_alive,
1.177     markus    680:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    681:            options.proxy_command) != 0)
1.257     dtucker   682:                exit(255);
1.31      markus    683:
1.303     djm       684:        if (timeout_ms > 0)
                    685:                debug3("timeout: %d ms remain after connect", timeout_ms);
                    686:
1.33      markus    687:        /*
                    688:         * If we successfully made the connection, load the host private key
                    689:         * in case we will need it later for combined rsa-rhosts
                    690:         * authentication. This must be done before releasing extra
                    691:         * privileges, because the file is only readable by root.
1.174     markus    692:         * If we cannot access the private keys, load the public keys
                    693:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    694:         */
1.112     markus    695:        sensitive_data.nkeys = 0;
                    696:        sensitive_data.keys = NULL;
1.173     markus    697:        sensitive_data.external_keysign = 0;
1.178     markus    698:        if (options.rhosts_rsa_authentication ||
                    699:            options.hostbased_authentication) {
1.112     markus    700:                sensitive_data.nkeys = 3;
1.274     deraadt   701:                sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1.180     deraadt   702:                    sizeof(Key));
1.177     markus    703:
                    704:                PRIV_START;
1.112     markus    705:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.276     dtucker   706:                    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1.112     markus    707:                sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
1.276     dtucker   708:                    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1.112     markus    709:                sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
1.276     dtucker   710:                    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1.177     markus    711:                PRIV_END;
1.173     markus    712:
1.181     markus    713:                if (options.hostbased_authentication == 1 &&
                    714:                    sensitive_data.keys[0] == NULL &&
1.173     markus    715:                    sensitive_data.keys[1] == NULL &&
                    716:                    sensitive_data.keys[2] == NULL) {
                    717:                        sensitive_data.keys[1] = key_load_public(
                    718:                            _PATH_HOST_DSA_KEY_FILE, NULL);
                    719:                        sensitive_data.keys[2] = key_load_public(
                    720:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    721:                        sensitive_data.external_keysign = 1;
                    722:                }
1.31      markus    723:        }
1.33      markus    724:        /*
                    725:         * Get rid of any extra privileges that we may have.  We will no
                    726:         * longer need them.  Also, extra privileges could make it very hard
                    727:         * to read identity files and other non-world-readable files from the
                    728:         * user's home directory if it happens to be on a NFS volume where
                    729:         * root is mapped to nobody.
                    730:         */
1.225     dtucker   731:        if (original_effective_uid == 0) {
                    732:                PRIV_START;
                    733:                permanently_set_uid(pw);
                    734:        }
1.31      markus    735:
1.33      markus    736:        /*
                    737:         * Now that we are back to our own permissions, create ~/.ssh
1.254     djm       738:         * directory if it doesn't already exist.
1.33      markus    739:         */
1.138     jakob     740:        snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1.31      markus    741:        if (stat(buf, &st) < 0)
1.57      djm       742:                if (mkdir(buf, 0700) < 0)
1.31      markus    743:                        error("Could not create directory '%.200s'.", buf);
                    744:
1.104     markus    745:        /* load options.identity_files */
                    746:        load_public_identity_files();
                    747:
                    748:        /* Expand ~ in known host file names. */
                    749:        /* XXX mem-leaks: */
1.72      markus    750:        options.system_hostfile =
                    751:            tilde_expand_filename(options.system_hostfile, original_real_uid);
                    752:        options.user_hostfile =
                    753:            tilde_expand_filename(options.user_hostfile, original_real_uid);
                    754:        options.system_hostfile2 =
                    755:            tilde_expand_filename(options.system_hostfile2, original_real_uid);
                    756:        options.user_hostfile2 =
                    757:            tilde_expand_filename(options.user_hostfile2, original_real_uid);
1.149     markus    758:
                    759:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.31      markus    760:
                    761:        /* Log into the remote system.  This never returns if the login fails. */
1.303     djm       762:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
                    763:            pw, timeout_ms);
1.31      markus    764:
1.112     markus    765:        /* We no longer need the private host keys.  Clear them now. */
                    766:        if (sensitive_data.nkeys != 0) {
                    767:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    768:                        if (sensitive_data.keys[i] != NULL) {
                    769:                                /* Destroys contents safely */
                    770:                                debug3("clear hostkey %d", i);
                    771:                                key_free(sensitive_data.keys[i]);
                    772:                                sensitive_data.keys[i] = NULL;
                    773:                        }
                    774:                }
                    775:                xfree(sensitive_data.keys);
1.134     markus    776:        }
                    777:        for (i = 0; i < options.num_identity_files; i++) {
                    778:                if (options.identity_files[i]) {
                    779:                        xfree(options.identity_files[i]);
                    780:                        options.identity_files[i] = NULL;
                    781:                }
                    782:                if (options.identity_keys[i]) {
                    783:                        key_free(options.identity_keys[i]);
                    784:                        options.identity_keys[i] = NULL;
                    785:                }
1.112     markus    786:        }
1.31      markus    787:
1.45      markus    788:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    789:        packet_close();
1.186     djm       790:
1.214     djm       791:        if (options.control_path != NULL && control_fd != -1)
                    792:                unlink(options.control_path);
                    793:
1.186     djm       794:        /*
1.203     djm       795:         * Send SIGHUP to proxy command if used. We don't wait() in
1.186     djm       796:         * case it hangs and instead rely on init to reap the child
                    797:         */
                    798:        if (proxy_command_pid > 1)
                    799:                kill(proxy_command_pid, SIGHUP);
                    800:
1.45      markus    801:        return exit_status;
                    802: }
                    803:
1.126     itojun    804: static void
1.70      markus    805: ssh_init_forwarding(void)
                    806: {
1.86      markus    807:        int success = 0;
1.70      markus    808:        int i;
1.86      markus    809:
1.70      markus    810:        /* Initiate local TCP/IP port forwardings. */
                    811:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm       812:                debug("Local connections to %.200s:%d forwarded to remote "
                    813:                    "address %.200s:%d",
1.234     deraadt   814:                    (options.local_forwards[i].listen_host == NULL) ?
                    815:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       816:                    options.local_forwards[i].listen_host,
                    817:                    options.local_forwards[i].listen_port,
                    818:                    options.local_forwards[i].connect_host,
                    819:                    options.local_forwards[i].connect_port);
1.158     markus    820:                success += channel_setup_local_fwd_listener(
1.232     djm       821:                    options.local_forwards[i].listen_host,
                    822:                    options.local_forwards[i].listen_port,
                    823:                    options.local_forwards[i].connect_host,
                    824:                    options.local_forwards[i].connect_port,
1.70      markus    825:                    options.gateway_ports);
                    826:        }
1.283     markus    827:        if (i > 0 && success != i && options.exit_on_forward_failure)
                    828:                fatal("Could not request local forwarding.");
1.86      markus    829:        if (i > 0 && success == 0)
                    830:                error("Could not request local forwarding.");
1.70      markus    831:
                    832:        /* Initiate remote TCP/IP port forwardings. */
                    833:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm       834:                debug("Remote connections from %.200s:%d forwarded to "
                    835:                    "local address %.200s:%d",
1.248     djm       836:                    (options.remote_forwards[i].listen_host == NULL) ?
1.253     djm       837:                    "LOCALHOST" : options.remote_forwards[i].listen_host,
1.232     djm       838:                    options.remote_forwards[i].listen_port,
                    839:                    options.remote_forwards[i].connect_host,
                    840:                    options.remote_forwards[i].connect_port);
1.283     markus    841:                if (channel_request_remote_forwarding(
1.232     djm       842:                    options.remote_forwards[i].listen_host,
                    843:                    options.remote_forwards[i].listen_port,
                    844:                    options.remote_forwards[i].connect_host,
1.283     markus    845:                    options.remote_forwards[i].connect_port) < 0) {
                    846:                        if (options.exit_on_forward_failure)
                    847:                                fatal("Could not request remote forwarding.");
                    848:                        else
                    849:                                logit("Warning: Could not request remote "
                    850:                                    "forwarding.");
                    851:                }
1.70      markus    852:        }
1.301     djm       853:
                    854:        /* Initiate tunnel forwarding. */
                    855:        if (options.tun_open != SSH_TUNMODE_NO) {
                    856:                if (client_request_tun_fwd(options.tun_open,
                    857:                    options.tun_local, options.tun_remote) == -1) {
                    858:                        if (options.exit_on_forward_failure)
                    859:                                fatal("Could not request tunnel forwarding.");
                    860:                        else
                    861:                                error("Could not request tunnel forwarding.");
                    862:                }
                    863:        }
1.70      markus    864: }
                    865:
1.126     itojun    866: static void
1.70      markus    867: check_agent_present(void)
                    868: {
                    869:        if (options.forward_agent) {
1.254     djm       870:                /* Clear agent forwarding if we don't have an agent. */
1.185     stevesk   871:                if (!ssh_agent_present())
1.70      markus    872:                        options.forward_agent = 0;
                    873:        }
                    874: }
                    875:
1.126     itojun    876: static int
1.45      markus    877: ssh_session(void)
                    878: {
                    879:        int type;
                    880:        int interactive = 0;
                    881:        int have_tty = 0;
                    882:        struct winsize ws;
                    883:        char *cp;
1.243     djm       884:        const char *display;
1.45      markus    885:
1.31      markus    886:        /* Enable compression if requested. */
                    887:        if (options.compression) {
                    888:                debug("Requesting compression at level %d.", options.compression_level);
                    889:
                    890:                if (options.compression_level < 1 || options.compression_level > 9)
                    891:                        fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
                    892:
                    893:                /* Send the request. */
                    894:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                    895:                packet_put_int(options.compression_level);
                    896:                packet_send();
                    897:                packet_write_wait();
1.156     markus    898:                type = packet_read();
1.31      markus    899:                if (type == SSH_SMSG_SUCCESS)
                    900:                        packet_start_compression(options.compression_level);
                    901:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun    902:                        logit("Warning: Remote host refused compression.");
1.31      markus    903:                else
                    904:                        packet_disconnect("Protocol error waiting for compression response.");
                    905:        }
                    906:        /* Allocate a pseudo tty if appropriate. */
                    907:        if (tty_flag) {
                    908:                debug("Requesting pty.");
                    909:
                    910:                /* Start the packet. */
                    911:                packet_start(SSH_CMSG_REQUEST_PTY);
                    912:
                    913:                /* Store TERM in the packet.  There is no limit on the
                    914:                   length of the string. */
                    915:                cp = getenv("TERM");
                    916:                if (!cp)
                    917:                        cp = "";
1.124     markus    918:                packet_put_cstring(cp);
1.31      markus    919:
                    920:                /* Store window size in the packet. */
                    921:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    922:                        memset(&ws, 0, sizeof(ws));
1.269     deraadt   923:                packet_put_int((u_int)ws.ws_row);
                    924:                packet_put_int((u_int)ws.ws_col);
                    925:                packet_put_int((u_int)ws.ws_xpixel);
                    926:                packet_put_int((u_int)ws.ws_ypixel);
1.31      markus    927:
                    928:                /* Store tty modes in the packet. */
1.115     stevesk   929:                tty_make_modes(fileno(stdin), NULL);
1.31      markus    930:
                    931:                /* Send the packet, and wait for it to leave. */
                    932:                packet_send();
                    933:                packet_write_wait();
                    934:
                    935:                /* Read response from the server. */
1.156     markus    936:                type = packet_read();
1.43      markus    937:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus    938:                        interactive = 1;
1.45      markus    939:                        have_tty = 1;
1.43      markus    940:                } else if (type == SSH_SMSG_FAILURE)
1.191     itojun    941:                        logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
1.31      markus    942:                else
                    943:                        packet_disconnect("Protocol error waiting for pty request response.");
                    944:        }
                    945:        /* Request X11 forwarding if enabled and DISPLAY is set. */
1.243     djm       946:        display = getenv("DISPLAY");
                    947:        if (options.forward_x11 && display != NULL) {
1.150     stevesk   948:                char *proto, *data;
1.50      markus    949:                /* Get reasonable local authentication information. */
1.243     djm       950:                client_x11_get_proto(display, options.xauth_location,
                    951:                    options.forward_x11_trusted, &proto, &data);
1.50      markus    952:                /* Request forwarding with authentication spoofing. */
1.31      markus    953:                debug("Requesting X11 forwarding with authentication spoofing.");
1.243     djm       954:                x11_request_forwarding_with_spoofing(0, display, proto, data);
1.31      markus    955:
                    956:                /* Read response from the server. */
1.156     markus    957:                type = packet_read();
1.31      markus    958:                if (type == SSH_SMSG_SUCCESS) {
                    959:                        interactive = 1;
1.50      markus    960:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun    961:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus    962:                } else {
1.31      markus    963:                        packet_disconnect("Protocol error waiting for X11 forwarding");
1.50      markus    964:                }
1.31      markus    965:        }
                    966:        /* Tell the packet module whether this is an interactive session. */
1.80      markus    967:        packet_set_interactive(interactive);
1.31      markus    968:
                    969:        /* Request authentication agent forwarding if appropriate. */
1.70      markus    970:        check_agent_present();
                    971:
1.31      markus    972:        if (options.forward_agent) {
                    973:                debug("Requesting authentication agent forwarding.");
                    974:                auth_request_forwarding();
                    975:
                    976:                /* Read response from the server. */
1.156     markus    977:                type = packet_read();
1.155     markus    978:                packet_check_eom();
1.31      markus    979:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun    980:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus    981:        }
                    982:
1.70      markus    983:        /* Initiate port forwardings. */
                    984:        ssh_init_forwarding();
1.34      markus    985:
                    986:        /* If requested, let ssh continue in the background. */
1.48      markus    987:        if (fork_after_authentication_flag)
1.34      markus    988:                if (daemon(1, 1) < 0)
                    989:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus    990:
1.33      markus    991:        /*
                    992:         * If a command was specified on the command line, execute the
                    993:         * command now. Otherwise request the server to start a shell.
                    994:         */
1.31      markus    995:        if (buffer_len(&command) > 0) {
                    996:                int len = buffer_len(&command);
                    997:                if (len > 900)
                    998:                        len = 900;
1.152     stevesk   999:                debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1.31      markus   1000:                packet_start(SSH_CMSG_EXEC_CMD);
                   1001:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1002:                packet_send();
                   1003:                packet_write_wait();
                   1004:        } else {
                   1005:                debug("Requesting shell.");
                   1006:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1007:                packet_send();
                   1008:                packet_write_wait();
                   1009:        }
                   1010:
                   1011:        /* Enter the interactive session. */
1.119     stevesk  1012:        return client_loop(have_tty, tty_flag ?
                   1013:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.45      markus   1014: }
                   1015:
1.126     itojun   1016: static void
1.214     djm      1017: ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1.89      markus   1018: {
                   1019:        int id, len;
                   1020:
                   1021:        id = packet_get_int();
                   1022:        len = buffer_len(&command);
1.100     markus   1023:        if (len > 900)
                   1024:                len = 900;
1.155     markus   1025:        packet_check_eom();
1.89      markus   1026:        if (type == SSH2_MSG_CHANNEL_FAILURE)
                   1027:                fatal("Request for subsystem '%.*s' failed on channel %d",
1.152     stevesk  1028:                    len, (u_char *)buffer_ptr(&command), id);
1.170     markus   1029: }
                   1030:
                   1031: void
1.206     markus   1032: client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1.170     markus   1033: {
                   1034:        int i;
                   1035:
                   1036:        i = client_global_request_id++;
1.206     markus   1037:        if (i >= options.num_remote_forwards)
1.170     markus   1038:                return;
                   1039:        debug("remote forward %s for: listen %d, connect %s:%d",
                   1040:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1.232     djm      1041:            options.remote_forwards[i].listen_port,
                   1042:            options.remote_forwards[i].connect_host,
                   1043:            options.remote_forwards[i].connect_port);
1.283     markus   1044:        if (type == SSH2_MSG_REQUEST_FAILURE) {
                   1045:                if (options.exit_on_forward_failure)
                   1046:                        fatal("Error: remote port forwarding failed for "
                   1047:                            "listen port %d",
                   1048:                            options.remote_forwards[i].listen_port);
                   1049:                else
                   1050:                        logit("Warning: remote port forwarding failed for "
                   1051:                            "listen port %d",
                   1052:                            options.remote_forwards[i].listen_port);
                   1053:        }
1.89      markus   1054: }
                   1055:
1.126     itojun   1056: static void
1.214     djm      1057: ssh_control_listener(void)
1.45      markus   1058: {
1.214     djm      1059:        struct sockaddr_un addr;
                   1060:        mode_t old_umask;
1.223     deraadt  1061:
1.242     djm      1062:        if (options.control_path == NULL ||
                   1063:            options.control_master == SSHCTL_MASTER_NO)
1.214     djm      1064:                return;
                   1065:
1.242     djm      1066:        debug("setting up multiplex master socket");
                   1067:
1.214     djm      1068:        memset(&addr, '\0', sizeof(addr));
                   1069:        addr.sun_family = AF_UNIX;
                   1070:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1071:            strlen(options.control_path) + 1;
                   1072:
                   1073:        if (strlcpy(addr.sun_path, options.control_path,
                   1074:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1075:                fatal("ControlPath too long");
                   1076:
                   1077:        if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1.252     stevesk  1078:                fatal("%s socket(): %s", __func__, strerror(errno));
1.214     djm      1079:
                   1080:        old_umask = umask(0177);
1.270     deraadt  1081:        if (bind(control_fd, (struct sockaddr *)&addr, addr.sun_len) == -1) {
1.214     djm      1082:                control_fd = -1;
1.238     djm      1083:                if (errno == EINVAL || errno == EADDRINUSE)
1.214     djm      1084:                        fatal("ControlSocket %s already exists",
                   1085:                            options.control_path);
                   1086:                else
1.252     stevesk  1087:                        fatal("%s bind(): %s", __func__, strerror(errno));
1.214     djm      1088:        }
                   1089:        umask(old_umask);
1.80      markus   1090:
1.214     djm      1091:        if (listen(control_fd, 64) == -1)
1.252     stevesk  1092:                fatal("%s listen(): %s", __func__, strerror(errno));
1.31      markus   1093:
1.214     djm      1094:        set_nonblock(control_fd);
                   1095: }
1.45      markus   1096:
1.214     djm      1097: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1098: static void
                   1099: ssh_session2_setup(int id, void *arg)
                   1100: {
1.215     djm      1101:        extern char **environ;
1.243     djm      1102:        const char *display;
                   1103:        int interactive = tty_flag;
1.215     djm      1104:
1.248     djm      1105:        display = getenv("DISPLAY");
1.243     djm      1106:        if (options.forward_x11 && display != NULL) {
1.150     stevesk  1107:                char *proto, *data;
1.50      markus   1108:                /* Get reasonable local authentication information. */
1.243     djm      1109:                client_x11_get_proto(display, options.xauth_location,
                   1110:                    options.forward_x11_trusted, &proto, &data);
1.50      markus   1111:                /* Request forwarding with authentication spoofing. */
                   1112:                debug("Requesting X11 forwarding with authentication spoofing.");
1.243     djm      1113:                x11_request_forwarding_with_spoofing(id, display, proto, data);
1.80      markus   1114:                interactive = 1;
1.50      markus   1115:                /* XXX wait for reply */
                   1116:        }
                   1117:
1.70      markus   1118:        check_agent_present();
                   1119:        if (options.forward_agent) {
                   1120:                debug("Requesting authentication agent forwarding.");
                   1121:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1122:                packet_send();
1.212     djm      1123:        }
                   1124:
1.214     djm      1125:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.215     djm      1126:            NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1.90      markus   1127:
1.80      markus   1128:        packet_set_interactive(interactive);
1.45      markus   1129: }
                   1130:
1.143     markus   1131: /* open new channel for a session */
1.126     itojun   1132: static int
1.143     markus   1133: ssh_session2_open(void)
1.45      markus   1134: {
1.118     markus   1135:        Channel *c;
                   1136:        int window, packetmax, in, out, err;
1.60      markus   1137:
1.62      markus   1138:        if (stdin_null_flag) {
1.93      itojun   1139:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1140:        } else {
                   1141:                in = dup(STDIN_FILENO);
                   1142:        }
1.60      markus   1143:        out = dup(STDOUT_FILENO);
                   1144:        err = dup(STDERR_FILENO);
1.45      markus   1145:
                   1146:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1147:                fatal("dup() in/out/err failed");
1.45      markus   1148:
1.69      markus   1149:        /* enable nonblocking unless tty */
                   1150:        if (!isatty(in))
                   1151:                set_nonblock(in);
                   1152:        if (!isatty(out))
                   1153:                set_nonblock(out);
                   1154:        if (!isatty(err))
                   1155:                set_nonblock(err);
                   1156:
1.65      markus   1157:        window = CHAN_SES_WINDOW_DEFAULT;
                   1158:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1159:        if (tty_flag) {
                   1160:                window >>= 1;
                   1161:                packetmax >>= 1;
1.45      markus   1162:        }
1.118     markus   1163:        c = channel_new(
1.45      markus   1164:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1165:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1166:            "client-session", /*nonblock*/0);
1.45      markus   1167:
1.143     markus   1168:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1169:
1.122     markus   1170:        channel_send_open(c->self);
1.143     markus   1171:        if (!no_shell_flag)
1.214     djm      1172:                channel_register_confirm(c->self, ssh_session2_setup, NULL);
1.106     markus   1173:
1.118     markus   1174:        return c->self;
1.106     markus   1175: }
                   1176:
1.126     itojun   1177: static int
1.106     markus   1178: ssh_session2(void)
                   1179: {
1.143     markus   1180:        int id = -1;
1.106     markus   1181:
                   1182:        /* XXX should be pre-session */
                   1183:        ssh_init_forwarding();
                   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.301     djm      1192:
                   1193:        /* Start listening for multiplex clients */
                   1194:        ssh_control_listener();
1.106     markus   1195:
                   1196:        /* If requested, let ssh continue in the background. */
                   1197:        if (fork_after_authentication_flag)
                   1198:                if (daemon(1, 1) < 0)
                   1199:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus   1200:
1.119     stevesk  1201:        return client_loop(tty_flag, tty_flag ?
                   1202:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1203: }
                   1204:
1.126     itojun   1205: static void
1.104     markus   1206: load_public_identity_files(void)
                   1207: {
1.275     djm      1208:        char *filename, *cp, thishost[NI_MAXHOST];
1.167     markus   1209:        int i = 0;
1.104     markus   1210:        Key *public;
1.275     djm      1211:        struct passwd *pw;
1.167     markus   1212: #ifdef SMARTCARD
                   1213:        Key **keys;
1.104     markus   1214:
1.133     markus   1215:        if (options.smartcard_device != NULL &&
1.167     markus   1216:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1.292     stevesk  1217:            (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1.167     markus   1218:                int count = 0;
                   1219:                for (i = 0; keys[i] != NULL; i++) {
                   1220:                        count++;
                   1221:                        memmove(&options.identity_files[1], &options.identity_files[0],
                   1222:                            sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
                   1223:                        memmove(&options.identity_keys[1], &options.identity_keys[0],
                   1224:                            sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
                   1225:                        options.num_identity_files++;
                   1226:                        options.identity_keys[0] = keys[i];
1.194     markus   1227:                        options.identity_files[0] = sc_get_key_label(keys[i]);
1.167     markus   1228:                }
1.168     markus   1229:                if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
                   1230:                        options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1.167     markus   1231:                i = count;
                   1232:                xfree(keys);
1.127     markus   1233:        }
1.136     jakob    1234: #endif /* SMARTCARD */
1.275     djm      1235:        if ((pw = getpwuid(original_real_uid)) == NULL)
                   1236:                fatal("load_public_identity_files: getpwuid failed");
                   1237:        if (gethostname(thishost, sizeof(thishost)) == -1)
                   1238:                fatal("load_public_identity_files: gethostname: %s",
                   1239:                    strerror(errno));
1.131     millert  1240:        for (; i < options.num_identity_files; i++) {
1.275     djm      1241:                cp = tilde_expand_filename(options.identity_files[i],
1.131     millert  1242:                    original_real_uid);
1.275     djm      1243:                filename = percent_expand(cp, "d", pw->pw_dir,
1.293     deraadt  1244:                    "u", pw->pw_name, "l", thishost, "h", host,
1.275     djm      1245:                    "r", options.user, (char *)NULL);
                   1246:                xfree(cp);
1.131     millert  1247:                public = key_load_public(filename, NULL);
                   1248:                debug("identity file %s type %d", filename,
                   1249:                    public ? public->type : -1);
                   1250:                xfree(options.identity_files[i]);
                   1251:                options.identity_files[i] = filename;
                   1252:                options.identity_keys[i] = public;
                   1253:        }
1.214     djm      1254: }
                   1255:
                   1256: static void
                   1257: control_client_sighandler(int signo)
                   1258: {
                   1259:        control_client_terminate = signo;
                   1260: }
                   1261:
                   1262: static void
                   1263: control_client_sigrelay(int signo)
                   1264: {
                   1265:        if (control_server_pid > 1)
                   1266:                kill(control_server_pid, signo);
                   1267: }
                   1268:
1.220     djm      1269: static int
                   1270: env_permitted(char *env)
                   1271: {
1.282     dtucker  1272:        int i, ret;
1.220     djm      1273:        char name[1024], *cp;
                   1274:
1.282     dtucker  1275:        if ((cp = strchr(env, '=')) == NULL || cp == env)
1.220     djm      1276:                return (0);
1.284     stevesk  1277:        ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1.282     dtucker  1278:        if (ret <= 0 || (size_t)ret >= sizeof(name))
                   1279:                fatal("env_permitted: name '%.100s...' too long", env);
1.220     djm      1280:
                   1281:        for (i = 0; i < options.num_send_env; i++)
                   1282:                if (match_pattern(name, options.send_env[i]))
                   1283:                        return (1);
                   1284:
                   1285:        return (0);
                   1286: }
                   1287:
1.214     djm      1288: static void
                   1289: control_client(const char *path)
                   1290: {
                   1291:        struct sockaddr_un addr;
1.300     djm      1292:        int i, r, fd, sock, exitval[2], num_env;
1.214     djm      1293:        Buffer m;
1.229     djm      1294:        char *term;
1.215     djm      1295:        extern char **environ;
1.229     djm      1296:        u_int  flags;
1.242     djm      1297:
                   1298:        if (mux_command == 0)
                   1299:                mux_command = SSHMUX_COMMAND_OPEN;
                   1300:
                   1301:        switch (options.control_master) {
                   1302:        case SSHCTL_MASTER_AUTO:
                   1303:        case SSHCTL_MASTER_AUTO_ASK:
                   1304:                debug("auto-mux: Trying existing master");
                   1305:                /* FALLTHROUGH */
                   1306:        case SSHCTL_MASTER_NO:
                   1307:                break;
                   1308:        default:
                   1309:                return;
                   1310:        }
1.228     djm      1311:
1.214     djm      1312:        memset(&addr, '\0', sizeof(addr));
                   1313:        addr.sun_family = AF_UNIX;
                   1314:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1315:            strlen(path) + 1;
                   1316:
                   1317:        if (strlcpy(addr.sun_path, path,
                   1318:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1319:                fatal("ControlPath too long");
                   1320:
                   1321:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1322:                fatal("%s socket(): %s", __func__, strerror(errno));
                   1323:
1.270     deraadt  1324:        if (connect(sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
1.240     djm      1325:                if (mux_command != SSHMUX_COMMAND_OPEN) {
                   1326:                        fatal("Control socket connect(%.100s): %s", path,
                   1327:                            strerror(errno));
                   1328:                }
1.239     djm      1329:                if (errno == ENOENT)
1.268     deraadt  1330:                        debug("Control socket \"%.100s\" does not exist", path);
1.239     djm      1331:                else {
1.268     deraadt  1332:                        error("Control socket connect(%.100s): %s", path,
1.239     djm      1333:                            strerror(errno));
                   1334:                }
1.268     deraadt  1335:                close(sock);
                   1336:                return;
                   1337:        }
1.248     djm      1338:
1.268     deraadt  1339:        if (stdin_null_flag) {
                   1340:                if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1341:                        fatal("open(/dev/null): %s", strerror(errno));
                   1342:                if (dup2(fd, STDIN_FILENO) == -1)
                   1343:                        fatal("dup2: %s", strerror(errno));
                   1344:                if (fd > STDERR_FILENO)
                   1345:                        close(fd);
                   1346:        }
1.248     djm      1347:
1.247     djm      1348:        term = getenv("TERM");
1.229     djm      1349:
                   1350:        flags = 0;
                   1351:        if (tty_flag)
                   1352:                flags |= SSHMUX_FLAG_TTY;
                   1353:        if (subsystem_flag)
                   1354:                flags |= SSHMUX_FLAG_SUBSYS;
1.247     djm      1355:        if (options.forward_x11)
                   1356:                flags |= SSHMUX_FLAG_X11_FWD;
                   1357:        if (options.forward_agent)
                   1358:                flags |= SSHMUX_FLAG_AGENT_FWD;
1.214     djm      1359:
                   1360:        buffer_init(&m);
                   1361:
1.229     djm      1362:        /* Send our command to server */
                   1363:        buffer_put_int(&m, mux_command);
                   1364:        buffer_put_int(&m, flags);
1.247     djm      1365:        if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1.229     djm      1366:                fatal("%s: msg_send", __func__);
                   1367:        buffer_clear(&m);
                   1368:
                   1369:        /* Get authorisation status and PID of controlee */
1.214     djm      1370:        if (ssh_msg_recv(sock, &m) == -1)
                   1371:                fatal("%s: msg_recv", __func__);
1.247     djm      1372:        if (buffer_get_char(&m) != SSHMUX_VER)
1.214     djm      1373:                fatal("%s: wrong version", __func__);
1.216     djm      1374:        if (buffer_get_int(&m) != 1)
                   1375:                fatal("Connection to master denied");
1.214     djm      1376:        control_server_pid = buffer_get_int(&m);
                   1377:
                   1378:        buffer_clear(&m);
                   1379:
1.229     djm      1380:        switch (mux_command) {
                   1381:        case SSHMUX_COMMAND_ALIVE_CHECK:
1.234     deraadt  1382:                fprintf(stderr, "Master running (pid=%d)\r\n",
1.229     djm      1383:                    control_server_pid);
                   1384:                exit(0);
                   1385:        case SSHMUX_COMMAND_TERMINATE:
                   1386:                fprintf(stderr, "Exit request sent.\r\n");
                   1387:                exit(0);
                   1388:        case SSHMUX_COMMAND_OPEN:
                   1389:                /* continue below */
                   1390:                break;
                   1391:        default:
                   1392:                fatal("silly mux_command %d", mux_command);
                   1393:        }
                   1394:
                   1395:        /* SSHMUX_COMMAND_OPEN */
1.247     djm      1396:        buffer_put_cstring(&m, term ? term : "");
1.214     djm      1397:        buffer_append(&command, "\0", 1);
                   1398:        buffer_put_cstring(&m, buffer_ptr(&command));
1.215     djm      1399:
1.220     djm      1400:        if (options.num_send_env == 0 || environ == NULL) {
                   1401:                buffer_put_int(&m, 0);
1.223     deraadt  1402:        } else {
1.220     djm      1403:                /* Pass environment */
                   1404:                num_env = 0;
                   1405:                for (i = 0; environ[i] != NULL; i++)
                   1406:                        if (env_permitted(environ[i]))
                   1407:                                num_env++; /* Count */
1.223     deraadt  1408:
1.220     djm      1409:                buffer_put_int(&m, num_env);
                   1410:
1.222     dtucker  1411:                for (i = 0; environ[i] != NULL && num_env >= 0; i++)
                   1412:                        if (env_permitted(environ[i])) {
                   1413:                                num_env--;
1.220     djm      1414:                                buffer_put_cstring(&m, environ[i]);
1.222     dtucker  1415:                        }
1.220     djm      1416:        }
1.214     djm      1417:
1.247     djm      1418:        if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1.214     djm      1419:                fatal("%s: msg_send", __func__);
                   1420:
1.302     djm      1421:        if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
                   1422:            mm_send_fd(sock, STDOUT_FILENO) == -1 ||
                   1423:            mm_send_fd(sock, STDERR_FILENO) == -1)
                   1424:                fatal("%s: send fds failed", __func__);
1.214     djm      1425:
                   1426:        /* Wait for reply, so master has a chance to gather ttymodes */
                   1427:        buffer_clear(&m);
                   1428:        if (ssh_msg_recv(sock, &m) == -1)
                   1429:                fatal("%s: msg_recv", __func__);
1.247     djm      1430:        if (buffer_get_char(&m) != SSHMUX_VER)
1.229     djm      1431:                fatal("%s: wrong version", __func__);
1.214     djm      1432:        buffer_free(&m);
1.218     djm      1433:
1.226     djm      1434:        signal(SIGHUP, control_client_sighandler);
1.218     djm      1435:        signal(SIGINT, control_client_sighandler);
                   1436:        signal(SIGTERM, control_client_sighandler);
                   1437:        signal(SIGWINCH, control_client_sigrelay);
1.214     djm      1438:
                   1439:        if (tty_flag)
                   1440:                enter_raw_mode();
                   1441:
1.300     djm      1442:        /*
                   1443:         * Stick around until the controlee closes the client_fd.
                   1444:         * Before it does, it is expected to write this process' exit
                   1445:         * value (one int). This process must read the value and wait for
                   1446:         * the closure of the client_fd; if this one closes early, the
                   1447:         * multiplex master will terminate early too (possibly losing data).
                   1448:         */
                   1449:        exitval[0] = 0;
1.296     djm      1450:        for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1.300     djm      1451:                r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1.214     djm      1452:                if (r == 0) {
                   1453:                        debug2("Received EOF from master");
                   1454:                        break;
                   1455:                }
1.299     djm      1456:                if (r == -1) {
                   1457:                        if (errno == EINTR)
                   1458:                                continue;
1.214     djm      1459:                        fatal("%s: read %s", __func__, strerror(errno));
1.299     djm      1460:                }
1.296     djm      1461:                i += r;
1.214     djm      1462:        }
1.300     djm      1463:
1.296     djm      1464:        close(sock);
                   1465:        leave_raw_mode();
1.300     djm      1466:        if (i > (int)sizeof(int))
                   1467:                fatal("%s: master returned too much data (%d > %lu)",
                   1468:                    __func__, i, sizeof(int));
1.296     djm      1469:        if (control_client_terminate) {
1.214     djm      1470:                debug2("Exiting on signal %d", control_client_terminate);
1.300     djm      1471:                exitval[0] = 255;
                   1472:        } else if (i < (int)sizeof(int)) {
1.296     djm      1473:                debug2("Control master terminated unexpectedly");
1.300     djm      1474:                exitval[0] = 255;
1.296     djm      1475:        } else
1.300     djm      1476:                debug2("Received exit status from master %d", exitval[0]);
1.214     djm      1477:
                   1478:        if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1.300     djm      1479:                fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1.214     djm      1480:
1.300     djm      1481:        exit(exitval[0]);
1.1       deraadt  1482: }