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

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.240   ! djm        43: RCSID("$OpenBSD: ssh.c,v 1.239 2005/05/10 10:30:43 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 */
1.240   ! djm       148: static u_int mux_command = 0;
1.229     djm       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.233     jmc       161: "           [-D port] [-e escape_char] [-F configfile]\n"
                    162: "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
1.232     djm       163: "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
1.233     jmc       164: "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
1.230     jmc       165: "           [user@]hostname [command]\n"
1.208     markus    166:        );
1.31      markus    167:        exit(1);
1.1       deraadt   168: }
                    169:
1.126     itojun    170: static int ssh_session(void);
                    171: static int ssh_session2(void);
                    172: static void load_public_identity_files(void);
1.214     djm       173: static void control_client(const char *path);
1.45      markus    174:
1.32      deraadt   175: /*
                    176:  * Main program for the ssh client.
                    177:  */
1.2       provos    178: int
                    179: main(int ac, char **av)
1.1       deraadt   180: {
1.178     markus    181:        int i, opt, exit_status;
1.205     markus    182:        char *p, *cp, *line, buf[256];
1.31      markus    183:        struct stat st;
1.98      markus    184:        struct passwd *pw;
1.45      markus    185:        int dummy;
1.144     stevesk   186:        extern int optind, optreset;
                    187:        extern char *optarg;
1.232     djm       188:        Forward fwd;
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 "
1.231     otto      295:                                    "not accessible: %s.\n", optarg,
                    296:                                    strerror(errno));
1.31      markus    297:                                break;
                    298:                        }
1.128     fgsch     299:                        if (options.num_identity_files >=
                    300:                            SSH_MAX_IDENTITY_FILES)
                    301:                                fatal("Too many identity files specified "
                    302:                                    "(max %d)", SSH_MAX_IDENTITY_FILES);
                    303:                        options.identity_files[options.num_identity_files++] =
                    304:                            xstrdup(optarg);
1.31      markus    305:                        break;
1.127     markus    306:                case 'I':
                    307: #ifdef SMARTCARD
1.133     markus    308:                        options.smartcard_device = xstrdup(optarg);
1.137     jakob     309: #else
1.127     markus    310:                        fprintf(stderr, "no support for smartcards.\n");
1.137     jakob     311: #endif
1.127     markus    312:                        break;
1.31      markus    313:                case 't':
1.79      markus    314:                        if (tty_flag)
                    315:                                force_tty_flag = 1;
1.31      markus    316:                        tty_flag = 1;
                    317:                        break;
                    318:                case 'v':
1.197     markus    319:                        if (debug_flag == 0) {
1.66      markus    320:                                debug_flag = 1;
                    321:                                options.log_level = SYSLOG_LEVEL_DEBUG1;
1.197     markus    322:                        } else {
                    323:                                if (options.log_level < SYSLOG_LEVEL_DEBUG3)
                    324:                                        options.log_level++;
1.66      markus    325:                                break;
1.197     markus    326:                        }
1.227     deraadt   327:                        /* FALLTHROUGH */
1.31      markus    328:                case 'V':
1.209     markus    329:                        fprintf(stderr, "%s, %s\n",
                    330:                            SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.31      markus    331:                        if (opt == 'V')
                    332:                                exit(0);
                    333:                        break;
                    334:                case 'q':
                    335:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    336:                        break;
                    337:                case 'e':
                    338:                        if (optarg[0] == '^' && optarg[2] == 0 &&
1.128     fgsch     339:                            (u_char) optarg[1] >= 64 &&
                    340:                            (u_char) optarg[1] < 128)
1.78      markus    341:                                options.escape_char = (u_char) optarg[1] & 31;
1.31      markus    342:                        else if (strlen(optarg) == 1)
1.78      markus    343:                                options.escape_char = (u_char) optarg[0];
1.31      markus    344:                        else if (strcmp(optarg, "none") == 0)
1.119     stevesk   345:                                options.escape_char = SSH_ESCAPECHAR_NONE;
1.31      markus    346:                        else {
1.128     fgsch     347:                                fprintf(stderr, "Bad escape character '%s'.\n",
                    348:                                    optarg);
1.31      markus    349:                                exit(1);
                    350:                        }
                    351:                        break;
                    352:                case 'c':
1.49      markus    353:                        if (ciphers_valid(optarg)) {
                    354:                                /* SSH2 only */
                    355:                                options.ciphers = xstrdup(optarg);
1.224     markus    356:                                options.cipher = SSH_CIPHER_INVALID;
1.49      markus    357:                        } else {
                    358:                                /* SSH1 only */
1.74      markus    359:                                options.cipher = cipher_number(optarg);
                    360:                                if (options.cipher == -1) {
1.128     fgsch     361:                                        fprintf(stderr,
                    362:                                            "Unknown cipher type '%s'\n",
                    363:                                            optarg);
1.49      markus    364:                                        exit(1);
                    365:                                }
1.128     fgsch     366:                                if (options.cipher == SSH_CIPHER_3DES)
1.74      markus    367:                                        options.ciphers = "3des-cbc";
1.128     fgsch     368:                                else if (options.cipher == SSH_CIPHER_BLOWFISH)
1.74      markus    369:                                        options.ciphers = "blowfish-cbc";
1.128     fgsch     370:                                else
1.74      markus    371:                                        options.ciphers = (char *)-1;
1.95      markus    372:                        }
                    373:                        break;
                    374:                case 'm':
                    375:                        if (mac_valid(optarg))
                    376:                                options.macs = xstrdup(optarg);
                    377:                        else {
1.128     fgsch     378:                                fprintf(stderr, "Unknown mac type '%s'\n",
                    379:                                    optarg);
1.95      markus    380:                                exit(1);
1.31      markus    381:                        }
                    382:                        break;
1.214     djm       383:                case 'M':
1.219     markus    384:                        options.control_master =
                    385:                            (options.control_master >= 1) ? 2 : 1;
1.214     djm       386:                        break;
1.31      markus    387:                case 'p':
1.113     stevesk   388:                        options.port = a2port(optarg);
                    389:                        if (options.port == 0) {
1.109     markus    390:                                fprintf(stderr, "Bad port '%s'\n", optarg);
                    391:                                exit(1);
                    392:                        }
1.31      markus    393:                        break;
                    394:                case 'l':
                    395:                        options.user = optarg;
                    396:                        break;
1.141     stevesk   397:
                    398:                case 'L':
1.232     djm       399:                        if (parse_forward(&fwd, optarg))
                    400:                                add_local_forward(&options, &fwd);
                    401:                        else {
1.128     fgsch     402:                                fprintf(stderr,
1.232     djm       403:                                    "Bad local forwarding specification '%s'\n",
1.128     fgsch     404:                                    optarg);
1.232     djm       405:                                exit(1);
1.31      markus    406:                        }
1.232     djm       407:                        break;
                    408:
                    409:                case 'R':
                    410:                        if (parse_forward(&fwd, optarg)) {
                    411:                                add_remote_forward(&options, &fwd);
                    412:                        } else {
1.128     fgsch     413:                                fprintf(stderr,
1.232     djm       414:                                    "Bad remote forwarding specification "
                    415:                                    "'%s'\n", optarg);
1.141     stevesk   416:                                exit(1);
1.31      markus    417:                        }
                    418:                        break;
1.108     markus    419:
                    420:                case 'D':
1.232     djm       421:                        cp = p = xstrdup(optarg);
                    422:                        memset(&fwd, '\0', sizeof(fwd));
                    423:                        fwd.connect_host = "socks";
                    424:                        if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
                    425:                                fprintf(stderr, "Bad dynamic forwarding "
                    426:                                    "specification '%.100s'\n", optarg);
                    427:                                exit(1);
                    428:                        }
                    429:                        if (cp != NULL) {
                    430:                                fwd.listen_port = a2port(cp);
                    431:                                fwd.listen_host = cleanhostname(fwd.listen_host);
                    432:                        } else {
                    433:                                fwd.listen_port = a2port(fwd.listen_host);
                    434:                                fwd.listen_host = "";
                    435:                        }
                    436:
                    437:                        if (fwd.listen_port == 0) {
1.128     fgsch     438:                                fprintf(stderr, "Bad dynamic port '%s'\n",
                    439:                                    optarg);
1.109     markus    440:                                exit(1);
                    441:                        }
