[BACK]Return to sshd.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sshd.c, Revision 1.114

1.86      markus      1: /*
1.65      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:  * Created: Fri Mar 17 17:09:28 1995 ylo
                      6:  * This program is the ssh daemon.  It listens for connections from clients, and
                      7:  * performs authentication, executes use commands or shell, and forwards
                      8:  * information to/from the application to the user client over an encrypted
                      9:  * connection.  This can also handle forwarding of X11, TCP/IP, and authentication
                     10:  * agent connections.
1.98      markus     11:  *
                     12:  * SSH2 implementation,
                     13:  * Copyright (c) 2000 Markus Friedl. All rights reserved.
1.65      deraadt    14:  */
1.1       deraadt    15:
                     16: #include "includes.h"
1.114   ! markus     17: RCSID("$OpenBSD: sshd.c,v 1.113 2000/05/01 20:34:51 markus Exp $");
1.1       deraadt    18:
                     19: #include "xmalloc.h"
                     20: #include "rsa.h"
                     21: #include "ssh.h"
                     22: #include "pty.h"
                     23: #include "packet.h"
                     24: #include "cipher.h"
                     25: #include "mpaux.h"
                     26: #include "servconf.h"
                     27: #include "uidswap.h"
1.33      markus     28: #include "compat.h"
1.96      markus     29: #include "buffer.h"
                     30:
1.98      markus     31: #include "ssh2.h"
1.104     markus     32: #include <openssl/dh.h>
                     33: #include <openssl/bn.h>
                     34: #include <openssl/hmac.h>
1.98      markus     35: #include "kex.h"
1.104     markus     36: #include <openssl/dsa.h>
                     37: #include <openssl/rsa.h>
1.96      markus     38: #include "key.h"
1.98      markus     39: #include "dsa.h"
1.96      markus     40:
                     41: #include "auth.h"
1.98      markus     42: #include "myproposal.h"
1.108     markus     43: #include "authfile.h"
1.1       deraadt    44:
                     45: #ifdef LIBWRAP
                     46: #include <tcpd.h>
                     47: #include <syslog.h>
                     48: int allow_severity = LOG_INFO;
                     49: int deny_severity = LOG_WARNING;
                     50: #endif /* LIBWRAP */
                     51:
                     52: #ifndef O_NOCTTY
                     53: #define O_NOCTTY       0
                     54: #endif
                     55:
                     56: /* Server configuration options. */
                     57: ServerOptions options;
                     58:
                     59: /* Name of the server configuration file. */
                     60: char *config_file_name = SERVER_CONFIG_FILE;
                     61:
1.105     markus     62: /*
1.75      markus     63:  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
                     64:  * Default value is AF_UNSPEC means both IPv4 and IPv6.
                     65:  */
                     66: int IPv4or6 = AF_UNSPEC;
                     67:
1.65      deraadt    68: /*
                     69:  * Debug mode flag.  This can be set on the command line.  If debug
                     70:  * mode is enabled, extra debugging output will be sent to the system
                     71:  * log, the daemon will not go to background, and will exit after processing
                     72:  * the first connection.
                     73:  */
1.1       deraadt    74: int debug_flag = 0;
                     75:
                     76: /* Flag indicating that the daemon is being started from inetd. */
                     77: int inetd_flag = 0;
                     78:
1.47      markus     79: /* debug goes to stderr unless inetd_flag is set */
                     80: int log_stderr = 0;
                     81:
1.1       deraadt    82: /* argv[0] without path. */
                     83: char *av0;
                     84:
                     85: /* Saved arguments to main(). */
                     86: char **saved_argv;
                     87:
1.66      markus     88: /*
1.75      markus     89:  * The sockets that the server is listening; this is used in the SIGHUP
                     90:  * signal handler.
1.66      markus     91:  */
1.75      markus     92: #define        MAX_LISTEN_SOCKS        16
                     93: int listen_socks[MAX_LISTEN_SOCKS];
                     94: int num_listen_socks = 0;
1.1       deraadt    95:
1.66      markus     96: /*
                     97:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                     98:  * sshd will skip the version-number exchange
                     99:  */
1.61      markus    100: char *client_version_string = NULL;
1.96      markus    101: char *server_version_string = NULL;
1.1       deraadt   102:
1.66      markus    103: /*
                    104:  * Any really sensitive data in the application is contained in this
                    105:  * structure. The idea is that this structure could be locked into memory so
                    106:  * that the pages do not get written into swap.  However, there are some
                    107:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    108:  * have access to the internals of them, and locking just the structure is
                    109:  * not very useful.  Currently, memory locking is not implemented.
                    110:  */
1.64      markus    111: struct {
1.108     markus    112:        RSA *private_key;        /* Private part of empheral server key. */
1.64      markus    113:        RSA *host_key;           /* Private part of host key. */
1.108     markus    114:        Key *dsa_host_key;       /* Private DSA host key. */
1.1       deraadt   115: } sensitive_data;
                    116:
1.66      markus    117: /*
                    118:  * Flag indicating whether the current session key has been used.  This flag
                    119:  * is set whenever the key is used, and cleared when the key is regenerated.
                    120:  */
1.1       deraadt   121: int key_used = 0;
                    122:
                    123: /* This is set to true when SIGHUP is received. */
                    124: int received_sighup = 0;
                    125:
                    126: /* Public side of the server key.  This value is regenerated regularly with
                    127:    the private key. */
1.2       provos    128: RSA *public_key;
1.1       deraadt   129:
1.96      markus    130: /* session identifier, used by RSA-auth */
                    131: unsigned char session_id[16];
                    132:
1.108     markus    133: /* same for ssh2 */
                    134: unsigned char *session_id2 = NULL;
                    135: int session_id2_len = 0;
                    136:
1.1       deraadt   137: /* Prototypes for various functions defined later in this file. */
1.96      markus    138: void do_ssh1_kex();
1.98      markus    139: void do_ssh2_kex();
1.87      markus    140:
                    141: /*
1.75      markus    142:  * Close all listening sockets
                    143:  */
                    144: void
                    145: close_listen_socks(void)
                    146: {
                    147:        int i;
                    148:        for (i = 0; i < num_listen_socks; i++)
                    149:                close(listen_socks[i]);
                    150:        num_listen_socks = -1;
                    151: }
                    152:
                    153: /*
1.65      deraadt   154:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    155:  * the effect is to reread the configuration file (and to regenerate
                    156:  * the server key).
                    157:  */
1.105     markus    158: void
1.64      markus    159: sighup_handler(int sig)
1.1       deraadt   160: {
1.64      markus    161:        received_sighup = 1;
                    162:        signal(SIGHUP, sighup_handler);
1.1       deraadt   163: }
                    164:
1.65      deraadt   165: /*
                    166:  * Called from the main program after receiving SIGHUP.
                    167:  * Restarts the server.
                    168:  */
1.105     markus    169: void
1.64      markus    170: sighup_restart()
1.1       deraadt   171: {
1.64      markus    172:        log("Received SIGHUP; restarting.");
1.75      markus    173:        close_listen_socks();
1.64      markus    174:        execv(saved_argv[0], saved_argv);
                    175:        log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
                    176:        exit(1);
1.1       deraadt   177: }
                    178:
1.65      deraadt   179: /*
                    180:  * Generic signal handler for terminating signals in the master daemon.
                    181:  * These close the listen socket; not closing it seems to cause "Address
                    182:  * already in use" problems on some machines, which is inconvenient.
                    183:  */
