]> granicus.if.org Git - apache/blobdiff - modules/ssl/ssl_engine_pphrase.c
mod_ssl: Add support for loading TLS certificates through the PKCS#11
[apache] / modules / ssl / ssl_engine_pphrase.c
index 7f0e4b6949e64565a65b723312d09286271eaa7c..85982c80c145a118e0808dcaa565f97f708bd386 100644 (file)
@@ -1,9 +1,9 @@
-/* Copyright 2001-2005 The Apache Software Foundation or its licensors, as
- * applicable.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
                                            -- Clifford Stoll     */
 #include "ssl_private.h"
 
+typedef struct {
+    server_rec         *s;
+    apr_pool_t         *p;
+    apr_array_header_t *aPassPhrase;
+    int                 nPassPhraseCur;
+    char               *cpPassPhraseCur;
+    int                 nPassPhraseDialog;
+    int                 nPassPhraseDialogCur;
+    BOOL                bPassPhraseDialogOnce;
+    const char         *key_id;
+    const char         *pkey_file;
+} pphrase_cb_arg_t;
+
 /*
  * Return true if the named file exists and is readable
  */
 
-static apr_status_t exists_and_readable(char *fname, apr_pool_t *pool, apr_time_t *mtime)
+static apr_status_t exists_and_readable(const char *fname, apr_pool_t *pool,
+                                        apr_time_t *mtime)
 {
     apr_status_t stat;
     apr_finfo_t sbuf;
@@ -73,11 +87,11 @@ static apr_status_t exists_and_readable(char *fname, apr_pool_t *pool, apr_time_
  * since apr_array_push() will apr_alloc arr->nalloc * 2 elts,
  * leaving the original arr->elts to waste.
  */
-static char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
-                                  char *id, char *an)
+static const char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
+                                  const char *id, int i)
 {
     /* 'p' pool used here is cleared on restarts (or sooner) */
-    char *key = apr_psprintf(p, "%s:%s", id, an);
+    char *key = apr_psprintf(p, "%s:%d", id, i);
     void *keyptr = apr_hash_get(mc->tVHostKeys, key,
                                 APR_HASH_KEY_STRING);
 
@@ -103,17 +117,7 @@ static char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
 static apr_file_t *writetty = NULL;
 static apr_file_t *readtty = NULL;
 
-/*
- * sslc has a nasty flaw where its
- * PEM_read_bio_PrivateKey does not take a callback arg.
- */
-static server_rec *ssl_pphrase_server_rec = NULL;
-
-#ifdef SSLC_VERSION_NUMBER
-int ssl_pphrase_Handle_CB(char *, int, int);
-#else
 int ssl_pphrase_Handle_CB(char *, int, int, void *);
-#endif
 
 static char *pphrase_array_get(apr_array_header_t *arr, int idx)
 {
@@ -124,421 +128,246 @@ static char *pphrase_array_get(apr_array_header_t *arr, int idx)
     return ((char **)arr->elts)[idx];
 }
 
-static void pphrase_array_clear(apr_array_header_t *arr)
-{
-    if (arr->nelts > 0) {
-        memset(arr->elts, 0, arr->elt_size * arr->nelts);
-    }
-    arr->nelts = 0;
-}
-
-void ssl_pphrase_Handle(server_rec *s, apr_pool_t *p)
+apr_status_t ssl_load_encrypted_pkey(server_rec *s, apr_pool_t *p, int idx,
+                                     const char *pkey_file,
+                                     apr_array_header_t **pphrases)
 {
     SSLModConfigRec *mc = myModConfig(s);
-    SSLSrvConfigRec *sc;
-    server_rec *pServ;
-    char *cpVHostID;
-    char szPath[MAX_STRING_LEN];
-    EVP_PKEY *pPrivateKey;
+    SSLSrvConfigRec *sc = mySrvConfig(s);
+    const char *key_id = asn1_table_vhost_key(mc, p, sc->vhost_id, idx);
+    EVP_PKEY *pPrivateKey = NULL;
     ssl_asn1_t *asn1;
-    unsigned char *ucp;
-    long int length;
-    X509 *pX509Cert;
-    BOOL bReadable;
-    apr_array_header_t *aPassPhrase;
-    int nPassPhrase;
-    int nPassPhraseCur;
-    char *cpPassPhraseCur;
-    int nPassPhraseRetry;
-    int nPassPhraseDialog;
-    int nPassPhraseDialogCur;
-    BOOL bPassPhraseDialogOnce;
-    char **cpp;
-    int i, j;
-    ssl_algo_t algoCert, algoKey, at;
-    char *an;
-    char *cp;
+    int nPassPhrase = (*pphrases)->nelts;
+    int nPassPhraseRetry = 0;
     apr_time_t pkey_mtime = 0;
-    int isterm = 1;
     apr_status_t rv;
-    /*
-     * Start with a fresh pass phrase array
-     */
-    aPassPhrase       = apr_array_make(p, 2, sizeof(char *));
-    nPassPhrase       = 0;
-    nPassPhraseDialog = 0;
+    pphrase_cb_arg_t ppcb_arg;
+
+    if (!pkey_file) {
+         ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02573)
+                      "Init: No private key specified for %s", key_id);
+         return ssl_die(s);
+    }
+    else if ((rv = exists_and_readable(pkey_file, p, &pkey_mtime))
+             != APR_SUCCESS ) {
+         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, APLOGNO(02574)
+                      "Init: Can't open server private key file %s", pkey_file);
+         return ssl_die(s);
+    }
+
+    ppcb_arg.s                     = s;
+    ppcb_arg.p                     = p;
+    ppcb_arg.aPassPhrase           = *pphrases;
+    ppcb_arg.nPassPhraseCur        = 0;
+    ppcb_arg.cpPassPhraseCur       = NULL;
+    ppcb_arg.nPassPhraseDialog     = 0;
+    ppcb_arg.nPassPhraseDialogCur  = 0;
+    ppcb_arg.bPassPhraseDialogOnce = TRUE;
+    ppcb_arg.key_id                = key_id;
+    ppcb_arg.pkey_file             = pkey_file;
 
     /*
-     * Walk through all configured servers
+     * if the private key is encrypted and SSLPassPhraseDialog
+     * is configured to "builtin" it isn't possible to prompt for
+     * a password after httpd has detached from the tty.
+     * in this case if we already have a private key and the
+     * file name/mtime hasn't changed, then reuse the existing key.
+     * we also reuse existing private keys that were encrypted for
+     * exec: and pipe: dialogs to minimize chances to snoop the
+     * password.  that and pipe: dialogs might prompt the user
+     * for password, which on win32 for example could happen 4
+     * times at startup.  twice for each child and twice within
+     * each since apache "restarts itself" on startup.
+     * of course this will not work for the builtin dialog if
+     * the server was started without LoadModule ssl_module
+     * configured, then restarted with it configured.
+     * but we fall through with a chance of success if the key
+     * is not encrypted or can be handled via exec or pipe dialog.
+     * and in the case of fallthrough, pkey_mtime and isatty()
+     * are used to give a better idea as to what failed.
      */
