/* ====================================================================
 * Copyright (c) 1998 Ralf S. Engelschall. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by 
 *     Ralf S. Engelschall <rse@engelschall.com> for use in the
 *     mod_ssl project (http://www.engelschall.com/sw/mod_ssl/)."
 *
 * 4. The names "mod_ssl" must not be used to endorse or promote
 *    products derived from this software without prior written
 *    permission. For written permission, please contact
 *    rse@engelschall.com.
 *
 * 5. Products derived from this software may not be called "mod_ssl"
 *    nor may "mod_ssl" appear in their names without prior
 *    written permission of Ralf S. Engelschall.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by 
 *     Ralf S. Engelschall <rse@engelschall.com> for use in the
 *     mod_ssl project (http://www.engelschall.com/sw/mod_ssl/)."
 *
 * THIS SOFTWARE IS PROVIDED BY RALF S. ENGELSCHALL ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL RALF S. ENGELSCHALL OR
 * HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 */


#include "mod_ssl.h"


/*  _________________________________________________________________
**
**  Module Initialization
**  _________________________________________________________________
*/

/*
 *  Per-module initialization
 */
void ssl_init_Module(server_rec *s, pool *p)
{
    SSLModConfigRec *mc = myModConfig();
    SSLSrvConfigRec *sc;
    server_rec *s2;
    char *cp;

    ssl_config_global_create();

    mc->nInitCount++;

    mc->rCtx.pServ = s;
    mc->rCtx.pPool = p;

    /* 
     *  try to fix the configuration and open the dedicated SSL
     *  logfile as early as possible 
     */
    for (s2 = s; s2 != NULL; s2 = s2->next) {
        sc = mySrvConfig(s2);

        /* Fix up stuff that may not have been set */
        if (sc->bEnabled == UNSET)
            sc->bEnabled = FALSE;
        if (sc->nVerifyClient == SSL_CVERIFY_UNSET)
            sc->nVerifyClient = SSL_CVERIFY_NONE;
        if (sc->nVerifyDepth == UNSET)
            sc->nVerifyDepth = 1;
        if (sc->nSessionCacheTimeout == UNSET)
            sc->nSessionCacheTimeout = CFGDEF_SESSION_CACHE_TIMEOUT;
        if (sc->nPassPhraseDialogType == SSL_PPTYPE_UNSET)
            sc->nPassPhraseDialogType = SSL_PPTYPE_BUILTIN;

        /* Open the dedicated SSL logfile */
        ssl_log_open(s2, p);
    }

    if (mc->nInitCount == 1)
        ssl_log(s, SSL_LOG_INFO, "Init: 1st startup round (still not detached)");
    else if (mc->nInitCount == 2)
        ssl_log(s, SSL_LOG_INFO, "Init: 2nd startup round (already detached)");
    else
        ssl_log(s, SSL_LOG_INFO, "Init: %d%s restart round (already detached)",
                mc->nInitCount-2, (mc->nInitCount-2) == 1 ? "st" : "nd");

    /*  
     *  The initialization phase inside the Apache API is totally bogus. 
     *  We actually have three non-trivial problems: 
     *
     *  1. Under Unix the API does a 2-round initialization of modules while
     *     under Win32 it doesn't. This means we have to make sure that at
     *     least the pass phrase dialog doesn't occur twice.  We overcome this
     *     problem by using a counter (mc->nInitCount) which has to
     *     survive the init rounds.
     *
     *  2. Between the first and the second round Apache detaches from
     *     the terminal under Unix. This means that our pass phrase dialog
     *     _has_ to be done in the first round and _cannot_ be done in the
     *     second round.
     *
     *  3. When Dynamic Shared Object (DSO) mechanism is used under Unix the
     *     module segment (code & data) gets unloaded and re-loaded between
     *     the first and the second round. This means no global data survives
     *     between first and the second init round. We overcome this by using
     *     an entry ("ssl_module") inside the ap_global_ctx.
     *
     *  The situation as a table:
     *
     *  Unix/static Unix/DSO          Win32     Action Required
     *              (-DSHARED_MODULE) (-DWIN32)
     *  ----------- ----------------- --------- -----------------------------------
     *  -           load module       -         -
     *  init        init              init      SSLeay init, Pass Phrase Dialog
     *  detach      detach            -         -
     *  -           reload module     -         -
     *  init        init              -         SSLeay init, mod_ssl init
     *
     *  Ok, now try to solve this totally ugly situation...
     */

#ifdef SHARED_MODULE
    ssl_init_SSLeay(s);
#else
    if (mc->nInitCount <= 2) {
        ssl_init_SSLeay(s);
    }
#endif
    if (mc->nInitCount == 1) {
        ssl_pphrase_Handle(s, p);
#ifndef WIN32
        return;
#endif
    }

    /*
     * Warn the user that he should use the session cache.
     * But we can operate without it, of course.
     */
    if (mc->nSessionCacheMode == SSL_SCMODE_UNSET) {
        ssl_log(s, SSL_LOG_WARN, 
                "Init: Session Cache is not configured [hint: SSLSessionCache]");
        mc->nSessionCacheMode = SSL_SCMODE_NONE;
    }

    /*
     *  initialize the mutex handling and session caching
     */
    ssl_mutex_init(s, p);
    ssl_scache_init(s, p);

    /*
     *  pre-generate the temporary RSA key
     */
    if (mc->pRSATmpKey == NULL) {
        ssl_log(s, SSL_LOG_INFO, "Init: Generating temporary (512 bit) RSA private key");
#if SSLEAY_VERSION_NUMBER >= 0x0900
        mc->pRSATmpKey = RSA_generate_key(512, RSA_F4, NULL, NULL);
#else
        mc->pRSATmpKey = RSA_generate_key(512, RSA_F4, NULL);
#endif
        if (mc->pRSATmpKey == NULL) {
            ssl_log(s, SSL_LOG_ERROR, "Init: Failed to generate temporary (512 bit) RSA private key");
            ssl_die();
        }
    }

    /*
     *  initialize servers
     */
    ssl_log(s, SSL_LOG_INFO, "Init: Initializing (virtual) servers for SSL");
    for (; s != NULL; s = s->next) {
        sc = mySrvConfig(s);

        if (sc->bEnabled)
            ssl_log(s, SSL_LOG_INFO, 
                    "Init: Configuring server %s:%d for SSL protocol",
                    s->server_hostname, s->port);

        /* If we are disabled skip this server but
           make sure the port is initialized correctly */
        if (!sc->bEnabled) {
            if (!s->port)
                s->port = DEFAULT_HTTP_PORT;
            continue;
        }

        /* Give a warning when HTTPS is configured for HTTP port */
        if (s->port == DEFAULT_HTTP_PORT)
            ssl_log(s, SSL_LOG_WARN, 
                    "Init: You configured HTTPS on the standard HTTP(%d) port!",
                    DEFAULT_HTTP_PORT);
        if (!s->port)
            s->port = DEFAULT_HTTPS_PORT;

        /* 
         * Now check for important parameters and the
         * possibility that the user forgot to set them.
         */
        if (sc->nSessionCacheTimeout == 0) {
            ssl_log(s, SSL_LOG_ERROR,
                    "Init: (%s:%d) No SSL Session Cache Timeout set "
                    "[hint: SSLSessionCacheTimeout]",
                    s->server_hostname, s->port);
            ssl_die();
        }
        if (!sc->szCertificateFile) {
            ssl_log(s, SSL_LOG_ERROR,
                    "Init: (%s:%d) No SSL Certificate set [hint: SSLCertificateFile]",
                    s->server_hostname, s->port);
            ssl_die();
        }

        /*
         * Read the server certificate and key
         */
        ssl_init_GetCertAndKey(s, p, sc);
    }

    /*
     *  Announce mod_ssl and SSLeay in HTTP Server field
     *  as ``mod_ssl/X.X.X SSLeay/X.X.X''
     */
    if ((cp = ssl_var_lookup(p, NULL, NULL, NULL, "SSL_VERSION_PRODUCT")) != NULL && cp[0] != NUL)
        ap_add_version_component(cp);
    ap_add_version_component(ssl_var_lookup(p, NULL, NULL, NULL, "SSL_VERSION_INTERFACE"));
    ap_add_version_component(ssl_var_lookup(p, NULL, NULL, NULL, "SSL_VERSION_LIBRARY"));

    return;
}