1.105     markus    184: void
1.64      markus    185: sigterm_handler(int sig)
1.1       deraadt   186: {
1.64      markus    187:        log("Received signal %d; terminating.", sig);
1.75      markus    188:        close_listen_socks();
1.113     markus    189:        unlink(options.pid_file);
1.64      markus    190:        exit(255);
1.1       deraadt   191: }
                    192:
1.65      deraadt   193: /*
                    194:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
                    195:  * reap any zombies left by exited c.
                    196:  */
1.105     markus    197: void
1.64      markus    198: main_sigchld_handler(int sig)
1.1       deraadt   199: {
1.64      markus    200:        int save_errno = errno;
                    201:        int status;
1.60      deraadt   202:
1.64      markus    203:        while (waitpid(-1, &status, WNOHANG) > 0)
                    204:                ;
1.60      deraadt   205:
1.64      markus    206:        signal(SIGCHLD, main_sigchld_handler);
                    207:        errno = save_errno;
1.1       deraadt   208: }
                    209:
1.65      deraadt   210: /*
                    211:  * Signal handler for the alarm after the login grace period has expired.
                    212:  */
1.105     markus    213: void
1.64      markus    214: grace_alarm_handler(int sig)
1.1       deraadt   215: {
1.64      markus    216:        /* Close the connection. */
                    217:        packet_close();
                    218:
                    219:        /* Log error and exit. */
                    220:        fatal("Timeout before authentication for %s.", get_remote_ipaddr());
1.62      markus    221: }
                    222:
1.65      deraadt   223: /*
                    224:  * Signal handler for the key regeneration alarm.  Note that this
                    225:  * alarm only occurs in the daemon waiting for connections, and it does not
                    226:  * do anything with the private key or random state before forking.
                    227:  * Thus there should be no concurrency control/asynchronous execution
                    228:  * problems.
                    229:  */
1.108     markus    230: /* XXX do we really want this work to be done in a signal handler ? -m */
1.105     markus    231: void
1.64      markus    232: key_regeneration_alarm(int sig)
1.1       deraadt   233: {
1.64      markus    234:        int save_errno = errno;
1.18      deraadt   235:
1.64      markus    236:        /* Check if we should generate a new key. */
                    237:        if (key_used) {
                    238:                /* This should really be done in the background. */
                    239:                log("Generating new %d bit RSA key.", options.server_key_bits);
                    240:
                    241:                if (sensitive_data.private_key != NULL)
                    242:                        RSA_free(sensitive_data.private_key);
                    243:                sensitive_data.private_key = RSA_new();
                    244:
                    245:                if (public_key != NULL)
                    246:                        RSA_free(public_key);
                    247:                public_key = RSA_new();
                    248:
                    249:                rsa_generate_key(sensitive_data.private_key, public_key,
                    250:                                 options.server_key_bits);
                    251:                arc4random_stir();
                    252:                key_used = 0;
                    253:                log("RSA key generation complete.");
                    254:        }
                    255:        /* Reschedule the alarm. */
                    256:        signal(SIGALRM, key_regeneration_alarm);
                    257:        alarm(options.key_regeneration_time);
                    258:        errno = save_errno;
1.1       deraadt   259: }
                    260:
1.98      markus    261: char *
                    262: chop(char *s)
                    263: {
1.105     markus    264:        char *t = s;
                    265:        while (*t) {
                    266:                if(*t == '\n' || *t == '\r') {
                    267:                        *t = '\0';
                    268:                        return s;
                    269:                }
                    270:                t++;
                    271:        }
                    272:        return s;
1.98      markus    273:
                    274: }
                    275:
1.96      markus    276: void
                    277: sshd_exchange_identification(int sock_in, int sock_out)
                    278: {
1.102     markus    279:        int i, mismatch;
1.96      markus    280:        int remote_major, remote_minor;
1.102     markus    281:        int major, minor;
1.96      markus    282:        char *s;
                    283:        char buf[256];                  /* Must not be larger than remote_version. */
                    284:        char remote_version[256];       /* Must be at least as big as buf. */
                    285:
1.103     markus    286:        if ((options.protocol & SSH_PROTO_1) &&
                    287:            (options.protocol & SSH_PROTO_2)) {
1.102     markus    288:                major = PROTOCOL_MAJOR_1;
                    289:                minor = 99;
                    290:        } else if (options.protocol & SSH_PROTO_2) {
                    291:                major = PROTOCOL_MAJOR_2;
                    292:                minor = PROTOCOL_MINOR_2;
                    293:        } else {
                    294:                major = PROTOCOL_MAJOR_1;
                    295:                minor = PROTOCOL_MINOR_1;
                    296:        }
                    297:        snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96      markus    298:        server_version_string = xstrdup(buf);
                    299:
                    300:        if (client_version_string == NULL) {
                    301:                /* Send our protocol version identification. */
                    302:                if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
                    303:                    != strlen(server_version_string)) {
                    304:                        log("Could not write ident string to %s.", get_remote_ipaddr());
                    305:                        fatal_cleanup();
                    306:                }
                    307:
                    308:                /* Read other side\'s version identification. */
                    309:                for (i = 0; i < sizeof(buf) - 1; i++) {
                    310:                        if (read(sock_in, &buf[i], 1) != 1) {
                    311:                                log("Did not receive ident string from %s.", get_remote_ipaddr());
                    312:                                fatal_cleanup();
                    313:                        }
                    314:                        if (buf[i] == '\r') {
                    315:                                buf[i] = '\n';
                    316:                                buf[i + 1] = 0;
                    317:                                continue;
                    318:                        }
                    319:                        if (buf[i] == '\n') {
                    320:                                /* buf[i] == '\n' */
                    321:                                buf[i + 1] = 0;
                    322:                                break;
                    323:                        }
                    324:                }
                    325:                buf[sizeof(buf) - 1] = 0;
                    326:                client_version_string = xstrdup(buf);
                    327:        }
                    328:
                    329:        /*
                    330:         * Check that the versions match.  In future this might accept
                    331:         * several versions and set appropriate flags to handle them.
                    332:         */
                    333:        if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
                    334:            &remote_major, &remote_minor, remote_version) != 3) {
1.105     markus    335:                s = "Protocol mismatch.\n";
1.96      markus    336:                (void) atomicio(write, sock_out, s, strlen(s));
                    337:                close(sock_in);
                    338:                close(sock_out);
                    339:                log("Bad protocol version identification '%.100s' from %s",
                    340:                    client_version_string, get_remote_ipaddr());
                    341:                fatal_cleanup();
                    342:        }
                    343:        debug("Client protocol version %d.%d; client software version %.100s",
                    344:              remote_major, remote_minor, remote_version);
                    345:
1.98      markus    346:        compat_datafellows(remote_version);
                    347:
1.102     markus    348:        mismatch = 0;
1.96      markus    349:        switch(remote_major) {
                    350:        case 1:
1.108     markus    351:                if (remote_minor == 99) {
                    352:                        if (options.protocol & SSH_PROTO_2)
                    353:                                enable_compat20();
                    354:                        else
                    355:                                mismatch = 1;
                    356:                        break;
                    357:                }
1.102     markus    358:                if (!(options.protocol & SSH_PROTO_1)) {
                    359:                        mismatch = 1;
                    360:                        break;
                    361:                }
1.96      markus    362:                if (remote_minor < 3) {
                    363:                        packet_disconnect("Your ssh version is too old and"
                    364:                            "is no longer supported.  Please install a newer version.");
                    365:                } else if (remote_minor == 3) {
                    366:                        /* note that this disables agent-forwarding */
                    367:                        enable_compat13();
                    368:                }
1.102     markus    369:                break;
1.98      markus    370:        case 2:
1.102     markus    371:                if (options.protocol & SSH_PROTO_2) {
1.98      markus    372:                        enable_compat20();
                    373:                        break;
                    374:                }
1.99      markus    375:                /* FALLTHROUGH */
1.105     markus    376:        default:
1.102     markus    377:                mismatch = 1;
                    378:                break;
                    379:        }
                    380:        chop(server_version_string);
                    381:        chop(client_version_string);
                    382:        debug("Local version string %.200s", server_version_string);
                    383:
                    384:        if (mismatch) {
1.96      markus    385:                s = "Protocol major versions differ.\n";
                    386:                (void) atomicio(write, sock_out, s, strlen(s));
                    387:                close(sock_in);
                    388:                close(sock_out);
1.102     markus    389:                log("Protocol major versions differ for %s: %.200s vs. %.200s",
                    390:                    get_remote_ipaddr(),
                    391:                    server_version_string, client_version_string);
1.96      markus    392:                fatal_cleanup();
                    393:        }
1.108     markus    394:        if (compat20)
                    395:                packet_set_ssh2_format();
                    396: }
                    397:
                    398:
                    399: void
                    400: destroy_sensitive_data(void)
                    401: {
                    402:        /* Destroy the private and public keys.  They will no longer be needed. */
                    403:        RSA_free(public_key);
                    404:        RSA_free(sensitive_data.private_key);
                    405:        RSA_free(sensitive_data.host_key);
                    406:        if (sensitive_data.dsa_host_key != NULL)
                    407:                key_free(sensitive_data.dsa_host_key);
1.96      markus    408: }
                    409:
1.65      deraadt   410: /*
                    411:  * Main program for the daemon.
                    412:  */
1.2       provos    413: int
                    414: main(int ac, char **av)
1.1       deraadt   415: {
1.64      markus    416:        extern char *optarg;
                    417:        extern int optind;
1.107     deraadt   418:        int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, on = 1;
                    419:        pid_t pid;
1.75      markus    420:        socklen_t fromlen;
1.110     markus    421:        int silent = 0;
1.75      markus    422:        fd_set *fdset;
                    423:        struct sockaddr_storage from;
1.64      markus    424:        const char *remote_ip;
                    425:        int remote_port;
                    426:        FILE *f;
                    427:        struct linger linger;
1.75      markus    428:        struct addrinfo *ai;
                    429:        char ntop[NI_MAXHOST], strport[NI_MAXSERV];
                    430:        int listen_sock, maxfd;
1.64      markus    431:
                    432:        /* Save argv[0]. */
                    433:        saved_argv = av;
                    434:        if (strchr(av[0], '/'))
                    435:                av0 = strrchr(av[0], '/') + 1;
                    436:        else
                    437:                av0 = av[0];
                    438:
                    439:        /* Initialize configuration options to their default values. */
                    440:        initialize_server_options(&options);
                    441:
                    442:        /* Parse command-line arguments. */
1.102     markus    443:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
1.64      markus    444:                switch (opt) {
1.75      markus    445:                case '4':
                    446:                        IPv4or6 = AF_INET;
                    447:                        break;
                    448:                case '6':
                    449:                        IPv4or6 = AF_INET6;
                    450:                        break;
1.64      markus    451:                case 'f':
                    452:                        config_file_name = optarg;
                    453:                        break;
                    454:                case 'd':
                    455:                        debug_flag = 1;
                    456:                        options.log_level = SYSLOG_LEVEL_DEBUG;
                    457:                        break;
                    458:                case 'i':
                    459:                        inetd_flag = 1;
                    460:                        break;
                    461:                case 'Q':
1.110     markus    462:                        silent = 1;
1.64      markus    463:                        break;
                    464:                case 'q':
                    465:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    466:                        break;
                    467:                case 'b':
                    468:                        options.server_key_bits = atoi(optarg);
                    469:                        break;
                    470:                case 'p':
1.75      markus    471:                        options.ports_from_cmdline = 1;
                    472:                        if (options.num_ports >= MAX_PORTS)
                    473:                                fatal("too many ports.\n");
                    474:                        options.ports[options.num_ports++] = atoi(optarg);
1.64      markus    475:                        break;
                    476:                case 'g':
                    477:                        options.login_grace_time = atoi(optarg);
                    478:                        break;
                    479:                case 'k':
                    480:                        options.key_regeneration_time = atoi(optarg);
                    481:                        break;
                    482:                case 'h':
                    483:                        options.host_key_file = optarg;
                    484:                        break;
                    485:                case 'V':
                    486:                        client_version_string = optarg;
                    487:                        /* only makes sense with inetd_flag, i.e. no listen() */
                    488:                        inetd_flag = 1;
                    489:                        break;
                    490:                case '?':
                    491:                default:
                    492:                        fprintf(stderr, "sshd version %s\n", SSH_VERSION);
                    493:                        fprintf(stderr, "Usage: %s [options]\n", av0);
                    494:                        fprintf(stderr, "Options:\n");
1.66      markus    495:                        fprintf(stderr, "  -f file    Configuration file (default %s)\n", SERVER_CONFIG_FILE);
1.64      markus    496:                        fprintf(stderr, "  -d         Debugging mode\n");
                    497:                        fprintf(stderr, "  -i         Started from inetd\n");
                    498:                        fprintf(stderr, "  -q         Quiet (no logging)\n");
                    499:                        fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
                    500:                        fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
                    501:                        fprintf(stderr, "  -g seconds Grace period for authentication (default: 300)\n");
                    502:                        fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
                    503:                        fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
1.75      markus    504:                            HOST_KEY_FILE);
                    505:                        fprintf(stderr, "  -4         Use IPv4 only\n");
                    506:                        fprintf(stderr, "  -6         Use IPv6 only\n");
1.64      markus    507:                        exit(1);
                    508:                }
                    509:        }
                    510:
1.75      markus    511:        /*
                    512:         * Force logging to stderr until we have loaded the private host
                    513:         * key (unless started from inetd)
                    514:         */
                    515:        log_init(av0,
                    516:            options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
                    517:            options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
1.110     markus    518:            !silent && !inetd_flag);
1.75      markus    519:
1.64      markus    520:        /* Read server configuration options from the configuration file. */
                    521:        read_server_config(&options, config_file_name);
                    522:
                    523:        /* Fill in default values for those options not explicitly set. */
                    524:        fill_default_server_options(&options);
                    525:
                    526:        /* Check that there are no remaining arguments. */
                    527:        if (optind < ac) {
                    528:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                    529:                exit(1);
                    530:        }
                    531:
                    532:        debug("sshd version %.100s", SSH_VERSION);
                    533:
1.108     markus    534:        sensitive_data.dsa_host_key = NULL;
                    535:        sensitive_data.host_key = NULL;
                    536:
                    537:        /* check if RSA support exists */
                    538:        if ((options.protocol & SSH_PROTO_1) &&
                    539:            rsa_alive() == 0) {
                    540:                log("no RSA support in libssl and libcrypto.  See ssl(8)");
                    541:                log("Disabling protocol version 1");
                    542:                options.protocol &= ~SSH_PROTO_1;
                    543:        }
                    544:        /* Load the RSA/DSA host key.  It must have empty passphrase. */
                    545:        if (options.protocol & SSH_PROTO_1) {
                    546:                Key k;
                    547:                sensitive_data.host_key = RSA_new();
                    548:                k.type = KEY_RSA;
                    549:                k.rsa = sensitive_data.host_key;
                    550:                errno = 0;
1.109     markus    551:                if (!load_private_key(options.host_key_file, "", &k, NULL)) {
1.108     markus    552:                        error("Could not load host key: %.200s: %.100s",
                    553:                            options.host_key_file, strerror(errno));
                    554:                        log("Disabling protocol version 1");
                    555:                        options.protocol &= ~SSH_PROTO_1;
                    556:                }
                    557:                k.rsa = NULL;
                    558:        }
                    559:        if (options.protocol & SSH_PROTO_2) {
                    560:                sensitive_data.dsa_host_key = key_new(KEY_DSA);
                    561:                if (!load_private_key(options.dsa_key_file, "", sensitive_data.dsa_host_key, NULL)) {
                    562:                        error("Could not load DSA host key: %.200s", options.dsa_key_file);
                    563:                        log("Disabling protocol version 2");
                    564:                        options.protocol &= ~SSH_PROTO_2;
                    565:                }
                    566:        }
                    567:        if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
1.110     markus    568:                if (silent == 0)
                    569:                        fprintf(stderr, "sshd: no hostkeys available -- exiting.\n");
1.108     markus    570:                log("sshd: no hostkeys available -- exiting.\n");
1.64      markus    571:                exit(1);
                    572:        }
                    573:
1.108     markus    574:        /* Check certain values for sanity. */
                    575:        if (options.protocol & SSH_PROTO_1) {
                    576:                if (options.server_key_bits < 512 ||
                    577:                    options.server_key_bits > 32768) {
                    578:                        fprintf(stderr, "Bad server key size.\n");
                    579:                        exit(1);
                    580:                }
                    581:                /*
                    582:                 * Check that server and host key lengths differ sufficiently. This
                    583:                 * is necessary to make double encryption work with rsaref. Oh, I
                    584:                 * hate software patents. I dont know if this can go? Niels
                    585:                 */
                    586:                if (options.server_key_bits >
                    587:                    BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
                    588:                    options.server_key_bits <
                    589:                    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                    590:                        options.server_key_bits =
                    591:                            BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
                    592:                        debug("Forcing server key to %d bits to make it differ from host key.",
                    593:                            options.server_key_bits);
                    594:                }
                    595:        }
                    596:
                    597:        /* Initialize the log (it is reinitialized below in case we forked). */
1.64      markus    598:        if (debug_flag && !inetd_flag)
                    599:                log_stderr = 1;
                    600:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    601:
1.108     markus    602:        /*
                    603:         * If not in debugging mode, and not started from inetd, disconnect
                    604:         * from the controlling terminal, and fork.  The original process
                    605:         * exits.
                    606:         */
1.64      markus    607:        if (!debug_flag && !inetd_flag) {
1.1       deraadt   608: #ifdef TIOCNOTTY
1.64      markus    609:                int fd;
1.1       deraadt   610: #endif /* TIOCNOTTY */
1.64      markus    611:                if (daemon(0, 0) < 0)
                    612:                        fatal("daemon() failed: %.200s", strerror(errno));
                    613:
                    614:                /* Disconnect from the controlling tty. */
1.1       deraadt   615: #ifdef TIOCNOTTY
1.64      markus    616:                fd = open("/dev/tty", O_RDWR | O_NOCTTY);
                    617:                if (fd >= 0) {
                    618:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                    619:                        close(fd);
                    620:                }
                    621: #endif /* TIOCNOTTY */
                    622:        }
                    623:        /* Reinitialize the log (because of the fork above). */
                    624:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    625:
                    626:        /* Do not display messages to stdout in RSA code. */
                    627:        rsa_set_verbose(0);
                    628:
                    629:        /* Initialize the random number generator. */
                    630:        arc4random_stir();
                    631:
                    632:        /* Chdir to the root directory so that the current disk can be
                    633:           unmounted if desired. */
                    634:        chdir("/");
                    635:
                    636:        /* Start listening for a socket, unless started from inetd. */
                    637:        if (inetd_flag) {
                    638:                int s1, s2;
                    639:                s1 = dup(0);    /* Make sure descriptors 0, 1, and 2 are in use. */
                    640:                s2 = dup(s1);
                    641:                sock_in = dup(0);
                    642:                sock_out = dup(1);
1.108     markus    643:                /*
                    644:                 * We intentionally do not close the descriptors 0, 1, and 2
                    645:                 * as our code for setting the descriptors won\'t work if
                    646:                 * ttyfd happens to be one of those.
                    647:                 */
1.64      markus    648:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
                    649:
1.108     markus    650:                if (options.protocol & SSH_PROTO_1) {
                    651:                        public_key = RSA_new();
                    652:                        sensitive_data.private_key = RSA_new();
                    653:                        log("Generating %d bit RSA key.", options.server_key_bits);
                    654:                        rsa_generate_key(sensitive_data.private_key, public_key,
                    655:                            options.server_key_bits);
                    656:                        arc4random_stir();
                    657:                        log("RSA key generation complete.");
                    658:                }
1.64      markus    659:        } else {
1.75      markus    660:                for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
                    661:                        if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
                    662:                                continue;
                    663:                        if (num_listen_socks >= MAX_LISTEN_SOCKS)
                    664:                                fatal("Too many listen sockets. "
                    665:                                    "Enlarge MAX_LISTEN_SOCKS");
                    666:                        if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
                    667:                            ntop, sizeof(ntop), strport, sizeof(strport),
                    668:                            NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
                    669:                                error("getnameinfo failed");
                    670:                                continue;
                    671:                        }
                    672:                        /* Create socket for listening. */
                    673:                        listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
                    674:                        if (listen_sock < 0) {
                    675:                                /* kernel may not support ipv6 */
                    676:                                verbose("socket: %.100s", strerror(errno));
                    677:                                continue;
                    678:                        }
                    679:                        if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
                    680:                                error("listen_sock O_NONBLOCK: %s", strerror(errno));
                    681:                                close(listen_sock);
                    682:                                continue;
                    683:                        }
                    684:                        /*
                    685:                         * Set socket options.  We try to make the port
                    686:                         * reusable and have it close as fast as possible
                    687:                         * without waiting in unnecessary wait states on
                    688:                         * close.
                    689:                         */
                    690:                        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
                    691:                            (void *) &on, sizeof(on));
                    692:                        linger.l_onoff = 1;
                    693:                        linger.l_linger = 5;
                    694:                        setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
                    695:                            (void *) &linger, sizeof(linger));
                    696:
                    697:                        debug("Bind to port %s on %s.", strport, ntop);
                    698:
                    699:                        /* Bind the socket to the desired port. */
                    700:                        if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
                    701:                                error("Bind to port %s on %s failed: %.200s.",
                    702:                                    strport, ntop, strerror(errno));
                    703:                                close(listen_sock);
                    704:                                continue;
                    705:                        }
                    706:                        listen_socks[num_listen_socks] = listen_sock;
                    707:                        num_listen_socks++;
                    708:
                    709:                        /* Start listening on the port. */
                    710:                        log("Server listening on %s port %s.", ntop, strport);
                    711:                        if (listen(listen_sock, 5) < 0)
                    712:                                fatal("listen: %.100s", strerror(errno));
                    713:
1.64      markus    714:                }
1.75      markus    715:                freeaddrinfo(options.listen_addrs);
                    716:
                    717:                if (!num_listen_socks)
                    718:                        fatal("Cannot bind any address.");
                    719:
1.64      markus    720:                if (!debug_flag) {
1.66      markus    721:                        /*
                    722:                         * Record our pid in /etc/sshd_pid to make it easier
                    723:                         * to kill the correct sshd.  We don\'t want to do
                    724:                         * this before the bind above because the bind will
                    725:                         * fail if there already is a daemon, and this will
                    726:                         * overwrite any old pid in the file.
                    727:                         */
1.112     markus    728:                        f = fopen(options.pid_file, "w");
1.64      markus    729:                        if (f) {
                    730:                                fprintf(f, "%u\n", (unsigned int) getpid());
                    731:                                fclose(f);
                    732:                        }
                    733:                }
1.108     markus    734:                if (options.protocol & SSH_PROTO_1) {
                    735:                        public_key = RSA_new();
                    736:                        sensitive_data.private_key = RSA_new();
                    737:
                    738:                        log("Generating %d bit RSA key.", options.server_key_bits);
                    739:                        rsa_generate_key(sensitive_data.private_key, public_key,
                    740:                            options.server_key_bits);
                    741:                        arc4random_stir();
                    742:                        log("RSA key generation complete.");
1.64      markus    743:
1.108     markus    744:                        /* Schedule server key regeneration alarm. */
                    745:                        signal(SIGALRM, key_regeneration_alarm);
                    746:                        alarm(options.key_regeneration_time);
                    747:                }
1.64      markus    748:
                    749:                /* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
                    750:                signal(SIGHUP, sighup_handler);
                    751:                signal(SIGTERM, sigterm_handler);
                    752:                signal(SIGQUIT, sigterm_handler);
                    753:
                    754:                /* Arrange SIGCHLD to be caught. */
                    755:                signal(SIGCHLD, main_sigchld_handler);
                    756:
1.75      markus    757:                /* setup fd set for listen */
                    758:                maxfd = 0;
                    759:                for (i = 0; i < num_listen_socks; i++)
                    760:                        if (listen_socks[i] > maxfd)
                    761:                                maxfd = listen_socks[i];
1.105     markus    762:                fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
                    763:                fdset = (fd_set *)xmalloc(fdsetsz);
1.75      markus    764:
1.66      markus    765:                /*
                    766:                 * Stay listening for connections until the system crashes or
                    767:                 * the daemon is killed with a signal.
                    768:                 */
1.64      markus    769:                for (;;) {
                    770:                        if (received_sighup)
                    771:                                sighup_restart();
1.75      markus    772:                        /* Wait in select until there is a connection. */
                    773:                        memset(fdset, 0, fdsetsz);
                    774:                        for (i = 0; i < num_listen_socks; i++)
                    775:                                FD_SET(listen_socks[i], fdset);
                    776:                        if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
                    777:                                if (errno != EINTR)
                    778:                                        error("select: %.100s", strerror(errno));
                    779:                                continue;
                    780:                        }
                    781:                        for (i = 0; i < num_listen_socks; i++) {
                    782:                                if (!FD_ISSET(listen_socks[i], fdset))
1.70      provos    783:                                        continue;
1.75      markus    784:                        fromlen = sizeof(from);
                    785:                        newsock = accept(listen_socks[i], (struct sockaddr *)&from,
                    786:                            &fromlen);
                    787:                        if (newsock < 0) {
                    788:                                if (errno != EINTR && errno != EWOULDBLOCK)
                    789:                                        error("accept: %.100s", strerror(errno));
                    790:                                continue;
1.70      provos    791:                        }
1.75      markus    792:                        if (fcntl(newsock, F_SETFL, 0) < 0) {
                    793:                                error("newsock del O_NONBLOCK: %s", strerror(errno));
1.64      markus    794:                                continue;
                    795:                        }
1.66      markus    796:                        /*
                    797:                         * Got connection.  Fork a child to handle it, unless
                    798:                         * we are in debugging mode.
                    799:                         */
1.64      markus    800:                        if (debug_flag) {
1.66      markus    801:                                /*
                    802:                                 * In debugging mode.  Close the listening
                    803:                                 * socket, and start processing the
                    804:                                 * connection without forking.
                    805:                                 */
1.64      markus    806:                                debug("Server will not fork when running in debugging mode.");
1.75      markus    807:                                close_listen_socks();
1.64      markus    808:                                sock_in = newsock;
                    809:                                sock_out = newsock;
                    810:                                pid = getpid();
                    811:                                break;
                    812:                        } else {
1.66      markus    813:                                /*
                    814:                                 * Normal production daemon.  Fork, and have
                    815:                                 * the child process the connection. The
                    816:                                 * parent continues listening.
                    817:                                 */
1.64      markus    818:                                if ((pid = fork()) == 0) {
1.66      markus    819:                                        /*
                    820:                                         * Child.  Close the listening socket, and start using the
                    821:                                         * accepted socket.  Reinitialize logging (since our pid has
                    822:                                         * changed).  We break out of the loop to handle the connection.
                    823:                                         */
1.75      markus    824:                                        close_listen_socks();
1.64      markus    825:                                        sock_in = newsock;
                    826:                                        sock_out = newsock;
                    827:                                        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    828:                                        break;
                    829:                                }
                    830:                        }
                    831:
                    832:                        /* Parent.  Stay in the loop. */
                    833:                        if (pid < 0)
                    834:                                error("fork: %.100s", strerror(errno));
                    835:                        else
                    836:                                debug("Forked child %d.", pid);
1.1       deraadt   837:
1.64      markus    838:                        /* Mark that the key has been used (it was "given" to the child). */
                    839:                        key_used = 1;
1.1       deraadt   840:
1.64      markus    841:                        arc4random_stir();
1.1       deraadt   842:
1.64      markus    843:                        /* Close the new socket (the child is now taking care of it). */
                    844:                        close(newsock);
1.75      markus    845:                        } /* for (i = 0; i < num_listen_socks; i++) */
                    846:                        /* child process check (or debug mode) */
                    847:                        if (num_listen_socks < 0)
                    848:                                break;
1.64      markus    849:                }
1.1       deraadt   850:        }
                    851:
1.64      markus    852:        /* This is the child processing a new connection. */
                    853:
1.66      markus    854:        /*
                    855:         * Disable the key regeneration alarm.  We will not regenerate the
                    856:         * key since we are no longer in a position to give it to anyone. We
                    857:         * will not restart on SIGHUP since it no longer makes sense.
                    858:         */
1.64      markus    859:        alarm(0);
                    860:        signal(SIGALRM, SIG_DFL);
                    861:        signal(SIGHUP, SIG_DFL);
                    862:        signal(SIGTERM, SIG_DFL);
                    863:        signal(SIGQUIT, SIG_DFL);
                    864:        signal(SIGCHLD, SIG_DFL);
                    865:
1.66      markus    866:        /*
                    867:         * Set socket options for the connection.  We want the socket to
                    868:         * close as fast as possible without waiting for anything.  If the
                    869:         * connection is not a socket, these will do nothing.
                    870:         */
                    871:        /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64      markus    872:        linger.l_onoff = 1;
                    873:        linger.l_linger = 5;
                    874:        setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
                    875:
1.66      markus    876:        /*
                    877:         * Register our connection.  This turns encryption off because we do
                    878:         * not have a key.
                    879:         */
1.64      markus    880:        packet_set_connection(sock_in, sock_out);
1.1       deraadt   881:
1.64      markus    882:        remote_port = get_remote_port();
                    883:        remote_ip = get_remote_ipaddr();
1.52      markus    884:
1.64      markus    885:        /* Check whether logins are denied from this host. */
1.37      dugsong   886: #ifdef LIBWRAP
1.75      markus    887:        /* XXX LIBWRAP noes not know about IPv6 */
1.64      markus    888:        {
                    889:                struct request_info req;
1.37      dugsong   890:
1.64      markus    891:                request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
                    892:                fromhost(&req);
1.37      dugsong   893:
1.64      markus    894:                if (!hosts_access(&req)) {
                    895:                        close(sock_in);
                    896:                        close(sock_out);
                    897:                        refuse(&req);
                    898:                }
1.75      markus    899: /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
1.64      markus    900:        }
1.75      markus    901: #endif /* LIBWRAP */
1.64      markus    902:        /* Log the connection. */
                    903:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1       deraadt   904:
1.66      markus    905:        /*
                    906:         * We don\'t want to listen forever unless the other side
                    907:         * successfully authenticates itself.  So we set up an alarm which is
                    908:         * cleared after successful authentication.  A limit of zero
                    909:         * indicates no limit. Note that we don\'t set the alarm in debugging
                    910:         * mode; it is just annoying to have the server exit just when you
                    911:         * are about to discover the bug.
                    912:         */
1.64      markus    913:        signal(SIGALRM, grace_alarm_handler);
                    914:        if (!debug_flag)
                    915:                alarm(options.login_grace_time);
                    916:
1.96      markus    917:        sshd_exchange_identification(sock_in, sock_out);
1.66      markus    918:        /*
                    919:         * Check that the connection comes from a privileged port.  Rhosts-
                    920:         * and Rhosts-RSA-Authentication only make sense from priviledged
                    921:         * programs.  Of course, if the intruder has root access on his local
                    922:         * machine, he can connect from any port.  So do not use these
                    923:         * authentication methods from machines that you do not trust.
                    924:         */
1.64      markus    925:        if (remote_port >= IPPORT_RESERVED ||
                    926:            remote_port < IPPORT_RESERVED / 2) {
                    927:                options.rhosts_authentication = 0;
                    928:                options.rhosts_rsa_authentication = 0;
                    929:        }
1.76      markus    930: #ifdef KRB4
                    931:        if (!packet_connection_is_ipv4() &&
                    932:            options.kerberos_authentication) {
                    933:                debug("Kerberos Authentication disabled, only available for IPv4.");
                    934:                options.kerberos_authentication = 0;
                    935:        }
                    936: #endif /* KRB4 */
                    937:
1.64      markus    938:        packet_set_nonblocking();
1.1       deraadt   939:
1.77      markus    940:        /* perform the key exchange */
                    941:        /* authenticate user and start session */
1.98      markus    942:        if (compat20) {
                    943:                do_ssh2_kex();
                    944:                do_authentication2();
                    945:        } else {
                    946:                do_ssh1_kex();
                    947:                do_authentication();
                    948:        }
1.1       deraadt   949:
                    950: #ifdef KRB4
1.64      markus    951:        /* Cleanup user's ticket cache file. */
                    952:        if (options.kerberos_ticket_cleanup)
                    953:                (void) dest_tkt();
1.1       deraadt   954: #endif /* KRB4 */
                    955:
1.64      markus    956:        /* The connection has been terminated. */
                    957:        verbose("Closing connection to %.100s", remote_ip);
                    958:        packet_close();
                    959:        exit(0);
1.1       deraadt   960: }
                    961:
1.65      deraadt   962: /*
1.77      markus    963:  * SSH1 key exchange
1.65      deraadt   964:  */
1.52      markus    965: void
1.96      markus    966: do_ssh1_kex()
1.1       deraadt   967: {
1.64      markus    968:        int i, len;
1.77      markus    969:        int plen, slen;
1.64      markus    970:        BIGNUM *session_key_int;
                    971:        unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1.77      markus    972:        unsigned char cookie[8];
1.64      markus    973:        unsigned int cipher_type, auth_mask, protocol_flags;
                    974:        u_int32_t rand = 0;
                    975:
1.66      markus    976:        /*
                    977:         * Generate check bytes that the client must send back in the user
                    978:         * packet in order for it to be accepted; this is used to defy ip
                    979:         * spoofing attacks.  Note that this only works against somebody
                    980:         * doing IP spoofing from a remote machine; any machine on the local
                    981:         * network can still see outgoing packets and catch the random
                    982:         * cookie.  This only affects rhosts authentication, and this is one
                    983:         * of the reasons why it is inherently insecure.
                    984:         */
1.64      markus    985:        for (i = 0; i < 8; i++) {
                    986:                if (i % 4 == 0)
                    987:                        rand = arc4random();
1.77      markus    988:                cookie[i] = rand & 0xff;
1.64      markus    989:                rand >>= 8;
                    990:        }
                    991:
1.66      markus    992:        /*
                    993:         * Send our public key.  We include in the packet 64 bits of random
                    994:         * data that must be matched in the reply in order to prevent IP
                    995:         * spoofing.
                    996:         */
1.64      markus    997:        packet_start(SSH_SMSG_PUBLIC_KEY);
                    998:        for (i = 0; i < 8; i++)
1.77      markus    999:                packet_put_char(cookie[i]);
1.64      markus   1000:
                   1001:        /* Store our public server RSA key. */
                   1002:        packet_put_int(BN_num_bits(public_key->n));
                   1003:        packet_put_bignum(public_key->e);
                   1004:        packet_put_bignum(public_key->n);
                   1005:
                   1006:        /* Store our public host RSA key. */
                   1007:        packet_put_int(BN_num_bits(sensitive_data.host_key->n));
                   1008:        packet_put_bignum(sensitive_data.host_key->e);
                   1009:        packet_put_bignum(sensitive_data.host_key->n);
                   1010:
                   1011:        /* Put protocol flags. */
                   1012:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1013:
                   1014:        /* Declare which ciphers we support. */
1.97      markus   1015:        packet_put_int(cipher_mask1());
1.64      markus   1016:
                   1017:        /* Declare supported authentication types. */
                   1018:        auth_mask = 0;
                   1019:        if (options.rhosts_authentication)
                   1020:                auth_mask |= 1 << SSH_AUTH_RHOSTS;
                   1021:        if (options.rhosts_rsa_authentication)
                   1022:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                   1023:        if (options.rsa_authentication)
                   1024:                auth_mask |= 1 << SSH_AUTH_RSA;
1.1       deraadt  1025: #ifdef KRB4
1.64      markus   1026:        if (options.kerberos_authentication)
                   1027:                auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1       deraadt  1028: #endif
1.5       dugsong  1029: #ifdef AFS
1.64      markus   1030:        if (options.kerberos_tgt_passing)
                   1031:                auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
                   1032:        if (options.afs_token_passing)
                   1033:                auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1       deraadt  1034: #endif
1.63      markus   1035: #ifdef SKEY
1.64      markus   1036:        if (options.skey_authentication == 1)
                   1037:                auth_mask |= 1 << SSH_AUTH_TIS;
1.63      markus   1038: #endif
1.64      markus   1039:        if (options.password_authentication)
                   1040:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                   1041:        packet_put_int(auth_mask);
                   1042:
                   1043:        /* Send the packet and wait for it to be sent. */
                   1044:        packet_send();
                   1045:        packet_write_wait();
                   1046:
                   1047:        debug("Sent %d bit public key and %d bit host key.",
                   1048:              BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
                   1049:
                   1050:        /* Read clients reply (cipher type and session key). */
                   1051:        packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
                   1052:
1.69      markus   1053:        /* Get cipher type and check whether we accept this. */
1.64      markus   1054:        cipher_type = packet_get_char();
1.69      markus   1055:
1.105     markus   1056:        if (!(cipher_mask() & (1 << cipher_type)))
1.69      markus   1057:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus   1058:
                   1059:        /* Get check bytes from the packet.  These must match those we
                   1060:           sent earlier with the public key packet. */
                   1061:        for (i = 0; i < 8; i++)
1.77      markus   1062:                if (cookie[i] != packet_get_char())
1.64      markus   1063:                        packet_disconnect("IP Spoofing check bytes do not match.");
                   1064:
                   1065:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                   1066:
                   1067:        /* Get the encrypted integer. */
                   1068:        session_key_int = BN_new();
                   1069:        packet_get_bignum(session_key_int, &slen);
                   1070:
                   1071:        protocol_flags = packet_get_int();
                   1072:        packet_set_protocol_flags(protocol_flags);
                   1073:
                   1074:        packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
                   1075:
1.66      markus   1076:        /*
                   1077:         * Decrypt it using our private server key and private host key (key
                   1078:         * with larger modulus first).
                   1079:         */
1.64      markus   1080:        if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
                   1081:                /* Private key has bigger modulus. */
                   1082:                if (BN_num_bits(sensitive_data.private_key->n) <
                   1083:                    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                   1084:                        fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                   1085:                              get_remote_ipaddr(),
                   1086:                              BN_num_bits(sensitive_data.private_key->n),
                   1087:                              BN_num_bits(sensitive_data.host_key->n),
                   1088:                              SSH_KEY_BITS_RESERVED);
                   1089:                }
                   1090:                rsa_private_decrypt(session_key_int, session_key_int,
                   1091:                                    sensitive_data.private_key);
                   1092:                rsa_private_decrypt(session_key_int, session_key_int,
                   1093:                                    sensitive_data.host_key);
                   1094:        } else {
                   1095:                /* Host key has bigger modulus (or they are equal). */
                   1096:                if (BN_num_bits(sensitive_data.host_key->n) <
                   1097:                    BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
                   1098:                        fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
                   1099:                              get_remote_ipaddr(),
                   1100:                              BN_num_bits(sensitive_data.host_key->n),
                   1101:                              BN_num_bits(sensitive_data.private_key->n),
                   1102:                              SSH_KEY_BITS_RESERVED);
                   1103:                }
                   1104:                rsa_private_decrypt(session_key_int, session_key_int,
                   1105:                                    sensitive_data.host_key);
                   1106:                rsa_private_decrypt(session_key_int, session_key_int,
                   1107:                                    sensitive_data.private_key);
                   1108:        }
                   1109:
1.77      markus   1110:        compute_session_id(session_id, cookie,
1.64      markus   1111:                           sensitive_data.host_key->n,
                   1112:                           sensitive_data.private_key->n);
                   1113:
1.77      markus   1114:        /* Destroy the private and public keys.  They will no longer be needed. */
1.108     markus   1115:        destroy_sensitive_data();
1.77      markus   1116:
1.66      markus   1117:        /*
                   1118:         * Extract session key from the decrypted integer.  The key is in the
                   1119:         * least significant 256 bits of the integer; the first byte of the
                   1120:         * key is in the highest bits.
                   1121:         */
1.64      markus   1122:        BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                   1123:        len = BN_num_bytes(session_key_int);
                   1124:        if (len < 0 || len > sizeof(session_key))
                   1125:                fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
                   1126:                      get_remote_ipaddr(),
                   1127:                      len, sizeof(session_key));
                   1128:        memset(session_key, 0, sizeof(session_key));
                   1129:        BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
                   1130:
1.77      markus   1131:        /* Destroy the decrypted integer.  It is no longer needed. */
                   1132:        BN_clear_free(session_key_int);
                   1133:
1.64      markus   1134:        /* Xor the first 16 bytes of the session key with the session id. */
                   1135:        for (i = 0; i < 16; i++)
                   1136:                session_key[i] ^= session_id[i];
                   1137:
                   1138:        /* Set the session key.  From this on all communications will be encrypted. */
                   1139:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                   1140:
                   1141:        /* Destroy our copy of the session key.  It is no longer needed. */
                   1142:        memset(session_key, 0, sizeof(session_key));
                   1143:
                   1144:        debug("Received session key; encryption turned on.");
                   1145:
                   1146:        /* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
                   1147:        packet_start(SSH_SMSG_SUCCESS);
                   1148:        packet_send();
                   1149:        packet_write_wait();
1.98      markus   1150: }
                   1151:
                   1152: /*
                   1153:  * SSH2 key exchange: diffie-hellman-group1-sha1
                   1154:  */
                   1155: void
                   1156: do_ssh2_kex()
                   1157: {
                   1158:        Buffer *server_kexinit;
                   1159:        Buffer *client_kexinit;
                   1160:        int payload_len, dlen;
                   1161:        int slen;
                   1162:        unsigned int klen, kout;
                   1163:        char *ptr;
                   1164:        unsigned char *signature = NULL;
                   1165:        unsigned char *server_host_key_blob = NULL;
                   1166:        unsigned int sbloblen;
                   1167:        DH *dh;
                   1168:        BIGNUM *dh_client_pub = 0;
                   1169:        BIGNUM *shared_secret = 0;
                   1170:        int i;
                   1171:        unsigned char *kbuf;
                   1172:        unsigned char *hash;
                   1173:        Kex *kex;
                   1174:        char *cprop[PROPOSAL_MAX];
                   1175:        char *sprop[PROPOSAL_MAX];
                   1176:
                   1177: /* KEXINIT */
1.102     markus   1178:
                   1179:        if (options.ciphers != NULL) {
1.105     markus   1180:                myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102     markus   1181:                myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
                   1182:        }
1.98      markus   1183:
                   1184:        debug("Sending KEX init.");
                   1185:
                   1186:        for (i = 0; i < PROPOSAL_MAX; i++)
                   1187:                sprop[i] = xstrdup(myproposal[i]);
                   1188:        server_kexinit = kex_init(sprop);
                   1189:        packet_start(SSH2_MSG_KEXINIT);
                   1190:        packet_put_raw(buffer_ptr(server_kexinit), buffer_len(server_kexinit));
                   1191:        packet_send();
                   1192:        packet_write_wait();
                   1193:
                   1194:        debug("done");
                   1195:
                   1196:        packet_read_expect(&payload_len, SSH2_MSG_KEXINIT);
                   1197:
                   1198:        /*
                   1199:         * save raw KEXINIT payload in buffer. this is used during
                   1200:         * computation of the session_id and the session keys.
                   1201:         */
                   1202:        client_kexinit = xmalloc(sizeof(*client_kexinit));
                   1203:        buffer_init(client_kexinit);
                   1204:        ptr = packet_get_raw(&payload_len);
                   1205:        buffer_append(client_kexinit, ptr, payload_len);
                   1206:
                   1207:        /* skip cookie */
                   1208:        for (i = 0; i < 16; i++)
                   1209:                (void) packet_get_char();
                   1210:        /* save kex init proposal strings */
                   1211:        for (i = 0; i < PROPOSAL_MAX; i++) {
                   1212:                cprop[i] = packet_get_string(NULL);
                   1213:                debug("got kexinit string: %s", cprop[i]);
                   1214:        }
                   1215:
                   1216:        i = (int) packet_get_char();
                   1217:        debug("first kex follow == %d", i);
                   1218:        i = packet_get_int();
                   1219:        debug("reserved == %d", i);
                   1220:
                   1221:        debug("done read kexinit");
                   1222:        kex = kex_choose_conf(cprop, sprop, 1);
                   1223:
                   1224: /* KEXDH */
                   1225:
                   1226:        debug("Wait SSH2_MSG_KEXDH_INIT.");
                   1227:        packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
                   1228:
                   1229:        /* key, cert */
                   1230:        dh_client_pub = BN_new();
                   1231:        if (dh_client_pub == NULL)
                   1232:                fatal("dh_client_pub == NULL");
                   1233:        packet_get_bignum2(dh_client_pub, &dlen);
                   1234:
                   1235: #ifdef DEBUG_KEXDH
                   1236:        fprintf(stderr, "\ndh_client_pub= ");
                   1237:        bignum_print(dh_client_pub);
                   1238:        fprintf(stderr, "\n");
                   1239:        debug("bits %d", BN_num_bits(dh_client_pub));
                   1240: #endif
                   1241:
                   1242:        /* generate DH key */
1.101     markus   1243:        dh = dh_new_group1();                   /* XXX depends on 'kex' */
1.98      markus   1244:
                   1245: #ifdef DEBUG_KEXDH
                   1246:        fprintf(stderr, "\np= ");
                   1247:        bignum_print(dh->p);
                   1248:        fprintf(stderr, "\ng= ");
                   1249:        bignum_print(dh->g);
                   1250:        fprintf(stderr, "\npub= ");
                   1251:        bignum_print(dh->pub_key);
                   1252:        fprintf(stderr, "\n");
                   1253: #endif
1.101     markus   1254:        if (!dh_pub_is_valid(dh, dh_client_pub))
                   1255:                packet_disconnect("bad client public DH value");
1.98      markus   1256:
                   1257:        klen = DH_size(dh);
                   1258:        kbuf = xmalloc(klen);
                   1259:        kout = DH_compute_key(kbuf, dh_client_pub, dh);
                   1260:
                   1261: #ifdef DEBUG_KEXDH
                   1262:        debug("shared secret: len %d/%d", klen, kout);
                   1263:        fprintf(stderr, "shared secret == ");
                   1264:        for (i = 0; i< kout; i++)
                   1265:                fprintf(stderr, "%02x", (kbuf[i])&0xff);
                   1266:        fprintf(stderr, "\n");
                   1267: #endif
                   1268:        shared_secret = BN_new();
                   1269:
                   1270:        BN_bin2bn(kbuf, kout, shared_secret);
                   1271:        memset(kbuf, 0, klen);
                   1272:        xfree(kbuf);
                   1273:
1.111     markus   1274:        /* XXX precompute? */
1.108     markus   1275:        dsa_make_key_blob(sensitive_data.dsa_host_key, &server_host_key_blob, &sbloblen);
1.98      markus   1276:
                   1277:        /* calc H */                    /* XXX depends on 'kex' */
                   1278:        hash = kex_hash(
                   1279:            client_version_string,
                   1280:            server_version_string,
                   1281:            buffer_ptr(client_kexinit), buffer_len(client_kexinit),
                   1282:            buffer_ptr(server_kexinit), buffer_len(server_kexinit),
                   1283:            (char *)server_host_key_blob, sbloblen,
                   1284:            dh_client_pub,
                   1285:            dh->pub_key,
                   1286:            shared_secret
                   1287:        );
                   1288:        buffer_free(client_kexinit);
                   1289:        buffer_free(server_kexinit);
                   1290:        xfree(client_kexinit);
                   1291:        xfree(server_kexinit);
                   1292: #ifdef DEBUG_KEXDH
1.105     markus   1293:        fprintf(stderr, "hash == ");
                   1294:        for (i = 0; i< 20; i++)
                   1295:                fprintf(stderr, "%02x", (hash[i])&0xff);
                   1296:        fprintf(stderr, "\n");
1.98      markus   1297: #endif
1.108     markus   1298:        /* save session id := H */
                   1299:        /* XXX hashlen depends on KEX */
                   1300:        session_id2_len = 20;
                   1301:        session_id2 = xmalloc(session_id2_len);
                   1302:        memcpy(session_id2, hash, session_id2_len);
                   1303:
1.98      markus   1304:        /* sign H */
1.108     markus   1305:        /* XXX hashlen depends on KEX */
                   1306:        dsa_sign(sensitive_data.dsa_host_key, &signature, &slen, hash, 20);
                   1307:
                   1308:        destroy_sensitive_data();
1.98      markus   1309:
                   1310:        /* send server hostkey, DH pubkey 'f' and singed H */
                   1311:        packet_start(SSH2_MSG_KEXDH_REPLY);
                   1312:        packet_put_string((char *)server_host_key_blob, sbloblen);
1.114   ! markus   1313:        packet_put_bignum2(dh->pub_key);        /* f */
1.98      markus   1314:        packet_put_string((char *)signature, slen);
                   1315:        packet_send();
1.106     markus   1316:        xfree(signature);
1.111     markus   1317:        xfree(server_host_key_blob);
1.98      markus   1318:        packet_write_wait();
                   1319:
                   1320:        kex_derive_keys(kex, hash, shared_secret);
                   1321:        packet_set_kex(kex);
                   1322:
                   1323:        /* have keys, free DH */
                   1324:        DH_free(dh);
                   1325:
                   1326:        debug("send SSH2_MSG_NEWKEYS.");
                   1327:        packet_start(SSH2_MSG_NEWKEYS);
                   1328:        packet_send();
                   1329:        packet_write_wait();
                   1330:        debug("done: send SSH2_MSG_NEWKEYS.");
                   1331:
                   1332:        debug("Wait SSH2_MSG_NEWKEYS.");
                   1333:        packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
                   1334:        debug("GOT SSH2_MSG_NEWKEYS.");
                   1335:
1.100     markus   1336: #ifdef DEBUG_KEXDH
1.98      markus   1337:        /* send 1st encrypted/maced/compressed message */
                   1338:        packet_start(SSH2_MSG_IGNORE);
                   1339:        packet_put_cstring("markus");
                   1340:        packet_send();
                   1341:        packet_write_wait();
1.100     markus   1342: #endif
1.98      markus   1343:        debug("done: KEX2.");
1.1       deraadt  1344: }