-    for (pServ = s; pServ != NULL; pServ = pServ->next) {
-        sc = mySrvConfig(pServ);
-
-        if (!sc->enabled)
-            continue;
+    if (pkey_mtime) {
+        ssl_asn1_t *asn1 = ssl_asn1_table_get(mc->tPrivateKey, key_id);
+        if (asn1 && (asn1->source_mtime == pkey_mtime)) {
+            ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02575)
+                         "Reusing existing private key from %s on restart",
+                         ppcb_arg.pkey_file);
+            return APR_SUCCESS;
+        }
+    }
 
-        cpVHostID = ssl_util_vhostid(p, pServ);
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, pServ,
-                     "Loading certificate & private key of SSL-aware server");
+    ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02576)
+                 "Attempting to load encrypted (?) private key %s", key_id);
 
+    for (;;) {
         /*
-         * Read in server certificate(s): This is the easy part
-         * because this file isn't encrypted in any way.
+         * Try to read the private key file with the help of
+         * the callback function which serves the pass
+         * phrases to OpenSSL
          */
-        if (sc->server->pks->cert_files[0] == NULL) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, 0, pServ,
-                         "Server should be SSL-aware but has no certificate "
-                         "configured [Hint: SSLCertificateFile]");
-            ssl_die();
-        }
-        algoCert = SSL_ALGO_UNKNOWN;
-        algoKey  = SSL_ALGO_UNKNOWN;
-        for (i = 0, j = 0; i < SSL_AIDX_MAX && sc->server->pks->cert_files[i] != NULL; i++) {
-
-            apr_cpystrn(szPath, sc->server->pks->cert_files[i], sizeof(szPath));
-            if ((rv = exists_and_readable(szPath, p, NULL)) != APR_SUCCESS) {
-                ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
-                             "Init: Can't open server certificate file %s",
-                             szPath);
-                ssl_die();
-            }
-            if ((pX509Cert = SSL_read_X509(szPath, NULL, NULL)) == NULL) {
-                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
-                        "Init: Unable to read server certificate from file %s", szPath);
-                ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
-                ssl_die();
-            }
 
