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

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