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

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