-            /*
-             * check algorithm type of certificate and make
-             * sure only one certificate per type is used.
-             */
-            at = ssl_util_algotypeof(pX509Cert, NULL);
-            an = ssl_util_algotypestr(at);
-            if (algoCert & at) {
-                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
-                             "Init: Multiple %s server certificates not "
-                             "allowed", an);
-                ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
-                ssl_die();
-            }
-            algoCert |= at;
+        ppcb_arg.cpPassPhraseCur = NULL;
 
-            /*
-             * Insert the certificate into global module configuration to let it
-             * survive the processing between the 1st Apache API init round (where
-             * we operate here) and the 2nd Apache init round (where the
-             * certificate is actually used to configure mod_ssl's per-server
-             * configuration structures).
-             */
-            cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
-            length = i2d_X509(pX509Cert, NULL);
-            ucp = ssl_asn1_table_set(mc->tPublicCert, cp, length);
-            (void)i2d_X509(pX509Cert, &ucp); /* 2nd arg increments */
+        /* Ensure that the error stack is empty; some SSL
+         * functions will fail spuriously if the error stack
+         * is not empty. */
+        ERR_clear_error();
 
-            /*
-             * Free the X509 structure
-             */
-            X509_free(pX509Cert);
+        pPrivateKey = modssl_read_privatekey(ppcb_arg.pkey_file,
+                                             ssl_pphrase_Handle_CB, &ppcb_arg);
+        /* If the private key was successfully read, nothing more to
+           do here. */
+        if (pPrivateKey != NULL)
+            break;
 
-            /*
-             * Read in the private key: This is the non-trivial part, because the
-             * key is typically encrypted, so a pass phrase dialog has to be used
-             * to request it from the user (or it has to be alternatively gathered
-             * from a dialog program). The important point here is that ISPs
-             * usually have hundrets of virtual servers configured and a lot of
-             * them use SSL, so really we have to minimize the pass phrase
-             * dialogs.
-             *
-             * The idea is this: When N virtual hosts are configured and all of
-             * them use encrypted private keys with different pass phrases, we
-             * have no chance and have to pop up N pass phrase dialogs. But
-             * usually the admin is clever enough and uses the same pass phrase
-             * for more private key files (typically he even uses one single pass
-             * phrase for all). When this is the case we can minimize the dialogs
-             * by trying to re-use already known/entered pass phrases.
-             */
-            if (sc->server->pks->key_files[j] != NULL)
-                apr_cpystrn(szPath, sc->server->pks->key_files[j++], sizeof(szPath));
-
-            /*
-             * Try to read the private key file with the help of
-             * the callback function which serves the pass
-             * phrases to OpenSSL
-             */
-            myCtxVarSet(mc,  1, pServ);
-            myCtxVarSet(mc,  2, p);
-            myCtxVarSet(mc,  3, aPassPhrase);
-            myCtxVarSet(mc,  4, &nPassPhraseCur);
-            myCtxVarSet(mc,  5, &cpPassPhraseCur);
-            myCtxVarSet(mc,  6, cpVHostID);
-            myCtxVarSet(mc,  7, an);
-            myCtxVarSet(mc,  8, &nPassPhraseDialog);
-            myCtxVarSet(mc,  9, &nPassPhraseDialogCur);
-            myCtxVarSet(mc, 10, &bPassPhraseDialogOnce);
-
-            nPassPhraseCur        = 0;
-            nPassPhraseRetry      = 0;
-            nPassPhraseDialogCur  = 0;
-            bPassPhraseDialogOnce = TRUE;
-
-            pPrivateKey = NULL;
-
-            for (;;) {
-                /*
-                 * Try to read the private key file with the help of
-                 * the callback function which serves the pass
-                 * phrases to OpenSSL
-                 */
-                if ((rv = exists_and_readable(szPath, p,
-                                              &pkey_mtime)) != APR_SUCCESS ) {
-                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
-                                  "Init: Can't open server private key file "
-                                  "%s",szPath);
-                     ssl_die();
-                }
-
-                /*
-                 * if the private key is encrypted and SSLPassPhraseDialog
-                 * is configured to "builtin" it isn't possible to prompt for
-                 * a password after httpd has detached from the tty.
-                 * in this case if we already have a private key and the
-                 * file name/mtime hasn't changed, then reuse the existing key.
-                 * we also reuse existing private keys that were encrypted for
-                 * exec: and pipe: dialogs to minimize chances to snoop the
-                 * password.  that and pipe: dialogs might prompt the user
-                 * for password, which on win32 for example could happen 4
-                 * times at startup.  twice for each child and twice within
-                 * each since apache "restarts itself" on startup.
-                 * of course this will not work for the builtin dialog if
-                 * the server was started without LoadModule ssl_module
-                 * configured, then restarted with it configured.
-                 * but we fall through with a chance of success if the key
-                 * is not encrypted or can be handled via exec or pipe dialog.
-                 * and in the case of fallthrough, pkey_mtime and isatty()
-                 * are used to give a better idea as to what failed.
-                 */
-                if (pkey_mtime) {
-                    int i;
-
-                    for (i=0; i < SSL_AIDX_MAX; i++) {
-                        const char *key_id =
-                            ssl_asn1_table_keyfmt(p, cpVHostID, i);
-                        ssl_asn1_t *asn1 = 
-                            ssl_asn1_table_get(mc->tPrivateKey, key_id);
-                    
-                        if (asn1 && (asn1->source_mtime == pkey_mtime)) {
-                            ap_log_error(APLOG_MARK, APLOG_INFO,
-                                         0, pServ,
-                                         "%s reusing existing "
-                                         "%s private key on restart",
-                                         cpVHostID, ssl_asn1_keystr(i));
-                            return;
-                        }
-                    }
-                }
-
-                cpPassPhraseCur = NULL;
-                ssl_pphrase_server_rec = s; /* to make up for sslc flaw */
-
-                /* Ensure that the error stack is empty; some SSL
-                 * functions will fail spuriously if the error stack
-                 * is not empty. */
-                ERR_clear_error();
-
-                bReadable = ((pPrivateKey = SSL_read_PrivateKey(szPath, NULL,
-                            ssl_pphrase_Handle_CB, s)) != NULL ? TRUE : FALSE);
-
-                /*
-                 * when the private key file now was readable,
-                 * it's fine and we go out of the loop
-                 */
-                if (bReadable)
-                   break;
-
-                /*
-                 * when we have more remembered pass phrases
-                 * try to reuse these first.
-                 */
-                if (nPassPhraseCur < nPassPhrase) {
-                    nPassPhraseCur++;
-                    continue;
-                }
+        /*
+         * when we have more remembered pass phrases
+         * try to reuse these first.
+         */
+        if (ppcb_arg.nPassPhraseCur < nPassPhrase) {
+            ppcb_arg.nPassPhraseCur++;
+            continue;
+        }
 