1.232     djm       442:                        add_local_forward(&options, &fwd);
                    443:                        xfree(p);
1.108     markus    444:                        break;
                    445:
1.31      markus    446:                case 'C':
                    447:                        options.compression = 1;
                    448:                        break;
1.45      markus    449:                case 'N':
                    450:                        no_shell_flag = 1;
                    451:                        no_tty_flag = 1;
                    452:                        break;
                    453:                case 'T':
                    454:                        no_tty_flag = 1;
                    455:                        break;
1.31      markus    456:                case 'o':
                    457:                        dummy = 1;
1.205     markus    458:                        line = xstrdup(optarg);
1.128     fgsch     459:                        if (process_config_line(&options, host ? host : "",
1.205     markus    460:                            line, "command-line", 0, &dummy) != 0)
1.31      markus    461:                                exit(1);
1.205     markus    462:                        xfree(line);
1.31      markus    463:                        break;
1.85      djm       464:                case 's':
                    465:                        subsystem_flag = 1;
1.117     markus    466:                        break;
1.214     djm       467:                case 'S':
                    468:                        if (options.control_path != NULL)
                    469:                                free(options.control_path);
                    470:                        options.control_path = xstrdup(optarg);
                    471:                        break;
1.117     markus    472:                case 'b':
                    473:                        options.bind_address = optarg;
1.85      djm       474:                        break;
1.139     markus    475:                case 'F':
                    476:                        config = optarg;
                    477:                        break;
1.31      markus    478:                default:
                    479:                        usage();
1.1       deraadt   480:                }
1.31      markus    481:        }
                    482:
1.128     fgsch     483:        ac -= optind;
                    484:        av += optind;
                    485:
                    486:        if (ac > 0 && !host && **av != '-') {
1.188     markus    487:                if (strrchr(*av, '@')) {
1.128     fgsch     488:                        p = xstrdup(*av);
1.188     markus    489:                        cp = strrchr(p, '@');
1.128     fgsch     490:                        if (cp == NULL || cp == p)
                    491:                                usage();
                    492:                        options.user = p;
                    493:                        *cp = '\0';
                    494:                        host = ++cp;
                    495:                } else
                    496:                        host = *av;
1.189     millert   497:                if (ac > 1) {
                    498:                        optind = optreset = 1;
1.128     fgsch     499:                        goto again;
                    500:                }
1.189     millert   501:                ac--, av++;
1.128     fgsch     502:        }
                    503:
1.31      markus    504:        /* Check that we got a host name. */
                    505:        if (!host)
                    506:                usage();
                    507:
1.54      markus    508:        SSLeay_add_all_algorithms();
1.72      markus    509:        ERR_load_crypto_strings();
1.31      markus    510:
                    511:        /* Initialize the command to execute on remote host. */
                    512:        buffer_init(&command);
1.1       deraadt   513:
1.33      markus    514:        /*
                    515:         * Save the command to execute on the remote host in a buffer. There
                    516:         * is no limit on the length of the command, except by the maximum
                    517:         * packet size.  Also sets the tty flag if there is no command.
                    518:         */
1.128     fgsch     519:        if (!ac) {
1.31      markus    520:                /* No command specified - execute shell on a tty. */
                    521:                tty_flag = 1;
1.85      djm       522:                if (subsystem_flag) {
1.128     fgsch     523:                        fprintf(stderr,
                    524:                            "You must specify a subsystem to invoke.\n");
1.85      djm       525:                        usage();
                    526:                }
1.31      markus    527:        } else {
1.128     fgsch     528:                /* A command has been specified.  Store it into the buffer. */
                    529:                for (i = 0; i < ac; i++) {
                    530:                        if (i)
1.31      markus    531:                                buffer_append(&command, " ", 1);
                    532:                        buffer_append(&command, av[i], strlen(av[i]));
                    533:                }
                    534:        }
                    535:
                    536:        /* Cannot fork to background if no command. */
1.63      markus    537:        if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
1.31      markus    538:                fatal("Cannot fork into background without a command to execute.");
                    539:
                    540:        /* Allocate a tty by default if no command specified. */
                    541:        if (buffer_len(&command) == 0)
                    542:                tty_flag = 1;
                    543:
1.180     deraadt   544:        /* Force no tty */
1.75      markus    545:        if (no_tty_flag)
                    546:                tty_flag = 0;
1.31      markus    547:        /* Do not allocate a tty if stdin is not a tty. */
1.236     djm       548:        if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
1.31      markus    549:                if (tty_flag)
1.191     itojun    550:                        logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
1.31      markus    551:                tty_flag = 0;
                    552:        }
1.45      markus    553:
1.101     markus    554:        /*
                    555:         * Initialize "log" output.  Since we are the client all output
                    556:         * actually goes to stderr.
                    557:         */
1.111     markus    558:        log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
                    559:            SYSLOG_FACILITY_USER, 1);
