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

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