-                /*
-                 * else it's not readable and we have no more
-                 * remembered pass phrases. Then this has to mean
-                 * that the callback function popped up the dialog
-                 * but a wrong pass phrase was entered.  We give the
-                 * user (but not the dialog program) a few more
-                 * chances...
-                 */
+        /*
+         * else it's not readable and we have no more
+         * remembered pass phrases. Then this has to mean
+         * that the callback function popped up the dialog
+         * but a wrong pass phrase was entered.  We give the
+         * user (but not the dialog program) a few more
+         * chances...
+         */
 #ifndef WIN32
-                if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
-                       || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
+        if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
+             || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
 #else
-                if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
+        if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
 #endif
-                    && cpPassPhraseCur != NULL
-                    && nPassPhraseRetry < BUILTIN_DIALOG_RETRIES ) {
-                    apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect "
-                            "(%d more retr%s permitted).\n",
-                            (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry),
-                            (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry) == 1 ? "y" : "ies");
-                    nPassPhraseRetry++;
-                    if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
-                        apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
-                                    * 5 * APR_USEC_PER_SEC);
-                    continue;
-                }
+            && ppcb_arg.cpPassPhraseCur != NULL
+            && nPassPhraseRetry < BUILTIN_DIALOG_RETRIES ) {
+            apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect "
+                    "(%d more retr%s permitted).\n",
+                    (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry),
+                    (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry) == 1 ? "y" : "ies");
+            nPassPhraseRetry++;
+            if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
+                apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
+                            * 5 * APR_USEC_PER_SEC);
+            continue;
+        }
 #ifdef WIN32
-                if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN) {
-                    ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
-                                 "Init: SSLPassPhraseDialog builtin is not "
-                                 "supported on Win32 (key file "
-                                 "%s)", szPath);
-                    ssl_die();
-                }
+        if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN) {
+            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02577)
+                         "Init: SSLPassPhraseDialog builtin is not "
+                         "supported on Win32 (key file "
+                         "%s)", ppcb_arg.pkey_file);
+            return ssl_die(s);
+        }
 #endif /* WIN32 */
 
