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

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