1.31      markus    560:
1.139     markus    561:        /*
                    562:         * Read per-user configuration file.  Ignore the system wide config
                    563:         * file if the user specifies a config file on the command line.
                    564:         */
                    565:        if (config != NULL) {
1.211     djm       566:                if (!read_config_file(config, host, &options, 0))
1.142     stevesk   567:                        fatal("Can't open user config file %.100s: "
                    568:                            "%.100s", config, strerror(errno));
1.139     markus    569:        } else  {
                    570:                snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
                    571:                    _PATH_SSH_USER_CONFFILE);
1.210     djm       572:                (void)read_config_file(buf, host, &options, 1);
1.139     markus    573:
1.145     markus    574:                /* Read systemwide configuration file after use config. */
1.223     deraadt   575:                (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
1.210     djm       576:                    &options, 0);
1.139     markus    577:        }
1.31      markus    578:
                    579:        /* Fill configuration defaults. */
                    580:        fill_default_options(&options);
                    581:
1.196     djm       582:        channel_set_af(options.address_family);
                    583:
1.31      markus    584:        /* reinit */
1.101     markus    585:        log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
1.31      markus    586:
                    587:        if (options.user == NULL)
                    588:                options.user = xstrdup(pw->pw_name);
                    589:
                    590:        if (options.hostname != NULL)
                    591:                host = options.hostname;
1.195     markus    592:
                    593:        /* force lowercase for hostkey matching */
                    594:        if (options.host_key_alias != NULL) {
                    595:                for (p = options.host_key_alias; *p; p++)
                    596:                        if (isupper(*p))
                    597:                                *p = tolower(*p);
                    598:        }
1.190     markus    599:
                    600:        if (options.proxy_command != NULL &&
                    601:            strcmp(options.proxy_command, "none") == 0)
                    602:                options.proxy_command = NULL;
1.31      markus    603:
1.214     djm       604:        if (options.control_path != NULL) {
                    605:                options.control_path = tilde_expand_filename(
                    606:                   options.control_path, original_real_uid);
                    607:        }
1.240   ! djm       608:        if (mux_command != 0 && options.control_path == NULL)
        !           609:                fatal("No ControlPath specified for \"-O\" command");
        !           610:        if (options.control_path != NULL && options.control_master == 0) {
        !           611:                if (mux_command == 0)
        !           612:                        mux_command = SSHMUX_COMMAND_OPEN;
1.237     jakob     613:                control_client(options.control_path);
1.240   ! djm       614:        }
1.214     djm       615:
1.77      markus    616:        /* Open a connection to the remote host. */
1.203     djm       617:        if (ssh_connect(host, &hostaddr, options.port,
1.196     djm       618:            options.address_family, options.connection_attempts,
1.177     markus    619:            original_effective_uid == 0 && options.use_privileged_port,
1.179     markus    620:            options.proxy_command) != 0)
1.178     markus    621:                exit(1);
1.31      markus    622:
1.33      markus    623:        /*
                    624:         * If we successfully made the connection, load the host private key
                    625:         * in case we will need it later for combined rsa-rhosts
                    626:         * authentication. This must be done before releasing extra
                    627:         * privileges, because the file is only readable by root.
1.174     markus    628:         * If we cannot access the private keys, load the public keys
                    629:         * instead and try to execute the ssh-keysign helper instead.
1.33      markus    630:         */
1.112     markus    631:        sensitive_data.nkeys = 0;
                    632:        sensitive_data.keys = NULL;
1.173     markus    633:        sensitive_data.external_keysign = 0;
1.178     markus    634:        if (options.rhosts_rsa_authentication ||
                    635:            options.hostbased_authentication) {
1.112     markus    636:                sensitive_data.nkeys = 3;
1.180     deraadt   637:                sensitive_data.keys = xmalloc(sensitive_data.nkeys *
                    638:                    sizeof(Key));
1.177     markus    639:
                    640:                PRIV_START;
1.112     markus    641:                sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1.105     markus    642:                    _PATH_HOST_KEY_FILE, "", NULL);
1.112     markus    643:                sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
                    644:                    _PATH_HOST_DSA_KEY_FILE, "", NULL);
                    645:                sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
                    646:                    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1.177     markus    647:                PRIV_END;
1.173     markus    648:
1.181     markus    649:                if (options.hostbased_authentication == 1 &&
                    650:                    sensitive_data.keys[0] == NULL &&
1.173     markus    651:                    sensitive_data.keys[1] == NULL &&
                    652:                    sensitive_data.keys[2] == NULL) {
                    653:                        sensitive_data.keys[1] = key_load_public(
                    654:                            _PATH_HOST_DSA_KEY_FILE, NULL);
                    655:                        sensitive_data.keys[2] = key_load_public(
                    656:                            _PATH_HOST_RSA_KEY_FILE, NULL);
                    657:                        sensitive_data.external_keysign = 1;
                    658:                }
1.31      markus    659:        }
1.33      markus    660:        /*
                    661:         * Get rid of any extra privileges that we may have.  We will no
                    662:         * longer need them.  Also, extra privileges could make it very hard
                    663:         * to read identity files and other non-world-readable files from the
                    664:         * user's home directory if it happens to be on a NFS volume where
                    665:         * root is mapped to nobody.
                    666:         */
1.225     dtucker   667:        if (original_effective_uid == 0) {
                    668:                PRIV_START;
                    669:                permanently_set_uid(pw);
                    670:        }
1.31      markus    671:
1.33      markus    672:        /*
                    673:         * Now that we are back to our own permissions, create ~/.ssh
                    674:         * directory if it doesn\'t already exist.
                    675:         */
1.138     jakob     676:        snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1.31      markus    677:        if (stat(buf, &st) < 0)
1.57      djm       678:                if (mkdir(buf, 0700) < 0)
1.31      markus    679:                        error("Could not create directory '%.200s'.", buf);
                    680:
1.104     markus    681:        /* load options.identity_files */
                    682:        load_public_identity_files();
                    683:
                    684:        /* Expand ~ in known host file names. */
                    685:        /* XXX mem-leaks: */
1.72      markus    686:        options.system_hostfile =
                    687:            tilde_expand_filename(options.system_hostfile, original_real_uid);
                    688:        options.user_hostfile =
                    689:            tilde_expand_filename(options.user_hostfile, original_real_uid);
                    690:        options.system_hostfile2 =
                    691:            tilde_expand_filename(options.system_hostfile2, original_real_uid);
                    692:        options.user_hostfile2 =
                    693:            tilde_expand_filename(options.user_hostfile2, original_real_uid);
1.149     markus    694:
                    695:        signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1.31      markus    696:
                    697:        /* Log into the remote system.  This never returns if the login fails. */