-                /*
-                 * Ok, anything else now means a fatal error.
-                 */
-                if (cpPassPhraseCur == NULL) {
-                    if (nPassPhraseDialogCur && pkey_mtime &&
-                        !(isterm = isatty(fileno(stdout)))) /* XXX: apr_isatty() */
-                    {
-                        ap_log_error(APLOG_MARK, APLOG_ERR, 0,
-                                     pServ,
-                                     "Init: Unable to read pass phrase "
-                                     "[Hint: key introduced or changed "
-                                     "before restart?]");
-                        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
-                    }
-                    else {
-                        ap_log_error(APLOG_MARK, APLOG_ERR, 0,
-                                     pServ, "Init: Private key not found");
-                        ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
-                    }
-                    if (writetty) {
-                        apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
-                        apr_file_printf(writetty, "**Stopped\n");
-                    }
-                }
-                else {
-                    ap_log_error(APLOG_MARK, APLOG_ERR, 0,
-                                 pServ, "Init: Pass phrase incorrect");
-                    ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
-
-                    if (writetty) {
-                        apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
-                        apr_file_printf(writetty, "**Stopped\n");
-                    }
-                }
-                ssl_die();
-            }
-
-            if (pPrivateKey == NULL) {
-                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
-                            "Init: Unable to read server private key from "
-                            "file %s [Hint: Perhaps it is in a separate file? "
-                            "  See SSLCertificateKeyFile]", szPath);
-                ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
-                ssl_die();
-            }
-
-            /*
-             * check algorithm type of private key and make
-             * sure only one private key per type is used.
-             */
-            at = ssl_util_algotypeof(NULL, pPrivateKey);
-            an = ssl_util_algotypestr(at);
-            if (algoKey & at) {
-                ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
-                             "Init: Multiple %s server private keys not "
-                             "allowed", an);
-                ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
-                ssl_die();
-            }
-            algoKey |= at;
-
-            /*
-             * Log the type of reading
-             */
-            if (nPassPhraseDialogCur == 0) {
-                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, pServ, 
-                             "unencrypted %s private key - pass phrase not "
-                             "required", an);
+        /*
+         * Ok, anything else now means a fatal error.
+         */
+        if (ppcb_arg.cpPassPhraseCur == NULL) {
+            if (ppcb_arg.nPassPhraseDialogCur && pkey_mtime &&
+                !isatty(fileno(stdout))) /* XXX: apr_isatty() */
+            {
+                ap_log_error(APLOG_MARK, APLOG_ERR, 0,
+                             s, APLOGNO(02578)
+                             "Init: Unable to read pass phrase "
+                             "[Hint: key introduced or changed "
+                             "before restart?]");
+                ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
             }
             else {
-                if (cpPassPhraseCur != NULL) {
-                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
-                                 pServ, 
-                                 "encrypted %s private key - pass phrase "
-                                 "requested", an);
-                }
-                else {
-                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
-                                 pServ, 
-                                 "encrypted %s private key - pass phrase"
-                                 " reused", an);
-                }
+                ap_log_error(APLOG_MARK, APLOG_ERR, 0,
+                             s, APLOGNO(02579) "Init: Private key not found");
+                ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
             }
-
-            /*
-             * Ok, when we have one more pass phrase store it
-             */
-            if (cpPassPhraseCur != NULL) {
-                cpp = (char **)apr_array_push(aPassPhrase);
-                *cpp = cpPassPhraseCur;
-                nPassPhrase++;
+            if (writetty) {
+                apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
+                apr_file_printf(writetty, "**Stopped\n");
             }
-
-            /*
-             * Insert private key into the global module configuration
-             * (we convert it to a stand-alone DER byte sequence
-             * because the SSL library uses static variables inside a
-             * RSA structure which do not survive DSO reloads!)
-             */
-            cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
-            length = i2d_PrivateKey(pPrivateKey, NULL);
-            ucp = ssl_asn1_table_set(mc->tPrivateKey, cp, length);
-            (void)i2d_PrivateKey(pPrivateKey, &ucp); /* 2nd arg increments */
-
-            if (nPassPhraseDialogCur != 0) {
-                /* remember mtime of encrypted keys */
-                asn1 = ssl_asn1_table_get(mc->tPrivateKey, cp);
-                asn1->source_mtime = pkey_mtime;
+        }
+        else {
+            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02580)
+                         "Init: Pass phrase incorrect for key %s",
+                         key_id);
+            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
+
+            if (writetty) {
+                apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
+                apr_file_printf(writetty, "**Stopped\n");
             }
+        }
+        return ssl_die(s);
+    }
 
