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

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