1.173     markus    698:        ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
1.31      markus    699:
1.112     markus    700:        /* We no longer need the private host keys.  Clear them now. */
                    701:        if (sensitive_data.nkeys != 0) {
                    702:                for (i = 0; i < sensitive_data.nkeys; i++) {
                    703:                        if (sensitive_data.keys[i] != NULL) {
                    704:                                /* Destroys contents safely */
                    705:                                debug3("clear hostkey %d", i);
                    706:                                key_free(sensitive_data.keys[i]);
                    707:                                sensitive_data.keys[i] = NULL;
                    708:                        }
                    709:                }
                    710:                xfree(sensitive_data.keys);
1.134     markus    711:        }
                    712:        for (i = 0; i < options.num_identity_files; i++) {
                    713:                if (options.identity_files[i]) {
                    714:                        xfree(options.identity_files[i]);
                    715:                        options.identity_files[i] = NULL;
                    716:                }
                    717:                if (options.identity_keys[i]) {
                    718:                        key_free(options.identity_keys[i]);
                    719:                        options.identity_keys[i] = NULL;
                    720:                }
1.112     markus    721:        }
1.31      markus    722:
1.45      markus    723:        exit_status = compat20 ? ssh_session2() : ssh_session();
                    724:        packet_close();
1.186     djm       725:
1.214     djm       726:        if (options.control_path != NULL && control_fd != -1)
                    727:                unlink(options.control_path);
                    728:
1.186     djm       729:        /*
1.203     djm       730:         * Send SIGHUP to proxy command if used. We don't wait() in
1.186     djm       731:         * case it hangs and instead rely on init to reap the child
                    732:         */
                    733:        if (proxy_command_pid > 1)
                    734:                kill(proxy_command_pid, SIGHUP);
                    735:
1.45      markus    736:        return exit_status;
                    737: }
                    738:
1.202     markus    739: #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
                    740:
1.126     itojun    741: static void
1.150     stevesk   742: x11_get_proto(char **_proto, char **_data)
1.50      markus    743: {
1.202     markus    744:        char cmd[1024];
1.50      markus    745:        char line[512];
1.202     markus    746:        char xdisplay[512];
1.150     stevesk   747:        static char proto[512], data[512];
1.50      markus    748:        FILE *f;
1.202     markus    749:        int got_data = 0, generated = 0, do_unlink = 0, i;
                    750:        char *display, *xauthdir, *xauthfile;
1.182     stevesk   751:        struct stat st;
1.50      markus    752:
1.202     markus    753:        xauthdir = xauthfile = NULL;
1.150     stevesk   754:        *_proto = proto;
                    755:        *_data = data;
                    756:        proto[0] = data[0] = '\0';
1.202     markus    757:
1.182     stevesk   758:        if (!options.xauth_location ||
                    759:            (stat(options.xauth_location, &st) == -1)) {
                    760:                debug("No xauth program.");
                    761:        } else {
                    762:                if ((display = getenv("DISPLAY")) == NULL) {
                    763:                        debug("x11_get_proto: DISPLAY not set");
                    764:                        return;
                    765:                }
1.202     markus    766:                /*
                    767:                 * Handle FamilyLocal case where $DISPLAY does
                    768:                 * not match an authorization entry.  For this we
                    769:                 * just try "xauth list unix:displaynum.screennum".
                    770:                 * XXX: "localhost" match to determine FamilyLocal
                    771:                 *      is not perfect.
                    772:                 */
                    773:                if (strncmp(display, "localhost:", 10) == 0) {
                    774:                        snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    775:                            display + 10);
                    776:                        display = xdisplay;
                    777:                }
                    778:                if (options.forward_x11_trusted == 0) {
                    779:                        xauthdir = xmalloc(MAXPATHLEN);
                    780:                        xauthfile = xmalloc(MAXPATHLEN);
                    781:                        strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
                    782:                        if (mkdtemp(xauthdir) != NULL) {
                    783:                                do_unlink = 1;
                    784:                                snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
                    785:                                    xauthdir);
                    786:                                snprintf(cmd, sizeof(cmd),
                    787:                                    "%s -f %s generate %s " SSH_X11_PROTO
1.207     markus    788:                                    " untrusted timeout 1200 2>" _PATH_DEVNULL,
1.202     markus    789:                                    options.xauth_location, xauthfile, display);
                    790:                                debug2("x11_get_proto: %s", cmd);
                    791:                                if (system(cmd) == 0)
                    792:                                        generated = 1;
                    793:                        }
                    794:                }
                    795:                snprintf(cmd, sizeof(cmd),
                    796:                    "%s %s%s list %s . 2>" _PATH_DEVNULL,
                    797:                    options.xauth_location,
                    798:                    generated ? "-f " : "" ,
                    799:                    generated ? xauthfile : "",
                    800:                    display);
                    801:                debug2("x11_get_proto: %s", cmd);
                    802:                f = popen(cmd, "r");
1.55      markus    803:                if (f && fgets(line, sizeof(line), f) &&
1.150     stevesk   804:                    sscanf(line, "%*s %511s %511s", proto, data) == 2)
1.55      markus    805:                        got_data = 1;
                    806:                if (f)
                    807:                        pclose(f);
                    808:        }
1.202     markus    809:
                    810:        if (do_unlink) {
                    811:                unlink(xauthfile);
                    812:                rmdir(xauthdir);
                    813:        }
                    814:        if (xauthdir)
                    815:                xfree(xauthdir);
                    816:        if (xauthfile)
                    817:                xfree(xauthfile);
                    818:
1.50      markus    819:        /*
                    820:         * If we didn't get authentication data, just make up some
                    821:         * data.  The forwarding code will check the validity of the
                    822:         * response anyway, and substitute this data.  The X11
                    823:         * server, however, will ignore this fake data and use
                    824:         * whatever authentication mechanisms it was using otherwise
                    825:         * for the local connection.
                    826:         */
                    827:        if (!got_data) {
1.221     avsm      828:                u_int32_t rnd = 0;
1.50      markus    829:
1.202     markus    830:                logit("Warning: No xauth data; "
                    831:                    "using fake authentication data for X11 forwarding.");
                    832:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
1.50      markus    833:                for (i = 0; i < 16; i++) {
                    834:                        if (i % 4 == 0)
1.221     avsm      835:                                rnd = arc4random();
1.202     markus    836:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
1.221     avsm      837:                            rnd & 0xff);
                    838:                        rnd >>= 8;
1.50      markus    839:                }
                    840:        }
                    841: }
                    842:
1.126     itojun    843: static void
1.70      markus    844: ssh_init_forwarding(void)
                    845: {
1.86      markus    846:        int success = 0;
1.70      markus    847:        int i;
1.86      markus    848:
1.70      markus    849:        /* Initiate local TCP/IP port forwardings. */
                    850:        for (i = 0; i < options.num_local_forwards; i++) {
1.232     djm       851:                debug("Local connections to %.200s:%d forwarded to remote "
                    852:                    "address %.200s:%d",
1.234     deraadt   853:                    (options.local_forwards[i].listen_host == NULL) ?
                    854:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       855:                    options.local_forwards[i].listen_host,
                    856:                    options.local_forwards[i].listen_port,
                    857:                    options.local_forwards[i].connect_host,
                    858:                    options.local_forwards[i].connect_port);
1.158     markus    859:                success += channel_setup_local_fwd_listener(
1.232     djm       860:                    options.local_forwards[i].listen_host,
                    861:                    options.local_forwards[i].listen_port,
                    862:                    options.local_forwards[i].connect_host,
                    863:                    options.local_forwards[i].connect_port,
1.70      markus    864:                    options.gateway_ports);
                    865:        }
1.86      markus    866:        if (i > 0 && success == 0)
                    867:                error("Could not request local forwarding.");
1.70      markus    868:
                    869:        /* Initiate remote TCP/IP port forwardings. */
                    870:        for (i = 0; i < options.num_remote_forwards; i++) {
1.232     djm       871:                debug("Remote connections from %.200s:%d forwarded to "
                    872:                    "local address %.200s:%d",
1.235     dtucker   873:                    (options.remote_forwards[i].listen_host == NULL) ?
                    874:                    (options.gateway_ports ? "*" : "LOCALHOST") :
1.232     djm       875:                    options.remote_forwards[i].listen_host,
                    876:                    options.remote_forwards[i].listen_port,
                    877:                    options.remote_forwards[i].connect_host,
                    878:                    options.remote_forwards[i].connect_port);
1.70      markus    879:                channel_request_remote_forwarding(
1.232     djm       880:                    options.remote_forwards[i].listen_host,
                    881:                    options.remote_forwards[i].listen_port,
                    882:                    options.remote_forwards[i].connect_host,
                    883:                    options.remote_forwards[i].connect_port);
1.70      markus    884:        }
                    885: }
                    886:
1.126     itojun    887: static void
1.70      markus    888: check_agent_present(void)
                    889: {
                    890:        if (options.forward_agent) {
                    891:                /* Clear agent forwarding if we don\'t have an agent. */
1.185     stevesk   892:                if (!ssh_agent_present())
1.70      markus    893:                        options.forward_agent = 0;
                    894:        }
                    895: }
                    896:
1.126     itojun    897: static int
1.45      markus    898: ssh_session(void)
                    899: {
                    900:        int type;
                    901:        int interactive = 0;
                    902:        int have_tty = 0;
                    903:        struct winsize ws;
                    904:        char *cp;
                    905:
1.31      markus    906:        /* Enable compression if requested. */
                    907:        if (options.compression) {
                    908:                debug("Requesting compression at level %d.", options.compression_level);
                    909:
                    910:                if (options.compression_level < 1 || options.compression_level > 9)
                    911:                        fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
                    912:
                    913:                /* Send the request. */
                    914:                packet_start(SSH_CMSG_REQUEST_COMPRESSION);
                    915:                packet_put_int(options.compression_level);
                    916:                packet_send();
                    917:                packet_write_wait();
1.156     markus    918:                type = packet_read();
1.31      markus    919:                if (type == SSH_SMSG_SUCCESS)
                    920:                        packet_start_compression(options.compression_level);
                    921:                else if (type == SSH_SMSG_FAILURE)
1.191     itojun    922:                        logit("Warning: Remote host refused compression.");
1.31      markus    923:                else
                    924:                        packet_disconnect("Protocol error waiting for compression response.");
                    925:        }
                    926:        /* Allocate a pseudo tty if appropriate. */
                    927:        if (tty_flag) {
                    928:                debug("Requesting pty.");
                    929:
                    930:                /* Start the packet. */
                    931:                packet_start(SSH_CMSG_REQUEST_PTY);
                    932:
                    933:                /* Store TERM in the packet.  There is no limit on the
                    934:                   length of the string. */
                    935:                cp = getenv("TERM");
                    936:                if (!cp)
                    937:                        cp = "";
1.124     markus    938:                packet_put_cstring(cp);
1.31      markus    939:
                    940:                /* Store window size in the packet. */
                    941:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    942:                        memset(&ws, 0, sizeof(ws));
                    943:                packet_put_int(ws.ws_row);
                    944:                packet_put_int(ws.ws_col);
                    945:                packet_put_int(ws.ws_xpixel);
                    946:                packet_put_int(ws.ws_ypixel);
                    947:
                    948:                /* Store tty modes in the packet. */
1.115     stevesk   949:                tty_make_modes(fileno(stdin), NULL);
1.31      markus    950:
                    951:                /* Send the packet, and wait for it to leave. */
                    952:                packet_send();
                    953:                packet_write_wait();
                    954:
                    955:                /* Read response from the server. */
1.156     markus    956:                type = packet_read();
1.43      markus    957:                if (type == SSH_SMSG_SUCCESS) {
1.31      markus    958:                        interactive = 1;
1.45      markus    959:                        have_tty = 1;
1.43      markus    960:                } else if (type == SSH_SMSG_FAILURE)
1.191     itojun    961:                        logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
1.31      markus    962:                else
                    963:                        packet_disconnect("Protocol error waiting for pty request response.");
                    964:        }
                    965:        /* Request X11 forwarding if enabled and DISPLAY is set. */
                    966:        if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1.150     stevesk   967:                char *proto, *data;
1.50      markus    968:                /* Get reasonable local authentication information. */
1.150     stevesk   969:                x11_get_proto(&proto, &data);
1.50      markus    970:                /* Request forwarding with authentication spoofing. */
1.31      markus    971:                debug("Requesting X11 forwarding with authentication spoofing.");
1.50      markus    972:                x11_request_forwarding_with_spoofing(0, proto, data);
1.31      markus    973:
                    974:                /* Read response from the server. */
1.156     markus    975:                type = packet_read();
1.31      markus    976:                if (type == SSH_SMSG_SUCCESS) {
                    977:                        interactive = 1;
1.50      markus    978:                } else if (type == SSH_SMSG_FAILURE) {
1.191     itojun    979:                        logit("Warning: Remote host denied X11 forwarding.");
1.50      markus    980:                } else {
1.31      markus    981:                        packet_disconnect("Protocol error waiting for X11 forwarding");
1.50      markus    982:                }
1.31      markus    983:        }
                    984:        /* Tell the packet module whether this is an interactive session. */
1.80      markus    985:        packet_set_interactive(interactive);
1.31      markus    986:
                    987:        /* Request authentication agent forwarding if appropriate. */
1.70      markus    988:        check_agent_present();
                    989:
1.31      markus    990:        if (options.forward_agent) {
                    991:                debug("Requesting authentication agent forwarding.");
                    992:                auth_request_forwarding();
                    993:
                    994:                /* Read response from the server. */
1.156     markus    995:                type = packet_read();
1.155     markus    996:                packet_check_eom();
1.31      markus    997:                if (type != SSH_SMSG_SUCCESS)
1.191     itojun    998:                        logit("Warning: Remote host denied authentication agent forwarding.");
1.31      markus    999:        }
                   1000:
1.70      markus   1001:        /* Initiate port forwardings. */
                   1002:        ssh_init_forwarding();
1.34      markus   1003:
                   1004:        /* If requested, let ssh continue in the background. */
1.48      markus   1005:        if (fork_after_authentication_flag)
1.34      markus   1006:                if (daemon(1, 1) < 0)
                   1007:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus   1008:
1.33      markus   1009:        /*
                   1010:         * If a command was specified on the command line, execute the
                   1011:         * command now. Otherwise request the server to start a shell.
                   1012:         */
1.31      markus   1013:        if (buffer_len(&command) > 0) {
                   1014:                int len = buffer_len(&command);
                   1015:                if (len > 900)
                   1016:                        len = 900;
1.152     stevesk  1017:                debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1.31      markus   1018:                packet_start(SSH_CMSG_EXEC_CMD);
                   1019:                packet_put_string(buffer_ptr(&command), buffer_len(&command));
                   1020:                packet_send();
                   1021:                packet_write_wait();
                   1022:        } else {
                   1023:                debug("Requesting shell.");
                   1024:                packet_start(SSH_CMSG_EXEC_SHELL);
                   1025:                packet_send();
                   1026:                packet_write_wait();
                   1027:        }
                   1028:
                   1029:        /* Enter the interactive session. */
1.119     stevesk  1030:        return client_loop(have_tty, tty_flag ?
                   1031:            options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1.45      markus   1032: }
                   1033:
1.126     itojun   1034: static void
1.214     djm      1035: ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1.89      markus   1036: {
                   1037:        int id, len;
                   1038:
                   1039:        id = packet_get_int();
                   1040:        len = buffer_len(&command);
1.100     markus   1041:        if (len > 900)
                   1042:                len = 900;
1.155     markus   1043:        packet_check_eom();
1.89      markus   1044:        if (type == SSH2_MSG_CHANNEL_FAILURE)
                   1045:                fatal("Request for subsystem '%.*s' failed on channel %d",
1.152     stevesk  1046:                    len, (u_char *)buffer_ptr(&command), id);
1.170     markus   1047: }
                   1048:
                   1049: void
1.206     markus   1050: client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1.170     markus   1051: {
                   1052:        int i;
                   1053:
                   1054:        i = client_global_request_id++;
1.206     markus   1055:        if (i >= options.num_remote_forwards)
1.170     markus   1056:                return;
                   1057:        debug("remote forward %s for: listen %d, connect %s:%d",
                   1058:            type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1.232     djm      1059:            options.remote_forwards[i].listen_port,
                   1060:            options.remote_forwards[i].connect_host,
                   1061:            options.remote_forwards[i].connect_port);
1.170     markus   1062:        if (type == SSH2_MSG_REQUEST_FAILURE)
1.232     djm      1063:                logit("Warning: remote port forwarding failed for listen "
                   1064:                    "port %d", options.remote_forwards[i].listen_port);
1.89      markus   1065: }
                   1066:
1.126     itojun   1067: static void
1.214     djm      1068: ssh_control_listener(void)
1.45      markus   1069: {
1.214     djm      1070:        struct sockaddr_un addr;
                   1071:        mode_t old_umask;
1.223     deraadt  1072:
1.216     djm      1073:        if (options.control_path == NULL || options.control_master <= 0)
1.214     djm      1074:                return;
                   1075:
                   1076:        memset(&addr, '\0', sizeof(addr));
                   1077:        addr.sun_family = AF_UNIX;
                   1078:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1079:            strlen(options.control_path) + 1;
                   1080:
                   1081:        if (strlcpy(addr.sun_path, options.control_path,
                   1082:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1083:                fatal("ControlPath too long");
                   1084:
                   1085:        if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1086:                fatal("%s socket(): %s\n", __func__, strerror(errno));
                   1087:
                   1088:        old_umask = umask(0177);
                   1089:        if (bind(control_fd, (struct sockaddr*)&addr, addr.sun_len) == -1) {
                   1090:                control_fd = -1;
1.238     djm      1091:                if (errno == EINVAL || errno == EADDRINUSE)
1.214     djm      1092:                        fatal("ControlSocket %s already exists",
                   1093:                            options.control_path);
                   1094:                else
                   1095:                        fatal("%s bind(): %s\n", __func__, strerror(errno));
                   1096:        }
                   1097:        umask(old_umask);
1.80      markus   1098:
1.214     djm      1099:        if (listen(control_fd, 64) == -1)
                   1100:                fatal("%s listen(): %s\n", __func__, strerror(errno));
1.31      markus   1101:
1.214     djm      1102:        set_nonblock(control_fd);
                   1103: }
1.45      markus   1104:
1.214     djm      1105: /* request pty/x11/agent/tcpfwd/shell for channel */
                   1106: static void
                   1107: ssh_session2_setup(int id, void *arg)
                   1108: {
1.215     djm      1109:        extern char **environ;
                   1110:
1.214     djm      1111:        int interactive = tty_flag;
                   1112:        if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1.150     stevesk  1113:                char *proto, *data;
1.50      markus   1114:                /* Get reasonable local authentication information. */
1.150     stevesk  1115:                x11_get_proto(&proto, &data);
1.50      markus   1116:                /* Request forwarding with authentication spoofing. */
                   1117:                debug("Requesting X11 forwarding with authentication spoofing.");
                   1118:                x11_request_forwarding_with_spoofing(id, proto, data);
1.80      markus   1119:                interactive = 1;
1.50      markus   1120:                /* XXX wait for reply */
                   1121:        }
                   1122:
1.70      markus   1123:        check_agent_present();
                   1124:        if (options.forward_agent) {
                   1125:                debug("Requesting authentication agent forwarding.");
                   1126:                channel_request_start(id, "auth-agent-req@openssh.com", 0);
                   1127:                packet_send();
1.212     djm      1128:        }
                   1129:
1.214     djm      1130:        client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1.215     djm      1131:            NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1.90      markus   1132:
1.80      markus   1133:        packet_set_interactive(interactive);
1.45      markus   1134: }
                   1135:
1.143     markus   1136: /* open new channel for a session */
1.126     itojun   1137: static int
1.143     markus   1138: ssh_session2_open(void)
1.45      markus   1139: {
1.118     markus   1140:        Channel *c;
                   1141:        int window, packetmax, in, out, err;
1.60      markus   1142:
1.62      markus   1143:        if (stdin_null_flag) {
1.93      itojun   1144:                in = open(_PATH_DEVNULL, O_RDONLY);
1.62      markus   1145:        } else {
                   1146:                in = dup(STDIN_FILENO);
                   1147:        }
1.60      markus   1148:        out = dup(STDOUT_FILENO);
                   1149:        err = dup(STDERR_FILENO);
1.45      markus   1150:
                   1151:        if (in < 0 || out < 0 || err < 0)
1.62      markus   1152:                fatal("dup() in/out/err failed");
1.45      markus   1153:
1.69      markus   1154:        /* enable nonblocking unless tty */
                   1155:        if (!isatty(in))
                   1156:                set_nonblock(in);
                   1157:        if (!isatty(out))
                   1158:                set_nonblock(out);
                   1159:        if (!isatty(err))
                   1160:                set_nonblock(err);
                   1161:
1.65      markus   1162:        window = CHAN_SES_WINDOW_DEFAULT;
                   1163:        packetmax = CHAN_SES_PACKET_DEFAULT;
1.164     markus   1164:        if (tty_flag) {
                   1165:                window >>= 1;
                   1166:                packetmax >>= 1;
1.45      markus   1167:        }
1.118     markus   1168:        c = channel_new(
1.45      markus   1169:            "session", SSH_CHANNEL_OPENING, in, out, err,
1.65      markus   1170:            window, packetmax, CHAN_EXTENDED_WRITE,
1.192     markus   1171:            "client-session", /*nonblock*/0);
1.45      markus   1172:
1.143     markus   1173:        debug3("ssh_session2_open: channel_new: %d", c->self);
1.106     markus   1174:
1.122     markus   1175:        channel_send_open(c->self);
1.143     markus   1176:        if (!no_shell_flag)
1.214     djm      1177:                channel_register_confirm(c->self, ssh_session2_setup, NULL);
1.106     markus   1178:
1.118     markus   1179:        return c->self;
1.106     markus   1180: }
                   1181:
1.126     itojun   1182: static int
1.106     markus   1183: ssh_session2(void)
                   1184: {
1.143     markus   1185:        int id = -1;
1.106     markus   1186:
                   1187:        /* XXX should be pre-session */
                   1188:        ssh_init_forwarding();
1.214     djm      1189:        ssh_control_listener();
1.106     markus   1190:
1.143     markus   1191:        if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
                   1192:                id = ssh_session2_open();
1.106     markus   1193:
                   1194:        /* If requested, let ssh continue in the background. */
                   1195:        if (fork_after_authentication_flag)
                   1196:                if (daemon(1, 1) < 0)
                   1197:                        fatal("daemon() failed: %.200s", strerror(errno));
1.31      markus   1198:
1.119     stevesk  1199:        return client_loop(tty_flag, tty_flag ?
                   1200:            options.escape_char : SSH_ESCAPECHAR_NONE, id);
1.72      markus   1201: }
                   1202:
1.126     itojun   1203: static void
1.104     markus   1204: load_public_identity_files(void)
                   1205: {
                   1206:        char *filename;
1.167     markus   1207:        int i = 0;
1.104     markus   1208:        Key *public;
1.167     markus   1209: #ifdef SMARTCARD
                   1210:        Key **keys;
1.104     markus   1211:
1.133     markus   1212:        if (options.smartcard_device != NULL &&
1.167     markus   1213:            options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
                   1214:            (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
                   1215:                int count = 0;
                   1216:                for (i = 0; keys[i] != NULL; i++) {
                   1217:                        count++;
                   1218:                        memmove(&options.identity_files[1], &options.identity_files[0],
                   1219:                            sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
                   1220:                        memmove(&options.identity_keys[1], &options.identity_keys[0],
                   1221:                            sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
                   1222:                        options.num_identity_files++;
                   1223:                        options.identity_keys[0] = keys[i];
1.194     markus   1224:                        options.identity_files[0] = sc_get_key_label(keys[i]);
1.167     markus   1225:                }
1.168     markus   1226:                if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
                   1227:                        options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1.167     markus   1228:                i = count;
                   1229:                xfree(keys);
1.127     markus   1230:        }
1.136     jakob    1231: #endif /* SMARTCARD */
1.131     millert  1232:        for (; i < options.num_identity_files; i++) {
                   1233:                filename = tilde_expand_filename(options.identity_files[i],
                   1234:                    original_real_uid);
                   1235:                public = key_load_public(filename, NULL);
                   1236:                debug("identity file %s type %d", filename,
                   1237:                    public ? public->type : -1);
                   1238:                xfree(options.identity_files[i]);
                   1239:                options.identity_files[i] = filename;
                   1240:                options.identity_keys[i] = public;
                   1241:        }
1.214     djm      1242: }
                   1243:
                   1244: static void
                   1245: control_client_sighandler(int signo)
                   1246: {
                   1247:        control_client_terminate = signo;
                   1248: }
                   1249:
                   1250: static void
                   1251: control_client_sigrelay(int signo)
                   1252: {
                   1253:        if (control_server_pid > 1)
                   1254:                kill(control_server_pid, signo);
                   1255: }
                   1256:
1.220     djm      1257: static int
                   1258: env_permitted(char *env)
                   1259: {
                   1260:        int i;
                   1261:        char name[1024], *cp;
                   1262:
                   1263:        strlcpy(name, env, sizeof(name));
                   1264:        if ((cp = strchr(name, '=')) == NULL)
                   1265:                return (0);
                   1266:
                   1267:        *cp = '\0';
                   1268:
                   1269:        for (i = 0; i < options.num_send_env; i++)
                   1270:                if (match_pattern(name, options.send_env[i]))
                   1271:                        return (1);
                   1272:
                   1273:        return (0);
                   1274: }
                   1275:
1.214     djm      1276: static void
                   1277: control_client(const char *path)
                   1278: {
                   1279:        struct sockaddr_un addr;
1.228     djm      1280:        int i, r, fd, sock, exitval, num_env;
1.214     djm      1281:        Buffer m;
1.229     djm      1282:        char *term;
1.215     djm      1283:        extern char **environ;
1.229     djm      1284:        u_int  flags;
1.228     djm      1285:
1.214     djm      1286:        memset(&addr, '\0', sizeof(addr));
                   1287:        addr.sun_family = AF_UNIX;
                   1288:        addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
                   1289:            strlen(path) + 1;
                   1290:
                   1291:        if (strlcpy(addr.sun_path, path,
                   1292:            sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
                   1293:                fatal("ControlPath too long");
                   1294:
                   1295:        if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
                   1296:                fatal("%s socket(): %s", __func__, strerror(errno));
                   1297:
1.237     jakob    1298:        if (connect(sock, (struct sockaddr*)&addr, addr.sun_len) == -1) {
1.240   ! djm      1299:                if (mux_command != SSHMUX_COMMAND_OPEN) {
        !          1300:                        fatal("Control socket connect(%.100s): %s", path,
        !          1301:                            strerror(errno));
        !          1302:                }
1.239     djm      1303:                if (errno == ENOENT)
                   1304:                        debug("Control socket \"%.100s\" does not exist", path);
                   1305:                else {
                   1306:                        error("Control socket connect(%.100s): %s", path,
                   1307:                            strerror(errno));
                   1308:                }
1.237     jakob    1309:                close(sock);
                   1310:                return;
                   1311:        }
                   1312:
                   1313:        if (stdin_null_flag) {
                   1314:                if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
                   1315:                        fatal("open(/dev/null): %s", strerror(errno));
                   1316:                if (dup2(fd, STDIN_FILENO) == -1)
                   1317:                        fatal("dup2: %s", strerror(errno));
                   1318:                if (fd > STDERR_FILENO)
                   1319:                        close(fd);
                   1320:        }
                   1321:
1.229     djm      1322:        if ((term = getenv("TERM")) == NULL)
                   1323:                term = "";
                   1324:
                   1325:        flags = 0;
                   1326:        if (tty_flag)
                   1327:                flags |= SSHMUX_FLAG_TTY;
                   1328:        if (subsystem_flag)
                   1329:                flags |= SSHMUX_FLAG_SUBSYS;
1.214     djm      1330:
                   1331:        buffer_init(&m);
                   1332:
1.229     djm      1333:        /* Send our command to server */
                   1334:        buffer_put_int(&m, mux_command);
                   1335:        buffer_put_int(&m, flags);
                   1336:        if (ssh_msg_send(sock, /* version */1, &m) == -1)
                   1337:                fatal("%s: msg_send", __func__);
                   1338:        buffer_clear(&m);
                   1339:
                   1340:        /* Get authorisation status and PID of controlee */
1.214     djm      1341:        if (ssh_msg_recv(sock, &m) == -1)
                   1342:                fatal("%s: msg_recv", __func__);
1.229     djm      1343:        if (buffer_get_char(&m) != 1)
1.214     djm      1344:                fatal("%s: wrong version", __func__);
1.216     djm      1345:        if (buffer_get_int(&m) != 1)
                   1346:                fatal("Connection to master denied");
1.214     djm      1347:        control_server_pid = buffer_get_int(&m);
                   1348:
                   1349:        buffer_clear(&m);
                   1350:
1.229     djm      1351:        switch (mux_command) {
                   1352:        case SSHMUX_COMMAND_ALIVE_CHECK:
1.234     deraadt  1353:                fprintf(stderr, "Master running (pid=%d)\r\n",
1.229     djm      1354:                    control_server_pid);
                   1355:                exit(0);
                   1356:        case SSHMUX_COMMAND_TERMINATE:
                   1357:                fprintf(stderr, "Exit request sent.\r\n");
                   1358:                exit(0);
                   1359:        case SSHMUX_COMMAND_OPEN:
                   1360:                /* continue below */
                   1361:                break;
                   1362:        default:
                   1363:                fatal("silly mux_command %d", mux_command);
                   1364:        }
                   1365:
                   1366:        /* SSHMUX_COMMAND_OPEN */
                   1367:        buffer_put_cstring(&m, term);
1.214     djm      1368:        buffer_append(&command, "\0", 1);
                   1369:        buffer_put_cstring(&m, buffer_ptr(&command));
1.215     djm      1370:
1.220     djm      1371:        if (options.num_send_env == 0 || environ == NULL) {
                   1372:                buffer_put_int(&m, 0);
1.223     deraadt  1373:        } else {
1.220     djm      1374:                /* Pass environment */
                   1375:                num_env = 0;
                   1376:                for (i = 0; environ[i] != NULL; i++)
                   1377:                        if (env_permitted(environ[i]))
                   1378:                                num_env++; /* Count */
1.223     deraadt  1379:
1.220     djm      1380:                buffer_put_int(&m, num_env);
                   1381:
1.222     dtucker  1382:                for (i = 0; environ[i] != NULL && num_env >= 0; i++)
                   1383:                        if (env_permitted(environ[i])) {
                   1384:                                num_env--;
1.220     djm      1385:                                buffer_put_cstring(&m, environ[i]);
1.222     dtucker  1386:                        }
1.220     djm      1387:        }
1.214     djm      1388:
1.229     djm      1389:        if (ssh_msg_send(sock, /* version */1, &m) == -1)
1.214     djm      1390:                fatal("%s: msg_send", __func__);
                   1391:
                   1392:        mm_send_fd(sock, STDIN_FILENO);
                   1393:        mm_send_fd(sock, STDOUT_FILENO);
                   1394:        mm_send_fd(sock, STDERR_FILENO);
                   1395:
                   1396:        /* Wait for reply, so master has a chance to gather ttymodes */
                   1397:        buffer_clear(&m);
                   1398:        if (ssh_msg_recv(sock, &m) == -1)
                   1399:                fatal("%s: msg_recv", __func__);
1.229     djm      1400:        if (buffer_get_char(&m) != 1)
                   1401:                fatal("%s: wrong version", __func__);
1.214     djm      1402:        buffer_free(&m);
1.218     djm      1403:
1.226     djm      1404:        signal(SIGHUP, control_client_sighandler);
1.218     djm      1405:        signal(SIGINT, control_client_sighandler);
                   1406:        signal(SIGTERM, control_client_sighandler);
                   1407:        signal(SIGWINCH, control_client_sigrelay);
1.214     djm      1408:
                   1409:        if (tty_flag)
                   1410:                enter_raw_mode();
                   1411:
                   1412:        /* Stick around until the controlee closes the client_fd */
                   1413:        exitval = 0;
                   1414:        for (;!control_client_terminate;) {
                   1415:                r = read(sock, &exitval, sizeof(exitval));
                   1416:                if (r == 0) {
                   1417:                        debug2("Received EOF from master");
                   1418:                        break;
                   1419:                }
                   1420:                if (r > 0)
                   1421:                        debug2("Received exit status from master %d", exitval);
                   1422:                if (r == -1 && errno != EINTR)
                   1423:                        fatal("%s: read %s", __func__, strerror(errno));
                   1424:        }
                   1425:
                   1426:        if (control_client_terminate)
                   1427:                debug2("Exiting on signal %d", control_client_terminate);
                   1428:
                   1429:        close(sock);
                   1430:
                   1431:        leave_raw_mode();
                   1432:
                   1433:        if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
                   1434:                fprintf(stderr, "Connection to master closed.\r\n");
                   1435:
                   1436:        exit(exitval);
1.1       deraadt  1437: }