-            /*
-             * Free the private key structure
-             */
-            EVP_PKEY_free(pPrivateKey);
+    if (pPrivateKey == NULL) {
+        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02581)
+                     "Init: Unable to read server private key from file %s",
+                     ppcb_arg.pkey_file);
+        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
+        return ssl_die(s);
+    }
+
+    /*
+     * Log the type of reading
+     */
+    if (ppcb_arg.nPassPhraseDialogCur == 0) {
+        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02582)
+                     "unencrypted %s private key - pass phrase not "
+                     "required", key_id);
+    }
+    else {
+        if (ppcb_arg.cpPassPhraseCur != NULL) {
+            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
+                         s, APLOGNO(02583)
+                         "encrypted %s private key - pass phrase "
+                         "requested", key_id);
+        }
+        else {
+            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
+                         s, APLOGNO(02584)
+                         "encrypted %s private key - pass phrase"
+                         " reused", key_id);
         }
     }
 
+    /*
+     * Ok, when we have one more pass phrase store it
+     */
+    if (ppcb_arg.cpPassPhraseCur != NULL) {
+        *(const char **)apr_array_push(ppcb_arg.aPassPhrase) =
+            ppcb_arg.cpPassPhraseCur;
+        nPassPhrase++;
+    }
+
+    /* Cache the private key in the global module configuration so it
+     * can be used after subsequent reloads. */
+    asn1 = ssl_asn1_table_set(mc->tPrivateKey, key_id, pPrivateKey);
+
+    if (ppcb_arg.nPassPhraseDialogCur != 0) {
+        /* remember mtime of encrypted keys */
+        asn1->source_mtime = pkey_mtime;
+    }
+
+    /*
+     * Free the private key structure
+     */
+    EVP_PKEY_free(pPrivateKey);
+
     /*
      * Let the user know when we're successful.
      */
-    if (nPassPhraseDialog > 0) {
-        sc = mySrvConfig(s);
+    if ((ppcb_arg.nPassPhraseDialog > 0) &&
+        (ppcb_arg.cpPassPhraseCur != NULL)) {
         if (writetty) {
             apr_file_printf(writetty, "\n"
                             "OK: Pass Phrase Dialog successful.\n");
         }
     }
 
-    /*
-     * Wipe out the used memory from the
-     * pass phrase array and then deallocate it
-     */
-    if (aPassPhrase->nelts) {
-        pphrase_array_clear(aPassPhrase);
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
-                     "Init: Wiped out the queried pass phrases from memory");
-    }
-
     /* Close the pipes if they were opened
      */
     if (readtty) {
@@ -546,7 +375,8 @@ void ssl_pphrase_Handle(server_rec *s, apr_pool_t *p)
         apr_file_close(writetty);
         readtty = writetty = NULL;
     }
-    return;
+
+    return APR_SUCCESS;
 }
 
 static apr_status_t ssl_pipe_child_create(apr_pool_t *p, const char *progname)