/*
 *  Initialize SSLeay (also already needed for the pass phrase dialog)
 */
void ssl_init_SSLeay(server_rec *s)
{
    ssl_log(s, SSL_LOG_INFO, "Init: Initializing SSLeay library");
#ifdef WIN32
    CRYPTO_malloc_init();
#endif
    SSL_load_error_strings();
    SSLeay_add_ssl_algorithms();
    ssl_util_thread_setup();
    return;
}

/*
 * Read the SSL Server Certificate and Key
 */
void ssl_init_GetCertAndKey(server_rec *s, pool *p, SSLSrvConfigRec *sc)
{
    SSLModConfigRec *mc = myModConfig();
    int nVerify;
    char *cpServerName;
    RSA **ppRSA;
    X509 **ppX509;

    cpServerName = ap_psprintf(p, "%s:%d", s->server_hostname, s->port);

    /*  
     *  Check for problematic re-initializations
     */
    if (sc->px509Certificate) {
        ssl_log(s, SSL_LOG_ERROR, 
                "Init: (%s) Illegal attempt to re-initialise SSL for server",
                cpServerName);
        ssl_die();
    }

    /*
     *  Calculate SSLeay verify type
     */
    nVerify = SSL_VERIFY_NONE;
    switch (sc->nVerifyClient) {
        case SSL_CVERIFY_REQUIRE:
            nVerify |= SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
            break;
        case SSL_CVERIFY_OPTIONAL:
        case SSL_CVERIFY_OPTIONAL_NO_CA:
            nVerify |= SSL_VERIFY_PEER;
            break;
        default:
            break;
    }

    /*
     *  Create new SSL context and configure callbacks
     */
    ssl_log(s, SSL_LOG_DEBUG, 
            "Init: (%s) Creating new SSL context", cpServerName);
    sc->pSSLCtx = SSL_CTX_new(SSLv23_server_method());
    SSL_CTX_set_verify(sc->pSSLCtx, nVerify, 
                 ssl_callback_SSLVerify);
    SSL_CTX_sess_set_new_cb(sc->pSSLCtx, 
                 ssl_callback_NewSessionCacheEntry);
    SSL_CTX_sess_set_get_cb(sc->pSSLCtx, 
                 ssl_callback_GetSessionCacheEntry);
    SSL_CTX_sess_set_remove_cb(sc->pSSLCtx, 
                 ssl_callback_DelSessionCacheEntry);
    SSL_CTX_set_tmp_rsa_callback(sc->pSSLCtx, 
                 ssl_callback_TmpRSA);

    /*
     *  Configure required SSL Ciphers 
     */
    ssl_log(s, SSL_LOG_DEBUG, 
            "Init: (%s) Configuring permitted SSL ciphers", cpServerName);
    if (sc->szCipherSuite != NULL) {
        if (!SSL_CTX_set_cipher_list(sc->pSSLCtx, sc->szCipherSuite)) {
            ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLEAY, 
                    "Init: (%s) Unable to configure permitted SSL ciphers",
                    cpServerName);
            ssl_die();
        }
    }

    /*
     * Configure SSL Client verification
     */
    ssl_log(s, SSL_LOG_DEBUG, 
            "Init: (%s) Configuring client verification locations", cpServerName);
    if (   ( (   sc->szCACertificateFile 
              || sc->szCACertificatePath)
           && !SSL_CTX_load_verify_locations(sc->pSSLCtx,
                                             sc->szCACertificateFile,
                                             sc->szCACertificatePath) )
        || !SSL_CTX_set_default_verify_paths(sc->pSSLCtx) ) {
        ssl_log(s, SSL_LOG_ERROR|SSL_ADD_SSLEAY, 
                "Init: (%s) Unable to configure SSL verify locations",
                cpServerName);
        ssl_die();
    }

    /* 
     *  Additionally load certificates which will be sent to the
     *  client on `SSLv3 write certificate request A'. This is
     *  optionally used by the clients to speedup the server
     *  authentication when SSLv3 certificate chaining is ised.
     *  Here the client loads intermediate certificates in the
     *  chain from the server. This defaults to
     *  SSLCACertificateFile. 
     */
    if (   sc->szCACertificateReqFile != NULL
        || sc->szCACertificateFile    != NULL)
        ssl_log(s, SSL_LOG_DEBUG, "Init: (%s) Reading server CA certification file",
                cpServerName);
    if (sc->szCACertificateReqFile != NULL)
        SSL_CTX_set_client_CA_list(sc->pSSLCtx,
            SSL_load_client_CA_file(sc->szCACertificateReqFile));
    else
        if (sc->szCACertificateFile != NULL)
            SSL_CTX_set_client_CA_list(sc->pSSLCtx,
                SSL_load_client_CA_file(sc->szCACertificateFile));

    /*
     *  Configure server certificate
     */
    ssl_log(s, SSL_LOG_DEBUG, 
            "Init: (%s) Configuring server certificate", cpServerName);
    if ((ppX509 = (X509 **)ssl_ds_table_get(mc->tPublicCert, 
                                            cpServerName)) == NULL) {
        ssl_log(s, SSL_LOG_ERROR, 
                "Init: (%s) Ops, can't find server certificate?!", cpServerName);
        ssl_die();
    }
    sc->px509Certificate = *ppX509;

    /*
     *  Configure server private key 
     */
    ssl_log(s, SSL_LOG_DEBUG, 
            "Init: (%s) Configuring server private key", cpServerName);
    if ((ppRSA = (RSA **)ssl_ds_table_get(mc->tPrivateKey, cpServerName)) == NULL) {
        ssl_log(s, SSL_LOG_ERROR, 
                "Init: (%s) Ops, can't find server private key?!", cpServerName);
        ssl_die();
    }
    sc->prsaKey = *ppRSA;

    return;
}

void ssl_init_Child(server_rec *s, pool *p)
{
     /* open the mutex lockfile */
     ssl_mutex_open(s, p);
     return;
}