@@ -565,12 +395,10 @@ static apr_status_t ssl_pipe_child_create(apr_pool_t *p, const char *progname)
                                    APR_FULL_BLOCK,
                                    APR_NO_PIPE)) == APR_SUCCESS)) {
         char **args;
-        const char *pname;
-        
+
         apr_tokenize_to_argv(progname, &args, p);
-        pname = apr_pstrdup(p, args[0]);
         procnew = (apr_proc_t *)apr_pcalloc(p, sizeof(*procnew));
-        rc = apr_proc_create(procnew, pname, (const char * const *)args,
+        rc = apr_proc_create(procnew, args[0], (const char * const *)args,
                              NULL, procattr, p);
         if (rc == APR_SUCCESS) {
             /* XXX: not sure if we aught to...
@@ -594,70 +422,38 @@ static int pipe_get_passwd_cb(char *buf, int length, char *prompt, int verify)
     buf[0]='\0';
     rc = apr_file_gets(buf, length, readtty);
     apr_file_puts(APR_EOL_STR, writetty);
-    
+
     if (rc != APR_SUCCESS || apr_file_eof(readtty)) {
-       memset(buf, 0, length);
+        memset(buf, 0, length);
         return 1;  /* failure */
     }
     if ((p = strchr(buf, '\n')) != NULL) {
-       *p = '\0';
+        *p = '\0';
     }
 #ifdef WIN32
     /* XXX: apr_sometest */
     if ((p = strchr(buf, '\r')) != NULL) {
-       *p = '\0';
+        *p = '\0';
     }
 #endif
     return 0;
 }
 
-#ifdef SSLC_VERSION_NUMBER
-int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify)
-{
-    void *srv = ssl_pphrase_server_rec;
-#else
 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
 {
-#endif
-    SSLModConfigRec *mc;
-    server_rec *s;
-    apr_pool_t *p;
-    apr_array_header_t *aPassPhrase;
-    SSLSrvConfigRec *sc;
-    int *pnPassPhraseCur;
-    char **cppPassPhraseCur;
-    char *cpVHostID;
-    char *cpAlgoType;
-    int *pnPassPhraseDialog;
-    int *pnPassPhraseDialogCur;
-    BOOL *pbPassPhraseDialogOnce;
+    pphrase_cb_arg_t *ppcb_arg = (pphrase_cb_arg_t *)srv;
+    SSLSrvConfigRec *sc = mySrvConfig(ppcb_arg->s);
     char *cpp;
     int len = -1;
 
-    mc = myModConfig((server_rec *)srv);
-
-    /*
-     * Reconnect to the context of ssl_phrase_Handle()
-     */
-    s                      = myCtxVarGet(mc,  1, server_rec *);
-    p                      = myCtxVarGet(mc,  2, apr_pool_t *);
-    aPassPhrase            = myCtxVarGet(mc,  3, apr_array_header_t *);
-    pnPassPhraseCur        = myCtxVarGet(mc,  4, int *);
-    cppPassPhraseCur       = myCtxVarGet(mc,  5, char **);
-    cpVHostID              = myCtxVarGet(mc,  6, char *);
-    cpAlgoType             = myCtxVarGet(mc,  7, char *);
-    pnPassPhraseDialog     = myCtxVarGet(mc,  8, int *);
-    pnPassPhraseDialogCur  = myCtxVarGet(mc,  9, int *);
-    pbPassPhraseDialogOnce = myCtxVarGet(mc, 10, BOOL *);
-    sc                     = mySrvConfig(s);
-
-    (*pnPassPhraseDialog)++;
-    (*pnPassPhraseDialogCur)++;
+    ppcb_arg->nPassPhraseDialog++;
+    ppcb_arg->nPassPhraseDialogCur++;
 
     /*
      * When remembered pass phrases are available use them...
      */
-    if ((cpp = pphrase_array_get(aPassPhrase, *pnPassPhraseCur)) != NULL) {
+    if ((cpp = pphrase_array_get(ppcb_arg->aPassPhrase,
+                                 ppcb_arg->nPassPhraseCur)) != NULL) {
         apr_cpystrn(buf, cpp, bufsize);
         len = strlen(buf);
         return len;
@@ -673,25 +469,29 @@ int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
 
         if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
             if (!readtty) {
-                ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
+                ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s,
+                             APLOGNO(01965)
                              "Init: Creating pass phrase dialog pipe child "
                              "'%s'", sc->server->pphrase_dialog_path);
-               if (ssl_pipe_child_create(p, sc->server->pphrase_dialog_path)
+                if (ssl_pipe_child_create(ppcb_arg->p,
+                                          sc->server->pphrase_dialog_path)
                         != APR_SUCCESS) {
-                    ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
+                    ap_log_error(APLOG_MARK, APLOG_ERR, 0, ppcb_arg->s,
+                                 APLOGNO(01966)
                                  "Init: Failed to create pass phrase pipe '%s'",
                                  sc->server->pphrase_dialog_path);
-                    PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
+                    PEMerr(PEM_F_PEM_DEF_CALLBACK,
+                           PEM_R_PROBLEMS_GETTING_PASSWORD);
                     memset(buf, 0, (unsigned int)bufsize);
                     return (-1);
                 }
             }
-            ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
+            ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s, APLOGNO(01967)
                          "Init: Requesting pass phrase via piped dialog");
         }
-        else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */ 
+        else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
 #ifdef WIN32
-            PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
+            PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
             memset(buf, 0, (unsigned int)bufsize);
             return (-1);
 #else
@@ -701,9 +501,9 @@ int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
              * we print the prompt to stdout before EVP_read_pw_string turns
              * off tty echo
              */
-            apr_file_open_stdout(&writetty, p);
+            apr_file_open_stdout(&writetty, ppcb_arg->p);
 
-            ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
+            ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s, APLOGNO(01968)
                          "Init: Requesting pass phrase via builtin terminal "
                          "dialog");
 #endif
@@ -715,16 +515,17 @@ int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
          * this terminal dialog and why to the hell he has to enter
          * something...
          */
-        if (*pnPassPhraseDialog == 1) {
-            apr_file_printf(writetty, "%s mod_ssl/%s (Pass Phrase Dialog)\n",
-                            AP_SERVER_BASEVERSION, MOD_SSL_VERSION);
+        if (ppcb_arg->nPassPhraseDialog == 1) {
+            apr_file_printf(writetty, "%s mod_ssl (Pass Phrase Dialog)\n",
+                            AP_SERVER_BASEVERSION);
             apr_file_printf(writetty, "Some of your private key files are encrypted for security reasons.\n");
             apr_file_printf(writetty, "In order to read them you have to provide the pass phrases.\n");
         }
-        if (*pbPassPhraseDialogOnce) {
-            *pbPassPhraseDialogOnce = FALSE;
+        if (ppcb_arg->bPassPhraseDialogOnce) {
+            ppcb_arg->bPassPhraseDialogOnce = FALSE;
             apr_file_printf(writetty, "\n");
-            apr_file_printf(writetty, "Server %s (%s)\n", cpVHostID, cpAlgoType);
+            apr_file_printf(writetty, "Private key %s (%s)\n",
+                            ppcb_arg->key_id, ppcb_arg->pkey_file);
         }
 
         /*
@@ -736,13 +537,13 @@ int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
         for (;;) {
             apr_file_puts(prompt, writetty);
             if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
-                i = pipe_get_passwd_cb(buf, bufsize, "", FALSE); 
-            }  
+                i = pipe_get_passwd_cb(buf, bufsize, "", FALSE);
+            }
             else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
-                i = EVP_read_pw_string(buf, bufsize, "", FALSE); 
-            }  
+                i = EVP_read_pw_string(buf, bufsize, "", FALSE);
+            }
             if (i != 0) {
-                PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
+                PEMerr(PEM_F_PEM_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
                 memset(buf, 0, (unsigned int)bufsize);
                 return (-1);
             }
@@ -759,19 +560,18 @@ int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
      */
     else if (sc->server->pphrase_dialog_type == SSL_PPTYPE_FILTER) {
         const char *cmd = sc->server->pphrase_dialog_path;
-        const char **argv = apr_palloc(p, sizeof(char *) * 4);
+        const char **argv = apr_palloc(ppcb_arg->p, sizeof(char *) * 3);
         char *result;
 
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
+        ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s, APLOGNO(01969)
                      "Init: Requesting pass phrase from dialog filter "
                      "program (%s)", cmd);
 
         argv[0] = cmd;
-        argv[1] = cpVHostID;
-        argv[2] = cpAlgoType;
-        argv[3] = NULL;
+        argv[1] = ppcb_arg->key_id;
+        argv[2] = NULL;
 
-        result = ssl_util_readfilter(s, p, cmd, argv);
+        result = ssl_util_readfilter(ppcb_arg->s, ppcb_arg->p, cmd, argv);
         apr_cpystrn(buf, result, bufsize);
         len = strlen(buf);
     }
@@ -779,11 +579,73 @@ int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
     /*
      * Ok, we now have the pass phrase, so give it back
      */
-    *cppPassPhraseCur = apr_pstrdup(p, buf);
+    ppcb_arg->cpPassPhraseCur = apr_pstrdup(ppcb_arg->p, buf);
 
     /*
-     * And return it's length to OpenSSL...
+     * And return its length to OpenSSL...
      */
     return (len);
 }
 
+#if defined(HAVE_OPENSSL_ENGINE_H) && defined(HAVE_ENGINE_INIT)
+apr_status_t modssl_load_engine_keypair(server_rec *s, apr_pool_t *p,
+                                        const char *certid, const char *keyid,
+                                        X509 **pubkey, EVP_PKEY **privkey)
+{
+    SSLModConfigRec *mc = myModConfig(s);
+    ENGINE *e;
+    UI_METHOD *ui_method;
+
+    if (!mc->szCryptoDevice) {
+        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10131)
+                     "Init: Cannot load private key `%s' without engine",
+                     keyid);
+        return ssl_die(s);
+    }
+
+    /*
+     * Using the builtin OpenSSL UI only, for now...
+     */
+    ui_method = UI_OpenSSL();
+
+    if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
+        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10132)
+                     "Init: Failed to load Crypto Device API `%s'",
+                     mc->szCryptoDevice);
+        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
+        return ssl_die(s);
+    }
+
+    if (APLOGdebug(s)) {
+        ENGINE_ctrl_cmd_string(e, "VERBOSE", NULL, 0);
+    }
+
+    if (certid) {
+        struct {
+            const char *cert_id;
+            X509 *cert;
+        } params = { certid, NULL };
+
+        if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &params, NULL, 1)) {
+            ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10136)
+                         "Init: Unable to get the certificate");
+            ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
+            return ssl_die(s);
+        }
+
+        *pubkey = params.cert;
+    }
+
+    *privkey = ENGINE_load_private_key(e, keyid, ui_method, NULL);
+    if (*privkey == NULL) {
+        ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(10133)
+                     "Init: Unable to get the private key");
+        ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
+        return ssl_die(s);
+    }
+
+    ENGINE_free(e);
+
+    return APR_SUCCESS;
+}
+#endif