summaryrefslogtreecommitdiff
path: root/crypto
diff options
context:
space:
mode:
Diffstat (limited to 'crypto')
-rw-r--r--crypto/apr_crypto.c95
-rw-r--r--crypto/apr_crypto_commoncrypto.c906
-rw-r--r--crypto/apr_crypto_nss.c421
-rw-r--r--crypto/apr_crypto_openssl.c357
-rw-r--r--crypto/apr_siphash.c196
-rw-r--r--crypto/crypt_blowfish.c6
6 files changed, 1782 insertions, 199 deletions
diff --git a/crypto/apr_crypto.c b/crypto/apr_crypto.c
index fe66582d124fe..9e6e0beebec67 100644
--- a/crypto/apr_crypto.c
+++ b/crypto/apr_crypto.c
@@ -120,7 +120,7 @@ static apr_status_t crypto_clear(void *ptr)
{
apr_crypto_clear_t *clear = (apr_crypto_clear_t *)ptr;
- memset(clear->buffer, 0, clear->size);
+ apr_crypto_memzero(clear->buffer, clear->size);
clear->buffer = NULL;
clear->size = 0;
@@ -141,6 +141,53 @@ APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool,
return APR_SUCCESS;
}
+#if defined(HAVE_WEAK_SYMBOLS)
+void apr__memzero_explicit(void *buffer, apr_size_t size);
+
+__attribute__ ((weak))
+void apr__memzero_explicit(void *buffer, apr_size_t size)
+{
+ memset(buffer, 0, size);
+}
+#endif
+
+APU_DECLARE(apr_status_t) apr_crypto_memzero(void *buffer, apr_size_t size)
+{
+#if defined(WIN32)
+ SecureZeroMemory(buffer, size);
+#elif defined(HAVE_MEMSET_S)
+ if (size) {
+ return memset_s(buffer, (rsize_t)size, 0, (rsize_t)size);
+ }
+#elif defined(HAVE_EXPLICIT_BZERO)
+ explicit_bzero(buffer, size);
+#elif defined(HAVE_WEAK_SYMBOLS)
+ apr__memzero_explicit(buffer, size);
+#else
+ apr_size_t i;
+ volatile unsigned char *volatile ptr = buffer;
+ for (i = 0; i < size; ++i) {
+ ptr[i] = 0;
+ }
+#endif
+ return APR_SUCCESS;
+}
+
+APU_DECLARE(int) apr_crypto_equals(const void *buf1, const void *buf2,
+ apr_size_t size)
+{
+ const unsigned char *p1 = buf1;
+ const unsigned char *p2 = buf2;
+ unsigned char diff = 0;
+ apr_size_t i;
+
+ for (i = 0; i < size; ++i) {
+ diff |= p1[i] ^ p2[i];
+ }
+
+ return 1 & ((diff - 1) >> 8);
+}
+
APU_DECLARE(apr_status_t) apr_crypto_get_driver(
const apr_crypto_driver_t **driver, const char *name,
const char *params, const apu_err_t **result, apr_pool_t *pool)
@@ -188,12 +235,15 @@ APU_DECLARE(apr_status_t) apr_crypto_get_driver(
apr_snprintf(symname, sizeof(symname), "apr_crypto_%s_driver", name);
rv = apu_dso_load(&dso, &symbol, modname, symname, pool);
if (rv == APR_SUCCESS || rv == APR_EINIT) { /* previously loaded?!? */
- *driver = symbol;
- name = apr_pstrdup(pool, name);
- apr_hash_set(drivers, name, APR_HASH_KEY_STRING, *driver);
+ apr_crypto_driver_t *d = symbol;
rv = APR_SUCCESS;
- if ((*driver)->init) {
- rv = (*driver)->init(pool, params, result);
+ if (d->init) {
+ rv = d->init(pool, params, result);
+ }
+ if (APR_SUCCESS == rv) {
+ *driver = symbol;
+ name = apr_pstrdup(pool, name);
+ apr_hash_set(drivers, name, APR_HASH_KEY_STRING, *driver);
}
}
apu_dso_mutex_unlock();
@@ -223,6 +273,11 @@ APU_DECLARE(apr_status_t) apr_crypto_get_driver(
DRIVER_LOAD("nss", apr_crypto_nss_driver, pool, params, rv, result);
}
#endif
+#if APU_HAVE_COMMONCRYPTO
+ if (name[0] == 'c' && !strcmp(name, "commoncrypto")) {
+ DRIVER_LOAD("commoncrypto", apr_crypto_commoncrypto_driver, pool, params, rv, result);
+ }
+#endif
#if APU_HAVE_MSCAPI
if (name[0] == 'm' && !strcmp(name, "mscapi")) {
DRIVER_LOAD("mscapi", apr_crypto_mscapi_driver, pool, params, rv, result);
@@ -287,7 +342,8 @@ APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f,
/**
* @brief Get a hash table of key types, keyed by the name of the type against
- * an integer pointer constant.
+ * a pointer to apr_crypto_block_key_type_t, which in turn begins with an
+ * integer.
*
* @param types - hashtable of key types keyed to constants.
* @param f - encryption context
@@ -301,7 +357,8 @@ APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types,
/**
* @brief Get a hash table of key modes, keyed by the name of the mode against
- * an integer pointer constant.
+ * a pointer to apr_crypto_block_key_mode_t, which in turn begins with an
+ * integer.
*
* @param modes - hashtable of key modes keyed to constants.
* @param f - encryption context
@@ -314,6 +371,28 @@ APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes,
}
/**
+ * @brief Create a key from the provided secret or passphrase. The key is cleaned
+ * up when the context is cleaned, and may be reused with multiple encryption
+ * or decryption operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param rec The key record, from which the key will be derived.
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+APU_DECLARE(apr_status_t) apr_crypto_key(apr_crypto_key_t **key,
+ const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p)
+{
+ return f->provider->key(key, rec, f, p);
+}
+
+/**
* @brief Create a key from the given passphrase. By default, the PBKDF2
* algorithm is used to generate the key from the passphrase. It is expected
* that the same pass phrase will generate the same key, regardless of the
diff --git a/crypto/apr_crypto_commoncrypto.c b/crypto/apr_crypto_commoncrypto.c
new file mode 100644
index 0000000000000..81b02995843ea
--- /dev/null
+++ b/crypto/apr_crypto_commoncrypto.c
@@ -0,0 +1,906 @@
+/* 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "apr.h"
+#include "apr_lib.h"
+#include "apu.h"
+#include "apu_errno.h"
+
+#include <ctype.h>
+#include <assert.h>
+#include <stdlib.h>
+
+#include "apr_strings.h"
+#include "apr_time.h"
+#include "apr_buckets.h"
+#include "apr_random.h"
+
+#include "apr_crypto_internal.h"
+
+#if APU_HAVE_CRYPTO
+
+#include <CommonCrypto/CommonCrypto.h>
+
+#define LOG_PREFIX "apr_crypto_commoncrypto: "
+
+struct apr_crypto_t
+{
+ apr_pool_t *pool;
+ const apr_crypto_driver_t *provider;
+ apu_err_t *result;
+ apr_hash_t *types;
+ apr_hash_t *modes;
+ apr_random_t *rng;
+};
+
+struct apr_crypto_key_t
+{
+ apr_pool_t *pool;
+ const apr_crypto_driver_t *provider;
+ const apr_crypto_t *f;
+ CCAlgorithm algorithm;
+ CCOptions options;
+ unsigned char *key;
+ int keyLen;
+ int ivSize;
+ apr_size_t blockSize;
+};
+
+struct apr_crypto_block_t
+{
+ apr_pool_t *pool;
+ const apr_crypto_driver_t *provider;
+ const apr_crypto_t *f;
+ const apr_crypto_key_t *key;
+ CCCryptorRef ref;
+};
+
+static struct apr_crypto_block_key_type_t key_types[] =
+{
+{ APR_KEY_3DES_192, 24, 8, 8 },
+{ APR_KEY_AES_128, 16, 16, 16 },
+{ APR_KEY_AES_192, 24, 16, 16 },
+{ APR_KEY_AES_256, 32, 16, 16 } };
+
+static struct apr_crypto_block_key_mode_t key_modes[] =
+{
+{ APR_MODE_ECB },
+{ APR_MODE_CBC } };
+
+/**
+ * Fetch the most recent error from this driver.
+ */
+static apr_status_t crypto_error(const apu_err_t **result,
+ const apr_crypto_t *f)
+{
+ *result = f->result;
+ return APR_SUCCESS;
+}
+
+/**
+ * Shutdown the crypto library and release resources.
+ */
+static apr_status_t crypto_shutdown(void)
+{
+ return APR_SUCCESS;
+}
+
+static apr_status_t crypto_shutdown_helper(void *data)
+{
+ return crypto_shutdown();
+}
+
+/**
+ * Initialise the crypto library and perform one time initialisation.
+ */
+static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
+ const apu_err_t **result)
+{
+
+ apr_pool_cleanup_register(pool, pool, crypto_shutdown_helper,
+ apr_pool_cleanup_null);
+
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Clean encryption / decryption context.
+ * @note After cleanup, a context is free to be reused if necessary.
+ * @param ctx The block context to use.
+ * @return Returns APR_ENOTIMPL if not supported.
+ */
+static apr_status_t crypto_block_cleanup(apr_crypto_block_t *ctx)
+{
+
+ if (ctx->ref) {
+ CCCryptorRelease(ctx->ref);
+ ctx->ref = NULL;
+ }
+
+ return APR_SUCCESS;
+
+}
+
+static apr_status_t crypto_block_cleanup_helper(void *data)
+{
+ apr_crypto_block_t *block = (apr_crypto_block_t *) data;
+ return crypto_block_cleanup(block);
+}
+
+/**
+ * @brief Clean encryption / decryption context.
+ * @note After cleanup, a context is free to be reused if necessary.
+ * @param f The context to use.
+ * @return Returns APR_ENOTIMPL if not supported.
+ */
+static apr_status_t crypto_cleanup(apr_crypto_t *f)
+{
+
+ return APR_SUCCESS;
+
+}
+
+static apr_status_t crypto_cleanup_helper(void *data)
+{
+ apr_crypto_t *f = (apr_crypto_t *) data;
+ return crypto_cleanup(f);
+}
+
+/**
+ * @brief Create a context for supporting encryption. Keys, certificates,
+ * algorithms and other parameters will be set per context. More than
+ * one context can be created at one time. A cleanup will be automatically
+ * registered with the given pool to guarantee a graceful shutdown.
+ * @param f - context pointer will be written here
+ * @param provider - provider to use
+ * @param params - array of key parameters
+ * @param pool - process pool
+ * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE
+ * if the engine cannot be initialised.
+ */
+static apr_status_t crypto_make(apr_crypto_t **ff,
+ const apr_crypto_driver_t *provider, const char *params,
+ apr_pool_t *pool)
+{
+ apr_crypto_t *f = apr_pcalloc(pool, sizeof(apr_crypto_t));
+ apr_status_t rv;
+
+ if (!f) {
+ return APR_ENOMEM;
+ }
+ *ff = f;
+ f->pool = pool;
+ f->provider = provider;
+
+ /* seed the secure random number generator */
+ f->rng = apr_random_standard_new(pool);
+ if (!f->rng) {
+ return APR_ENOMEM;
+ }
+ do {
+ unsigned char seed[8];
+ rv = apr_generate_random_bytes(seed, sizeof(seed));
+ if (rv != APR_SUCCESS) {
+ return rv;
+ }
+ apr_random_add_entropy(f->rng, seed, sizeof(seed));
+ rv = apr_random_secure_ready(f->rng);
+ } while (rv == APR_ENOTENOUGHENTROPY);
+
+ f->result = apr_pcalloc(pool, sizeof(apu_err_t));
+ if (!f->result) {
+ return APR_ENOMEM;
+ }
+
+ f->types = apr_hash_make(pool);
+ if (!f->types) {
+ return APR_ENOMEM;
+ }
+ apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_types[0]));
+ apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_types[1]));
+ apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_types[2]));
+ apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_types[3]));
+
+ f->modes = apr_hash_make(pool);
+ if (!f->modes) {
+ return APR_ENOMEM;
+ }
+ apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(key_modes[0]));
+ apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(key_modes[1]));
+
+ apr_pool_cleanup_register(pool, f, crypto_cleanup_helper,
+ apr_pool_cleanup_null);
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * @brief Get a hash table of key types, keyed by the name of the type against
+ * a pointer to apr_crypto_block_key_type_t.
+ *
+ * @param types - hashtable of key types keyed to constants.
+ * @param f - encryption context
+ * @return APR_SUCCESS for success
+ */
+static apr_status_t crypto_get_block_key_types(apr_hash_t **types,
+ const apr_crypto_t *f)
+{
+ *types = f->types;
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Get a hash table of key modes, keyed by the name of the mode against
+ * a pointer to apr_crypto_block_key_mode_t.
+ *
+ * @param modes - hashtable of key modes keyed to constants.
+ * @param f - encryption context
+ * @return APR_SUCCESS for success
+ */
+static apr_status_t crypto_get_block_key_modes(apr_hash_t **modes,
+ const apr_crypto_t *f)
+{
+ *modes = f->modes;
+ return APR_SUCCESS;
+}
+
+/*
+ * Work out which mechanism to use.
+ */
+static apr_status_t crypto_cipher_mechanism(apr_crypto_key_t *key,
+ const apr_crypto_block_key_type_e type,
+ const apr_crypto_block_key_mode_e mode, const int doPad, apr_pool_t *p)
+{
+ /* handle padding */
+ key->options = doPad ? kCCOptionPKCS7Padding : 0;
+
+ /* determine the algorithm to be used */
+ switch (type) {
+
+ case (APR_KEY_3DES_192):
+
+ /* A 3DES key */
+ if (mode == APR_MODE_CBC) {
+ key->algorithm = kCCAlgorithm3DES;
+ key->keyLen = kCCKeySize3DES;
+ key->ivSize = kCCBlockSize3DES;
+ key->blockSize = kCCBlockSize3DES;
+ }
+ else {
+ key->algorithm = kCCAlgorithm3DES;
+ key->options += kCCOptionECBMode;
+ key->keyLen = kCCKeySize3DES;
+ key->ivSize = 0;
+ key->blockSize = kCCBlockSize3DES;
+ }
+ break;
+
+ case (APR_KEY_AES_128):
+
+ if (mode == APR_MODE_CBC) {
+ key->algorithm = kCCAlgorithmAES128;
+ key->keyLen = kCCKeySizeAES128;
+ key->ivSize = kCCBlockSizeAES128;
+ key->blockSize = kCCBlockSizeAES128;
+ }
+ else {
+ key->algorithm = kCCAlgorithmAES128;
+ key->options += kCCOptionECBMode;
+ key->keyLen = kCCKeySizeAES128;
+ key->ivSize = 0;
+ key->blockSize = kCCBlockSizeAES128;
+ }
+ break;
+
+ case (APR_KEY_AES_192):
+
+ if (mode == APR_MODE_CBC) {
+ key->algorithm = kCCAlgorithmAES128;
+ key->keyLen = kCCKeySizeAES192;
+ key->ivSize = kCCBlockSizeAES128;
+ key->blockSize = kCCBlockSizeAES128;
+ }
+ else {
+ key->algorithm = kCCAlgorithmAES128;
+ key->options += kCCOptionECBMode;
+ key->keyLen = kCCKeySizeAES192;
+ key->ivSize = 0;
+ key->blockSize = kCCBlockSizeAES128;
+ }
+ break;
+
+ case (APR_KEY_AES_256):
+
+ if (mode == APR_MODE_CBC) {
+ key->algorithm = kCCAlgorithmAES128;
+ key->keyLen = kCCKeySizeAES256;
+ key->ivSize = kCCBlockSizeAES128;
+ key->blockSize = kCCBlockSizeAES128;
+ }
+ else {
+ key->algorithm = kCCAlgorithmAES128;
+ key->options += kCCOptionECBMode;
+ key->keyLen = kCCKeySizeAES256;
+ key->ivSize = 0;
+ key->blockSize = kCCBlockSizeAES128;
+ }
+ break;
+
+ default:
+
+ /* TODO: Support CAST, Blowfish */
+
+ /* unknown key type, give up */
+ return APR_EKEYTYPE;
+
+ }
+
+ /* make space for the key */
+ key->key = apr_palloc(p, key->keyLen);
+ if (!key->key) {
+ return APR_ENOMEM;
+ }
+ apr_crypto_clear(p, key->key, key->keyLen);
+
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Create a key from the provided secret or passphrase. The key is cleaned
+ * up when the context is cleaned, and may be reused with multiple encryption
+ * or decryption operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param rec The key record, from which the key will be derived.
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_key(apr_crypto_key_t **k,
+ const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p)
+{
+ apr_status_t rv;
+ apr_crypto_key_t *key = *k;
+
+ if (!key) {
+ *k = key = apr_pcalloc(p, sizeof *key);
+ }
+ if (!key) {
+ return APR_ENOMEM;
+ }
+
+ key->f = f;
+ key->provider = f->provider;
+
+ /* decide on what cipher mechanism we will be using */
+ rv = crypto_cipher_mechanism(key, rec->type, rec->mode, rec->pad, p);
+ if (APR_SUCCESS != rv) {
+ return rv;
+ }
+
+ switch (rec->ktype) {
+
+ case APR_CRYPTO_KTYPE_PASSPHRASE: {
+
+ /* generate the key */
+ if ((f->result->rc = CCKeyDerivationPBKDF(kCCPBKDF2,
+ rec->k.passphrase.pass, rec->k.passphrase.passLen,
+ rec->k.passphrase.salt, rec->k.passphrase.saltLen,
+ kCCPRFHmacAlgSHA1, rec->k.passphrase.iterations, key->key,
+ key->keyLen)) == kCCParamError) {
+ return APR_ENOKEY;
+ }
+
+ break;
+ }
+
+ case APR_CRYPTO_KTYPE_SECRET: {
+
+ /* sanity check - key correct size? */
+ if (rec->k.secret.secretLen != key->keyLen) {
+ return APR_EKEYLENGTH;
+ }
+
+ /* copy the key */
+ memcpy(key->key, rec->k.secret.secret, rec->k.secret.secretLen);
+
+ break;
+ }
+
+ default: {
+
+ return APR_ENOKEY;
+
+ }
+ }
+
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Create a key from the given passphrase. By default, the PBKDF2
+ * algorithm is used to generate the key from the passphrase. It is expected
+ * that the same pass phrase will generate the same key, regardless of the
+ * backend crypto platform used. The key is cleaned up when the context
+ * is cleaned, and may be reused with multiple encryption or decryption
+ * operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param ivSize The size of the initialisation vector will be returned, based
+ * on whether an IV is relevant for this type of crypto.
+ * @param pass The passphrase to use.
+ * @param passLen The passphrase length in bytes
+ * @param salt The salt to use.
+ * @param saltLen The salt length in bytes
+ * @param type 3DES_192, AES_128, AES_192, AES_256.
+ * @param mode Electronic Code Book / Cipher Block Chaining.
+ * @param doPad Pad if necessary.
+ * @param iterations Iteration count
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
+ const char *pass, apr_size_t passLen, const unsigned char * salt,
+ apr_size_t saltLen, const apr_crypto_block_key_type_e type,
+ const apr_crypto_block_key_mode_e mode, const int doPad,
+ const int iterations, const apr_crypto_t *f, apr_pool_t *p)
+{
+ apr_status_t rv;
+ apr_crypto_key_t *key = *k;
+
+ if (!key) {
+ *k = key = apr_pcalloc(p, sizeof *key);
+ if (!key) {
+ return APR_ENOMEM;
+ }
+ }
+
+ key->f = f;
+ key->provider = f->provider;
+
+ /* decide on what cipher mechanism we will be using */
+ rv = crypto_cipher_mechanism(key, type, mode, doPad, p);
+ if (APR_SUCCESS != rv) {
+ return rv;
+ }
+
+ /* generate the key */
+ if ((f->result->rc = CCKeyDerivationPBKDF(kCCPBKDF2, pass, passLen, salt,
+ saltLen, kCCPRFHmacAlgSHA1, iterations, key->key, key->keyLen))
+ == kCCParamError) {
+ return APR_ENOKEY;
+ }
+
+ if (ivSize) {
+ *ivSize = key->ivSize;
+ }
+
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Initialise a context for encrypting arbitrary data using the given key.
+ * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
+ * *ctx is not NULL, *ctx must point at a previously created structure.
+ * @param ctx The block context returned, see note.
+ * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
+ * an IV will be created at random, in space allocated from the pool.
+ * If the buffer pointed to is not NULL, the IV in the buffer will be
+ * used.
+ * @param key The key structure.
+ * @param blockSize The block size of the cipher.
+ * @param p The pool to use.
+ * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
+ * Returns APR_EINIT if the backend failed to initialise the context. Returns
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
+ const unsigned char **iv, const apr_crypto_key_t *key,
+ apr_size_t *blockSize, apr_pool_t *p)
+{
+ unsigned char *usedIv;
+ apr_crypto_block_t *block = *ctx;
+ if (!block) {
+ *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
+ }
+ if (!block) {
+ return APR_ENOMEM;
+ }
+ block->f = key->f;
+ block->pool = p;
+ block->provider = key->provider;
+ block->key = key;
+
+ apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
+ apr_pool_cleanup_null);
+
+ /* generate an IV, if necessary */
+ usedIv = NULL;
+ if (key->ivSize) {
+ if (iv == NULL) {
+ return APR_ENOIV;
+ }
+ if (*iv == NULL) {
+ apr_status_t status;
+ usedIv = apr_pcalloc(p, key->ivSize);
+ if (!usedIv) {
+ return APR_ENOMEM;
+ }
+ apr_crypto_clear(p, usedIv, key->ivSize);
+ status = apr_random_secure_bytes(block->f->rng, usedIv,
+ key->ivSize);
+ if (APR_SUCCESS != status) {
+ return status;
+ }
+ *iv = usedIv;
+ }
+ else {
+ usedIv = (unsigned char *) *iv;
+ }
+ }
+
+ /* create a new context for encryption */
+ switch ((block->f->result->rc = CCCryptorCreate(kCCEncrypt, key->algorithm,
+ key->options, key->key, key->keyLen, usedIv, &block->ref))) {
+ case kCCSuccess: {
+ break;
+ }
+ case kCCParamError: {
+ return APR_EINIT;
+ }
+ case kCCMemoryFailure: {
+ return APR_ENOMEM;
+ }
+ case kCCAlignmentError: {
+ return APR_EPADDING;
+ }
+ case kCCUnimplemented: {
+ return APR_ENOTIMPL;
+ }
+ default: {
+ return APR_EINIT;
+ }
+ }
+
+ if (blockSize) {
+ *blockSize = key->blockSize;
+ }
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * @brief Encrypt data provided by in, write it to out.
+ * @note The number of bytes written will be written to outlen. If
+ * out is NULL, outlen will contain the maximum size of the
+ * buffer needed to hold the data, including any data
+ * generated by apr_crypto_block_encrypt_finish below. If *out points
+ * to NULL, a buffer sufficiently large will be created from
+ * the pool provided. If *out points to a not-NULL value, this
+ * value will be used as a buffer instead.
+ * @param out Address of a buffer to which data will be written,
+ * see note.
+ * @param outlen Length of the output will be written here.
+ * @param in Address of the buffer to read.
+ * @param inlen Length of the buffer to read.
+ * @param ctx The block context to use.
+ * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
+ * not implemented.
+ */
+static apr_status_t crypto_block_encrypt(unsigned char **out,
+ apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
+ apr_crypto_block_t *ctx)
+{
+ apr_size_t outl = *outlen;
+ unsigned char *buffer;
+
+ /* are we after the maximum size of the out buffer? */
+ if (!out) {
+ *outlen = CCCryptorGetOutputLength(ctx->ref, inlen, 1);
+ return APR_SUCCESS;
+ }
+
+ /* must we allocate the output buffer from a pool? */
+ if (!*out) {
+ outl = CCCryptorGetOutputLength(ctx->ref, inlen, 1);
+ buffer = apr_palloc(ctx->pool, outl);
+ if (!buffer) {
+ return APR_ENOMEM;
+ }
+ apr_crypto_clear(ctx->pool, buffer, outl);
+ *out = buffer;
+ }
+
+ switch ((ctx->f->result->rc = CCCryptorUpdate(ctx->ref, in, inlen, (*out),
+ outl, &outl))) {
+ case kCCSuccess: {
+ break;
+ }
+ case kCCBufferTooSmall: {
+ return APR_ENOSPACE;
+ }
+ default: {
+ return APR_ECRYPT;
+ }
+ }
+ *outlen = outl;
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * @brief Encrypt final data block, write it to out.
+ * @note If necessary the final block will be written out after being
+ * padded. Typically the final block will be written to the
+ * same buffer used by apr_crypto_block_encrypt, offset by the
+ * number of bytes returned as actually written by the
+ * apr_crypto_block_encrypt() call. After this call, the context
+ * is cleaned and can be reused by apr_crypto_block_encrypt_init().
+ * @param out Address of a buffer to which data will be written. This
+ * buffer must already exist, and is usually the same
+ * buffer used by apr_evp_crypt(). See note.
+ * @param outlen Length of the output will be written here.
+ * @param ctx The block context to use.
+ * @return APR_ECRYPT if an error occurred.
+ * @return APR_EPADDING if padding was enabled and the block was incorrectly
+ * formatted.
+ * @return APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_block_encrypt_finish(unsigned char *out,
+ apr_size_t *outlen, apr_crypto_block_t *ctx)
+{
+ apr_size_t len = *outlen;
+
+ ctx->f->result->rc = CCCryptorFinal(ctx->ref, out,
+ CCCryptorGetOutputLength(ctx->ref, 0, 1), &len);
+
+ /* always clean up */
+ crypto_block_cleanup(ctx);
+
+ switch (ctx->f->result->rc) {
+ case kCCSuccess: {
+ break;
+ }
+ case kCCBufferTooSmall: {
+ return APR_ENOSPACE;
+ }
+ case kCCAlignmentError: {
+ return APR_EPADDING;
+ }
+ case kCCDecodeError: {
+ return APR_ECRYPT;
+ }
+ default: {
+ return APR_ECRYPT;
+ }
+ }
+ *outlen = len;
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * @brief Initialise a context for decrypting arbitrary data using the given key.
+ * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
+ * *ctx is not NULL, *ctx must point at a previously created structure.
+ * @param ctx The block context returned, see note.
+ * @param blockSize The block size of the cipher.
+ * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
+ * an IV will be created at random, in space allocated from the pool.
+ * If the buffer is not NULL, the IV in the buffer will be used.
+ * @param key The key structure.
+ * @param p The pool to use.
+ * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
+ * Returns APR_EINIT if the backend failed to initialise the context. Returns
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
+ apr_size_t *blockSize, const unsigned char *iv,
+ const apr_crypto_key_t *key, apr_pool_t *p)
+{
+ apr_crypto_block_t *block = *ctx;
+ if (!block) {
+ *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
+ }
+ if (!block) {
+ return APR_ENOMEM;
+ }
+ block->f = key->f;
+ block->pool = p;
+ block->provider = key->provider;
+
+ apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
+ apr_pool_cleanup_null);
+
+ /* generate an IV, if necessary */
+ if (key->ivSize) {
+ if (iv == NULL) {
+ return APR_ENOIV;
+ }
+ }
+
+ /* create a new context for decryption */
+ switch ((block->f->result->rc = CCCryptorCreate(kCCDecrypt, key->algorithm,
+ key->options, key->key, key->keyLen, iv, &block->ref))) {
+ case kCCSuccess: {
+ break;
+ }
+ case kCCParamError: {
+ return APR_EINIT;
+ }
+ case kCCMemoryFailure: {
+ return APR_ENOMEM;
+ }
+ case kCCAlignmentError: {
+ return APR_EPADDING;
+ }
+ case kCCUnimplemented: {
+ return APR_ENOTIMPL;
+ }
+ default: {
+ return APR_EINIT;
+ }
+ }
+
+ if (blockSize) {
+ *blockSize = key->blockSize;
+ }
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * @brief Decrypt data provided by in, write it to out.
+ * @note The number of bytes written will be written to outlen. If
+ * out is NULL, outlen will contain the maximum size of the
+ * buffer needed to hold the data, including any data
+ * generated by apr_crypto_block_decrypt_finish below. If *out points
+ * to NULL, a buffer sufficiently large will be created from
+ * the pool provided. If *out points to a not-NULL value, this
+ * value will be used as a buffer instead.
+ * @param out Address of a buffer to which data will be written,
+ * see note.
+ * @param outlen Length of the output will be written here.
+ * @param in Address of the buffer to read.
+ * @param inlen Length of the buffer to read.
+ * @param ctx The block context to use.
+ * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
+ * not implemented.
+ */
+static apr_status_t crypto_block_decrypt(unsigned char **out,
+ apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
+ apr_crypto_block_t *ctx)
+{
+ apr_size_t outl = *outlen;
+ unsigned char *buffer;
+
+ /* are we after the maximum size of the out buffer? */
+ if (!out) {
+ *outlen = CCCryptorGetOutputLength(ctx->ref, inlen, 1);
+ return APR_SUCCESS;
+ }
+
+ /* must we allocate the output buffer from a pool? */
+ if (!*out) {
+ outl = CCCryptorGetOutputLength(ctx->ref, inlen, 1);
+ buffer = apr_palloc(ctx->pool, outl);
+ if (!buffer) {
+ return APR_ENOMEM;
+ }
+ apr_crypto_clear(ctx->pool, buffer, outl);
+ *out = buffer;
+ }
+
+ switch ((ctx->f->result->rc = CCCryptorUpdate(ctx->ref, in, inlen, (*out),
+ outl, &outl))) {
+ case kCCSuccess: {
+ break;
+ }
+ case kCCBufferTooSmall: {
+ return APR_ENOSPACE;
+ }
+ default: {
+ return APR_ECRYPT;
+ }
+ }
+ *outlen = outl;
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * @brief Decrypt final data block, write it to out.
+ * @note If necessary the final block will be written out after being
+ * padded. Typically the final block will be written to the
+ * same buffer used by apr_crypto_block_decrypt, offset by the
+ * number of bytes returned as actually written by the
+ * apr_crypto_block_decrypt() call. After this call, the context
+ * is cleaned and can be reused by apr_crypto_block_decrypt_init().
+ * @param out Address of a buffer to which data will be written. This
+ * buffer must already exist, and is usually the same
+ * buffer used by apr_evp_crypt(). See note.
+ * @param outlen Length of the output will be written here.
+ * @param ctx The block context to use.
+ * @return APR_ECRYPT if an error occurred.
+ * @return APR_EPADDING if padding was enabled and the block was incorrectly
+ * formatted.
+ * @return APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_block_decrypt_finish(unsigned char *out,
+ apr_size_t *outlen, apr_crypto_block_t *ctx)
+{
+ apr_size_t len = *outlen;
+
+ ctx->f->result->rc = CCCryptorFinal(ctx->ref, out,
+ CCCryptorGetOutputLength(ctx->ref, 0, 1), &len);
+
+ /* always clean up */
+ crypto_block_cleanup(ctx);
+
+ switch (ctx->f->result->rc) {
+ case kCCSuccess: {
+ break;
+ }
+ case kCCBufferTooSmall: {
+ return APR_ENOSPACE;
+ }
+ case kCCAlignmentError: {
+ return APR_EPADDING;
+ }
+ case kCCDecodeError: {
+ return APR_ECRYPT;
+ }
+ default: {
+ return APR_ECRYPT;
+ }
+ }
+ *outlen = len;
+
+ return APR_SUCCESS;
+
+}
+
+/**
+ * OSX Common Crypto module.
+ */
+APU_MODULE_DECLARE_DATA const apr_crypto_driver_t apr_crypto_commoncrypto_driver =
+{
+ "commoncrypto", crypto_init, crypto_make, crypto_get_block_key_types,
+ crypto_get_block_key_modes, crypto_passphrase,
+ crypto_block_encrypt_init, crypto_block_encrypt,
+ crypto_block_encrypt_finish, crypto_block_decrypt_init,
+ crypto_block_decrypt, crypto_block_decrypt_finish, crypto_block_cleanup,
+ crypto_cleanup, crypto_shutdown, crypto_error, crypto_key
+};
+
+#endif
diff --git a/crypto/apr_crypto_nss.c b/crypto/apr_crypto_nss.c
index b345953de73d2..47d164094614d 100644
--- a/crypto/apr_crypto_nss.c
+++ b/crypto/apr_crypto_nss.c
@@ -50,7 +50,6 @@ struct apr_crypto_t {
apr_pool_t *pool;
const apr_crypto_driver_t *provider;
apu_err_t *result;
- apr_array_header_t *keys;
apr_crypto_config_t *config;
apr_hash_t *types;
apr_hash_t *modes;
@@ -68,6 +67,7 @@ struct apr_crypto_key_t {
SECOidTag cipherOid;
PK11SymKey *symKey;
int ivSize;
+ int keyLength;
};
struct apr_crypto_block_t {
@@ -76,16 +76,24 @@ struct apr_crypto_block_t {
const apr_crypto_t *f;
PK11Context *ctx;
apr_crypto_key_t *key;
+ SECItem *secParam;
int blockSize;
};
-static int key_3des_192 = APR_KEY_3DES_192;
-static int key_aes_128 = APR_KEY_AES_128;
-static int key_aes_192 = APR_KEY_AES_192;
-static int key_aes_256 = APR_KEY_AES_256;
+static struct apr_crypto_block_key_type_t key_types[] =
+{
+{ APR_KEY_3DES_192, 24, 8, 8 },
+{ APR_KEY_AES_128, 16, 16, 16 },
+{ APR_KEY_AES_192, 24, 16, 16 },
+{ APR_KEY_AES_256, 32, 16, 16 } };
+
+static struct apr_crypto_block_key_mode_t key_modes[] =
+{
+{ APR_MODE_ECB },
+{ APR_MODE_CBC } };
-static int mode_ecb = APR_MODE_ECB;
-static int mode_cbc = APR_MODE_CBC;
+/* sufficient space to wrap a key */
+#define BUFFER_SIZE 128
/**
* Fetch the most recent error from this driver.
@@ -107,6 +115,8 @@ static apr_status_t crypto_shutdown(void)
if (NSS_IsInitialized()) {
SECStatus s = NSS_Shutdown();
if (s != SECSuccess) {
+ fprintf(stderr, "NSS failed to shutdown, possible leak: %d: %s",
+ PR_GetError(), PR_ErrorToName(s));
return APR_EINIT;
}
}
@@ -197,9 +207,6 @@ static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
return APR_EREINIT;
}
- apr_pool_cleanup_register(pool, pool, crypto_shutdown_helper,
- apr_pool_cleanup_null);
-
if (keyPrefix || certPrefix || secmod) {
s = NSS_Initialize(dir, certPrefix, keyPrefix, secmod, flags);
}
@@ -211,15 +218,20 @@ static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
}
if (s != SECSuccess) {
if (result) {
+ /* Note: all memory must be owned by the caller, in case we're unloaded */
apu_err_t *err = apr_pcalloc(pool, sizeof(apu_err_t));
err->rc = PR_GetError();
- err->msg = PR_ErrorToName(s);
- err->reason = "Error during 'nss' initialisation";
+ err->msg = apr_pstrdup(pool, PR_ErrorToName(s));
+ err->reason = apr_pstrdup(pool, "Error during 'nss' initialisation");
*result = err;
}
+
return APR_ECRYPT;
}
+ apr_pool_cleanup_register(pool, pool, crypto_shutdown_helper,
+ apr_pool_cleanup_null);
+
return APR_SUCCESS;
}
@@ -233,6 +245,11 @@ static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
static apr_status_t crypto_block_cleanup(apr_crypto_block_t *block)
{
+ if (block->secParam) {
+ SECITEM_FreeItem(block->secParam, PR_TRUE);
+ block->secParam = NULL;
+ }
+
if (block->ctx) {
PK11_DestroyContext(block->ctx, PR_TRUE);
block->ctx = NULL;
@@ -248,6 +265,15 @@ static apr_status_t crypto_block_cleanup_helper(void *data)
return crypto_block_cleanup(block);
}
+static apr_status_t crypto_key_cleanup(void *data)
+{
+ apr_crypto_key_t *key = data;
+ if (key->symKey) {
+ PK11_FreeSymKey(key->symKey);
+ key->symKey = NULL;
+ }
+ return APR_SUCCESS;
+}
/**
* @brief Clean encryption / decryption context.
* @note After cleanup, a context is free to be reused if necessary.
@@ -256,15 +282,6 @@ static apr_status_t crypto_block_cleanup_helper(void *data)
*/
static apr_status_t crypto_cleanup(apr_crypto_t *f)
{
- apr_crypto_key_t *key;
- if (f->keys) {
- while ((key = apr_array_pop(f->keys))) {
- if (key->symKey) {
- PK11_FreeSymKey(key->symKey);
- key->symKey = NULL;
- }
- }
- }
return APR_SUCCESS;
}
@@ -308,23 +325,22 @@ static apr_status_t crypto_make(apr_crypto_t **ff,
if (!f->result) {
return APR_ENOMEM;
}
- f->keys = apr_array_make(pool, 10, sizeof(apr_crypto_key_t));
f->types = apr_hash_make(pool);
if (!f->types) {
return APR_ENOMEM;
}
- apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_3des_192));
- apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_aes_128));
- apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_aes_192));
- apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_aes_256));
+ apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_types[0]));
+ apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_types[1]));
+ apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_types[2]));
+ apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_types[3]));
f->modes = apr_hash_make(pool);
if (!f->modes) {
return APR_ENOMEM;
}
- apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(mode_ecb));
- apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(mode_cbc));
+ apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(key_modes[0]));
+ apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(key_modes[1]));
apr_pool_cleanup_register(pool, f, crypto_cleanup_helper,
apr_pool_cleanup_null);
@@ -335,7 +351,7 @@ static apr_status_t crypto_make(apr_crypto_t **ff,
/**
* @brief Get a hash table of key types, keyed by the name of the type against
- * an integer pointer constant.
+ * a pointer to apr_crypto_block_key_type_t.
*
* @param types - hashtable of key types keyed to constants.
* @param f - encryption context
@@ -350,7 +366,7 @@ static apr_status_t crypto_get_block_key_types(apr_hash_t **types,
/**
* @brief Get a hash table of key modes, keyed by the name of the mode against
- * an integer pointer constant.
+ * a pointer to apr_crypto_block_key_mode_t.
*
* @param modes - hashtable of key modes keyed to constants.
* @param f - encryption context
@@ -363,57 +379,13 @@ static apr_status_t crypto_get_block_key_modes(apr_hash_t **modes,
return APR_SUCCESS;
}
-/**
- * @brief Create a key from the given passphrase. By default, the PBKDF2
- * algorithm is used to generate the key from the passphrase. It is expected
- * that the same pass phrase will generate the same key, regardless of the
- * backend crypto platform used. The key is cleaned up when the context
- * is cleaned, and may be reused with multiple encryption or decryption
- * operations.
- * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
- * *key is not NULL, *key must point at a previously created structure.
- * @param key The key returned, see note.
- * @param ivSize The size of the initialisation vector will be returned, based
- * on whether an IV is relevant for this type of crypto.
- * @param pass The passphrase to use.
- * @param passLen The passphrase length in bytes
- * @param salt The salt to use.
- * @param saltLen The salt length in bytes
- * @param type 3DES_192, AES_128, AES_192, AES_256.
- * @param mode Electronic Code Book / Cipher Block Chaining.
- * @param doPad Pad if necessary.
- * @param iterations Iteration count
- * @param f The context to use.
- * @param p The pool to use.
- * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
- * error occurred while generating the key. APR_ENOCIPHER if the type or mode
- * is not supported by the particular backend. APR_EKEYTYPE if the key type is
- * not known. APR_EPADDING if padding was requested but is not supported.
- * APR_ENOTIMPL if not implemented.
+/*
+ * Work out which mechanism to use.
*/
-static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
- const char *pass, apr_size_t passLen, const unsigned char * salt,
- apr_size_t saltLen, const apr_crypto_block_key_type_e type,
- const apr_crypto_block_key_mode_e mode, const int doPad,
- const int iterations, const apr_crypto_t *f, apr_pool_t *p)
+static apr_status_t crypto_cipher_mechanism(apr_crypto_key_t *key,
+ const apr_crypto_block_key_type_e type,
+ const apr_crypto_block_key_mode_e mode, const int doPad)
{
- apr_status_t rv = APR_SUCCESS;
- PK11SlotInfo * slot;
- SECItem passItem;
- SECItem saltItem;
- SECAlgorithmID *algid;
- void *wincx = NULL; /* what is wincx? */
- apr_crypto_key_t *key = *k;
-
- if (!key) {
- *k = key = apr_array_push(f->keys);
- }
- if (!key) {
- return APR_ENOMEM;
- }
-
- key->f = f;
- key->provider = f->provider;
/* decide on what cipher mechanism we will be using */
switch (type) {
@@ -426,6 +398,7 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
return APR_ENOCIPHER;
/* No OID for CKM_DES3_ECB; */
}
+ key->keyLength = 24;
break;
case (APR_KEY_AES_128):
if (APR_MODE_CBC == mode) {
@@ -434,6 +407,7 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
else {
key->cipherOid = SEC_OID_AES_128_ECB;
}
+ key->keyLength = 16;
break;
case (APR_KEY_AES_192):
if (APR_MODE_CBC == mode) {
@@ -442,6 +416,7 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
else {
key->cipherOid = SEC_OID_AES_192_ECB;
}
+ key->keyLength = 24;
break;
case (APR_KEY_AES_256):
if (APR_MODE_CBC == mode) {
@@ -450,6 +425,7 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
else {
key->cipherOid = SEC_OID_AES_256_ECB;
}
+ key->keyLength = 32;
break;
default:
/* unknown key type, give up */
@@ -464,13 +440,266 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
if (doPad) {
CK_MECHANISM_TYPE paddedMech;
paddedMech = PK11_GetPadMechanism(key->cipherMech);
- if (CKM_INVALID_MECHANISM == paddedMech || key->cipherMech
- == paddedMech) {
+ if (CKM_INVALID_MECHANISM == paddedMech
+ || key->cipherMech == paddedMech) {
return APR_EPADDING;
}
key->cipherMech = paddedMech;
}
+ key->ivSize = PK11_GetIVLength(key->cipherMech);
+
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Create a key from the provided secret or passphrase. The key is cleaned
+ * up when the context is cleaned, and may be reused with multiple encryption
+ * or decryption operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param rec The key record, from which the key will be derived.
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_key(apr_crypto_key_t **k,
+ const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p)
+{
+ apr_status_t rv = APR_SUCCESS;
+ PK11SlotInfo *slot, *tslot;
+ PK11SymKey *tkey;
+ SECItem secretItem;
+ SECItem wrappedItem;
+ SECItem *secParam;
+ PK11Context *ctx;
+ SECStatus s;
+ SECItem passItem;
+ SECItem saltItem;
+ SECAlgorithmID *algid;
+ void *wincx = NULL; /* what is wincx? */
+ apr_crypto_key_t *key;
+ int blockSize;
+ int remainder;
+
+ key = *k;
+ if (!key) {
+ *k = key = apr_pcalloc(p, sizeof *key);
+ if (!key) {
+ return APR_ENOMEM;
+ }
+ apr_pool_cleanup_register(p, key, crypto_key_cleanup,
+ apr_pool_cleanup_null);
+ }
+
+ key->f = f;
+ key->provider = f->provider;
+
+ /* decide on what cipher mechanism we will be using */
+ rv = crypto_cipher_mechanism(key, rec->type, rec->mode, rec->pad);
+ if (APR_SUCCESS != rv) {
+ return rv;
+ }
+
+ switch (rec->ktype) {
+
+ case APR_CRYPTO_KTYPE_PASSPHRASE: {
+
+ /* Turn the raw passphrase and salt into SECItems */
+ passItem.data = (unsigned char*) rec->k.passphrase.pass;
+ passItem.len = rec->k.passphrase.passLen;
+ saltItem.data = (unsigned char*) rec->k.passphrase.salt;
+ saltItem.len = rec->k.passphrase.saltLen;
+
+ /* generate the key */
+ /* pbeAlg and cipherAlg are the same. */
+ algid = PK11_CreatePBEV2AlgorithmID(key->cipherOid, key->cipherOid,
+ SEC_OID_HMAC_SHA1, key->keyLength,
+ rec->k.passphrase.iterations, &saltItem);
+ if (algid) {
+ slot = PK11_GetBestSlot(key->cipherMech, wincx);
+ if (slot) {
+ key->symKey = PK11_PBEKeyGen(slot, algid, &passItem, PR_FALSE,
+ wincx);
+ PK11_FreeSlot(slot);
+ }
+ SECOID_DestroyAlgorithmID(algid, PR_TRUE);
+ }
+
+ break;
+ }
+
+ case APR_CRYPTO_KTYPE_SECRET: {
+
+ /*
+ * NSS is by default in FIPS mode, which disallows the use of unencrypted
+ * symmetrical keys. As per http://permalink.gmane.org/gmane.comp.mozilla.crypto/7947
+ * we do the following:
+ *
+ * 1. Generate a (temporary) symmetric key in NSS.
+ * 2. Use that symmetric key to encrypt your symmetric key as data.
+ * 3. Unwrap your wrapped symmetric key, using the symmetric key
+ * you generated in Step 1 as the unwrapping key.
+ *
+ * http://permalink.gmane.org/gmane.comp.mozilla.crypto/7947
+ */
+
+ /* generate the key */
+ slot = PK11_GetBestSlot(key->cipherMech, NULL);
+ if (slot) {
+ unsigned char data[BUFFER_SIZE];
+
+ /* sanity check - key correct size? */
+ if (rec->k.secret.secretLen != key->keyLength) {
+ PK11_FreeSlot(slot);
+ return APR_EKEYLENGTH;
+ }
+
+ tslot = PK11_GetBestSlot(CKM_AES_ECB, NULL);
+ if (tslot) {
+
+ /* generate a temporary wrapping key */
+ tkey = PK11_KeyGen(tslot, CKM_AES_ECB, 0, PK11_GetBestKeyLength(tslot, CKM_AES_ECB), 0);
+
+ /* prepare the key to wrap */
+ secretItem.data = (unsigned char *) rec->k.secret.secret;
+ secretItem.len = rec->k.secret.secretLen;
+
+ /* ensure our key matches the blocksize */
+ secParam = PK11_GenerateNewParam(CKM_AES_ECB, tkey);
+ blockSize = PK11_GetBlockSize(CKM_AES_ECB, secParam);
+ remainder = rec->k.secret.secretLen % blockSize;
+ if (remainder) {
+ secretItem.data =
+ apr_pcalloc(p, rec->k.secret.secretLen + remainder);
+ apr_crypto_clear(p, secretItem.data,
+ rec->k.secret.secretLen);
+ memcpy(secretItem.data, rec->k.secret.secret,
+ rec->k.secret.secretLen);
+ secretItem.len += remainder;
+ }
+
+ /* prepare a space for the wrapped key */
+ wrappedItem.data = data;
+
+ /* wrap the key */
+ ctx = PK11_CreateContextBySymKey(CKM_AES_ECB, CKA_ENCRYPT, tkey,
+ secParam);
+ if (ctx) {
+ s = PK11_CipherOp(ctx, wrappedItem.data,
+ (int *) (&wrappedItem.len), BUFFER_SIZE,
+ secretItem.data, secretItem.len);
+ if (s == SECSuccess) {
+
+ /* unwrap the key again */
+ key->symKey = PK11_UnwrapSymKeyWithFlags(tkey,
+ CKM_AES_ECB, NULL, &wrappedItem,
+ key->cipherMech, CKA_ENCRYPT,
+ rec->k.secret.secretLen, 0);
+
+ }
+
+ PK11_DestroyContext(ctx, PR_TRUE);
+ }
+
+ /* clean up */
+ SECITEM_FreeItem(secParam, PR_TRUE);
+ PK11_FreeSymKey(tkey);
+ PK11_FreeSlot(tslot);
+
+ }
+
+ PK11_FreeSlot(slot);
+ }
+
+ break;
+ }
+
+ default: {
+
+ return APR_ENOKEY;
+
+ }
+ }
+
+ /* sanity check? */
+ if (!key->symKey) {
+ PRErrorCode perr = PORT_GetError();
+ if (perr) {
+ f->result->rc = perr;
+ f->result->msg = PR_ErrorToName(perr);
+ rv = APR_ENOKEY;
+ }
+ }
+
+ return rv;
+}
+
+/**
+ * @brief Create a key from the given passphrase. By default, the PBKDF2
+ * algorithm is used to generate the key from the passphrase. It is expected
+ * that the same pass phrase will generate the same key, regardless of the
+ * backend crypto platform used. The key is cleaned up when the context
+ * is cleaned, and may be reused with multiple encryption or decryption
+ * operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param ivSize The size of the initialisation vector will be returned, based
+ * on whether an IV is relevant for this type of crypto.
+ * @param pass The passphrase to use.
+ * @param passLen The passphrase length in bytes
+ * @param salt The salt to use.
+ * @param saltLen The salt length in bytes
+ * @param type 3DES_192, AES_128, AES_192, AES_256.
+ * @param mode Electronic Code Book / Cipher Block Chaining.
+ * @param doPad Pad if necessary.
+ * @param iterations Iteration count
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
+ const char *pass, apr_size_t passLen, const unsigned char * salt,
+ apr_size_t saltLen, const apr_crypto_block_key_type_e type,
+ const apr_crypto_block_key_mode_e mode, const int doPad,
+ const int iterations, const apr_crypto_t *f, apr_pool_t *p)
+{
+ apr_status_t rv = APR_SUCCESS;
+ PK11SlotInfo * slot;
+ SECItem passItem;
+ SECItem saltItem;
+ SECAlgorithmID *algid;
+ void *wincx = NULL; /* what is wincx? */
+ apr_crypto_key_t *key = *k;
+
+ if (!key) {
+ *k = key = apr_pcalloc(p, sizeof *key);
+ if (!key) {
+ return APR_ENOMEM;
+ }
+ apr_pool_cleanup_register(p, key, crypto_key_cleanup,
+ apr_pool_cleanup_null);
+ }
+
+ key->f = f;
+ key->provider = f->provider;
+
+ /* decide on what cipher mechanism we will be using */
+ rv = crypto_cipher_mechanism(key, type, mode, doPad);
+ if (APR_SUCCESS != rv) {
+ return rv;
+ }
+
/* Turn the raw passphrase and salt into SECItems */
passItem.data = (unsigned char*) pass;
passItem.len = passLen;
@@ -478,9 +707,9 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
saltItem.len = saltLen;
/* generate the key */
- /* pbeAlg and cipherAlg are the same. NSS decides the keylength. */
+ /* pbeAlg and cipherAlg are the same. */
algid = PK11_CreatePBEV2AlgorithmID(key->cipherOid, key->cipherOid,
- SEC_OID_HMAC_SHA1, 0, iterations, &saltItem);
+ SEC_OID_HMAC_SHA1, key->keyLength, iterations, &saltItem);
if (algid) {
slot = PK11_GetBestSlot(key->cipherMech, wincx);
if (slot) {
@@ -501,7 +730,6 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
}
}
- key->ivSize = PK11_GetIVLength(key->cipherMech);
if (ivSize) {
*ivSize = key->ivSize;
}
@@ -530,7 +758,6 @@ static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
apr_size_t *blockSize, apr_pool_t *p)
{
PRErrorCode perr;
- SECItem * secParam;
SECItem ivItem;
unsigned char * usedIv;
apr_crypto_block_t *block = *ctx;
@@ -569,14 +796,14 @@ static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
}
ivItem.data = usedIv;
ivItem.len = key->ivSize;
- secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
+ block->secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
}
else {
- secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
+ block->secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
}
- block->blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
+ block->blockSize = PK11_GetBlockSize(key->cipherMech, block->secParam);
block->ctx = PK11_CreateContextBySymKey(key->cipherMech, CKA_ENCRYPT,
- key->symKey, secParam);
+ key->symKey, block->secParam);
/* did an error occur? */
perr = PORT_GetError();
@@ -587,7 +814,7 @@ static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
}
if (blockSize) {
- *blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
+ *blockSize = PK11_GetBlockSize(key->cipherMech, block->secParam);
}
return APR_SUCCESS;
@@ -711,7 +938,6 @@ static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
const apr_crypto_key_t *key, apr_pool_t *p)
{
PRErrorCode perr;
- SECItem * secParam;
apr_crypto_block_t *block = *ctx;
if (!block) {
*ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
@@ -733,14 +959,14 @@ static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
}
ivItem.data = (unsigned char*) iv;
ivItem.len = key->ivSize;
- secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
+ block->secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
}
else {
- secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
+ block->secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
}
- block->blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
+ block->blockSize = PK11_GetBlockSize(key->cipherMech, block->secParam);
block->ctx = PK11_CreateContextBySymKey(key->cipherMech, CKA_DECRYPT,
- key->symKey, secParam);
+ key->symKey, block->secParam);
/* did an error occur? */
perr = PORT_GetError();
@@ -751,7 +977,7 @@ static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
}
if (blockSize) {
- *blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
+ *blockSize = PK11_GetBlockSize(key->cipherMech, block->secParam);
}
return APR_SUCCESS;
@@ -864,7 +1090,8 @@ APU_MODULE_DECLARE_DATA const apr_crypto_driver_t apr_crypto_nss_driver = {
crypto_block_encrypt_init, crypto_block_encrypt,
crypto_block_encrypt_finish, crypto_block_decrypt_init,
crypto_block_decrypt, crypto_block_decrypt_finish,
- crypto_block_cleanup, crypto_cleanup, crypto_shutdown, crypto_error
+ crypto_block_cleanup, crypto_cleanup, crypto_shutdown, crypto_error,
+ crypto_key
};
#endif
diff --git a/crypto/apr_crypto_openssl.c b/crypto/apr_crypto_openssl.c
index 0740f93f63493..310bb2c762b12 100644
--- a/crypto/apr_crypto_openssl.c
+++ b/crypto/apr_crypto_openssl.c
@@ -31,15 +31,27 @@
#if APU_HAVE_CRYPTO
#include <openssl/evp.h>
+#include <openssl/rand.h>
#include <openssl/engine.h>
#define LOG_PREFIX "apr_crypto_openssl: "
+#ifndef APR_USE_OPENSSL_PRE_1_1_API
+#if defined(LIBRESSL_VERSION_NUMBER)
+/* LibreSSL declares OPENSSL_VERSION_NUMBER == 2.0 but does not include most
+ * changes from OpenSSL >= 1.1 (new functions, macros, deprecations, ...), so
+ * we have to work around this...
+ */
+#define APR_USE_OPENSSL_PRE_1_1_API (1)
+#else
+#define APR_USE_OPENSSL_PRE_1_1_API (OPENSSL_VERSION_NUMBER < 0x10100000L)
+#endif
+#endif
+
struct apr_crypto_t {
apr_pool_t *pool;
const apr_crypto_driver_t *provider;
apu_err_t *result;
- apr_array_header_t *keys;
apr_crypto_config_t *config;
apr_hash_t *types;
apr_hash_t *modes;
@@ -64,20 +76,27 @@ struct apr_crypto_block_t {
apr_pool_t *pool;
const apr_crypto_driver_t *provider;
const apr_crypto_t *f;
- EVP_CIPHER_CTX cipherCtx;
+ EVP_CIPHER_CTX *cipherCtx;
int initialised;
int ivSize;
int blockSize;
int doPad;
};
-static int key_3des_192 = APR_KEY_3DES_192;
-static int key_aes_128 = APR_KEY_AES_128;
-static int key_aes_192 = APR_KEY_AES_192;
-static int key_aes_256 = APR_KEY_AES_256;
+static struct apr_crypto_block_key_type_t key_types[] =
+{
+{ APR_KEY_3DES_192, 24, 8, 8 },
+{ APR_KEY_AES_128, 16, 16, 16 },
+{ APR_KEY_AES_192, 24, 16, 16 },
+{ APR_KEY_AES_256, 32, 16, 16 } };
+
+static struct apr_crypto_block_key_mode_t key_modes[] =
+{
+{ APR_MODE_ECB },
+{ APR_MODE_CBC } };
-static int mode_ecb = APR_MODE_ECB;
-static int mode_cbc = APR_MODE_CBC;
+/* sufficient space to wrap a key */
+#define BUFFER_SIZE 128
/**
* Fetch the most recent error from this driver.
@@ -111,7 +130,11 @@ static apr_status_t crypto_shutdown_helper(void *data)
static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
const apu_err_t **result)
{
- CRYPTO_malloc_init();
+#if APR_USE_OPENSSL_PRE_1_1_API
+ (void)CRYPTO_malloc_init();
+#else
+ OPENSSL_malloc_init();
+#endif
ERR_load_crypto_strings();
/* SSL_load_error_strings(); */
OpenSSL_add_all_algorithms();
@@ -124,6 +147,30 @@ static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
return APR_SUCCESS;
}
+#if OPENSSL_VERSION_NUMBER < 0x0090802fL
+
+/* Code taken from OpenSSL 0.9.8b, see
+ * https://github.com/openssl/openssl/commit/cf6bc84148cb15af09b292394aaf2b45f0d5af0d
+ */
+
+EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
+{
+ EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
+ if (ctx)
+ EVP_CIPHER_CTX_init(ctx);
+ return ctx;
+}
+
+void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
+{
+ if (ctx) {
+ EVP_CIPHER_CTX_cleanup(ctx);
+ OPENSSL_free(ctx);
+ }
+}
+
+#endif
+
/**
* @brief Clean encryption / decryption context.
* @note After cleanup, a context is free to be reused if necessary.
@@ -134,7 +181,7 @@ static apr_status_t crypto_block_cleanup(apr_crypto_block_t *ctx)
{
if (ctx->initialised) {
- EVP_CIPHER_CTX_cleanup(&ctx->cipherCtx);
+ EVP_CIPHER_CTX_free(ctx->cipherCtx);
ctx->initialised = 0;
}
@@ -256,26 +303,21 @@ static apr_status_t crypto_make(apr_crypto_t **ff,
return APR_ENOMEM;
}
- f->keys = apr_array_make(pool, 10, sizeof(apr_crypto_key_t));
- if (!f->keys) {
- return APR_ENOMEM;
- }
-
f->types = apr_hash_make(pool);
if (!f->types) {
return APR_ENOMEM;
}
- apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_3des_192));
- apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_aes_128));
- apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_aes_192));
- apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_aes_256));
+ apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_types[0]));
+ apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_types[1]));
+ apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_types[2]));
+ apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_types[3]));
f->modes = apr_hash_make(pool);
if (!f->modes) {
return APR_ENOMEM;
}
- apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(mode_ecb));
- apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(mode_cbc));
+ apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(key_modes[0]));
+ apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(key_modes[1]));
apr_pool_cleanup_register(pool, f, crypto_cleanup_helper,
apr_pool_cleanup_null);
@@ -298,7 +340,7 @@ static apr_status_t crypto_make(apr_crypto_t **ff,
/**
* @brief Get a hash table of key types, keyed by the name of the type against
- * an integer pointer constant.
+ * a pointer to apr_crypto_block_key_type_t.
*
* @param types - hashtable of key types keyed to constants.
* @param f - encryption context
@@ -313,7 +355,7 @@ static apr_status_t crypto_get_block_key_types(apr_hash_t **types,
/**
* @brief Get a hash table of key modes, keyed by the name of the mode against
- * an integer pointer constant.
+ * a pointer to apr_crypto_block_key_mode_t.
*
* @param modes - hashtable of key modes keyed to constants.
* @param f - encryption context
@@ -326,52 +368,13 @@ static apr_status_t crypto_get_block_key_modes(apr_hash_t **modes,
return APR_SUCCESS;
}
-/**
- * @brief Create a key from the given passphrase. By default, the PBKDF2
- * algorithm is used to generate the key from the passphrase. It is expected
- * that the same pass phrase will generate the same key, regardless of the
- * backend crypto platform used. The key is cleaned up when the context
- * is cleaned, and may be reused with multiple encryption or decryption
- * operations.
- * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
- * *key is not NULL, *key must point at a previously created structure.
- * @param key The key returned, see note.
- * @param ivSize The size of the initialisation vector will be returned, based
- * on whether an IV is relevant for this type of crypto.
- * @param pass The passphrase to use.
- * @param passLen The passphrase length in bytes
- * @param salt The salt to use.
- * @param saltLen The salt length in bytes
- * @param type 3DES_192, AES_128, AES_192, AES_256.
- * @param mode Electronic Code Book / Cipher Block Chaining.
- * @param doPad Pad if necessary.
- * @param iterations Iteration count
- * @param f The context to use.
- * @param p The pool to use.
- * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
- * error occurred while generating the key. APR_ENOCIPHER if the type or mode
- * is not supported by the particular backend. APR_EKEYTYPE if the key type is
- * not known. APR_EPADDING if padding was requested but is not supported.
- * APR_ENOTIMPL if not implemented.
+/*
+ * Work out which mechanism to use.
*/
-static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
- const char *pass, apr_size_t passLen, const unsigned char * salt,
- apr_size_t saltLen, const apr_crypto_block_key_type_e type,
- const apr_crypto_block_key_mode_e mode, const int doPad,
- const int iterations, const apr_crypto_t *f, apr_pool_t *p)
+static apr_status_t crypto_cipher_mechanism(apr_crypto_key_t *key,
+ const apr_crypto_block_key_type_e type,
+ const apr_crypto_block_key_mode_e mode, const int doPad, apr_pool_t *p)
{
- apr_crypto_key_t *key = *k;
-
- if (!key) {
- *k = key = apr_array_push(f->keys);
- }
- if (!key) {
- return APR_ENOMEM;
- }
-
- key->f = f;
- key->provider = f->provider;
-
/* determine the cipher to be used */
switch (type) {
@@ -433,6 +436,148 @@ static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
}
apr_crypto_clear(p, key->key, key->keyLen);
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Create a key from the provided secret or passphrase. The key is cleaned
+ * up when the context is cleaned, and may be reused with multiple encryption
+ * or decryption operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param rec The key record, from which the key will be derived.
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_key(apr_crypto_key_t **k,
+ const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p)
+{
+ apr_crypto_key_t *key = *k;
+ apr_status_t rv;
+
+ if (!key) {
+ *k = key = apr_pcalloc(p, sizeof *key);
+ if (!key) {
+ return APR_ENOMEM;
+ }
+ }
+
+ key->f = f;
+ key->provider = f->provider;
+
+ /* decide on what cipher mechanism we will be using */
+ rv = crypto_cipher_mechanism(key, rec->type, rec->mode, rec->pad, p);
+ if (APR_SUCCESS != rv) {
+ return rv;
+ }
+
+ switch (rec->ktype) {
+
+ case APR_CRYPTO_KTYPE_PASSPHRASE: {
+
+ /* generate the key */
+ if (PKCS5_PBKDF2_HMAC_SHA1(rec->k.passphrase.pass,
+ rec->k.passphrase.passLen,
+ (unsigned char *) rec->k.passphrase.salt,
+ rec->k.passphrase.saltLen, rec->k.passphrase.iterations,
+ key->keyLen, key->key) == 0) {
+ return APR_ENOKEY;
+ }
+
+ break;
+ }
+
+ case APR_CRYPTO_KTYPE_SECRET: {
+
+ /* sanity check - key correct size? */
+ if (rec->k.secret.secretLen != key->keyLen) {
+ return APR_EKEYLENGTH;
+ }
+
+ /* copy the key */
+ memcpy(key->key, rec->k.secret.secret, rec->k.secret.secretLen);
+
+ break;
+ }
+
+ default: {
+
+ return APR_ENOKEY;
+
+ }
+ }
+
+ key->doPad = rec->pad;
+
+ /* note: openssl incorrectly returns non zero IV size values for ECB
+ * algorithms, so work around this by ignoring the IV size.
+ */
+ if (APR_MODE_ECB != rec->mode) {
+ key->ivSize = EVP_CIPHER_iv_length(key->cipher);
+ }
+
+ return APR_SUCCESS;
+}
+
+/**
+ * @brief Create a key from the given passphrase. By default, the PBKDF2
+ * algorithm is used to generate the key from the passphrase. It is expected
+ * that the same pass phrase will generate the same key, regardless of the
+ * backend crypto platform used. The key is cleaned up when the context
+ * is cleaned, and may be reused with multiple encryption or decryption
+ * operations.
+ * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
+ * *key is not NULL, *key must point at a previously created structure.
+ * @param key The key returned, see note.
+ * @param ivSize The size of the initialisation vector will be returned, based
+ * on whether an IV is relevant for this type of crypto.
+ * @param pass The passphrase to use.
+ * @param passLen The passphrase length in bytes
+ * @param salt The salt to use.
+ * @param saltLen The salt length in bytes
+ * @param type 3DES_192, AES_128, AES_192, AES_256.
+ * @param mode Electronic Code Book / Cipher Block Chaining.
+ * @param doPad Pad if necessary.
+ * @param iterations Iteration count
+ * @param f The context to use.
+ * @param p The pool to use.
+ * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
+ * error occurred while generating the key. APR_ENOCIPHER if the type or mode
+ * is not supported by the particular backend. APR_EKEYTYPE if the key type is
+ * not known. APR_EPADDING if padding was requested but is not supported.
+ * APR_ENOTIMPL if not implemented.
+ */
+static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
+ const char *pass, apr_size_t passLen, const unsigned char * salt,
+ apr_size_t saltLen, const apr_crypto_block_key_type_e type,
+ const apr_crypto_block_key_mode_e mode, const int doPad,
+ const int iterations, const apr_crypto_t *f, apr_pool_t *p)
+{
+ apr_crypto_key_t *key = *k;
+ apr_status_t rv;
+
+ if (!key) {
+ *k = key = apr_pcalloc(p, sizeof *key);
+ if (!key) {
+ return APR_ENOMEM;
+ }
+ }
+
+ key->f = f;
+ key->provider = f->provider;
+
+ /* decide on what cipher mechanism we will be using */
+ rv = crypto_cipher_mechanism(key, type, mode, doPad, p);
+ if (APR_SUCCESS != rv) {
+ return rv;
+ }
+
/* generate the key */
if (PKCS5_PBKDF2_HMAC_SHA1(pass, passLen, (unsigned char *) salt, saltLen,
iterations, key->keyLen, key->key) == 0) {
@@ -491,8 +636,10 @@ static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
apr_pool_cleanup_null);
/* create a new context for encryption */
- EVP_CIPHER_CTX_init(&block->cipherCtx);
- block->initialised = 1;
+ if (!block->initialised) {
+ block->cipherCtx = EVP_CIPHER_CTX_new();
+ block->initialised = 1;
+ }
/* generate an IV, if necessary */
usedIv = NULL;
@@ -519,16 +666,16 @@ static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
/* set up our encryption context */
#if CRYPTO_OPENSSL_CONST_BUFFERS
- if (!EVP_EncryptInit_ex(&block->cipherCtx, key->cipher, config->engine,
+ if (!EVP_EncryptInit_ex(block->cipherCtx, key->cipher, config->engine,
key->key, usedIv)) {
#else
- if (!EVP_EncryptInit_ex(&block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) usedIv)) {
+ if (!EVP_EncryptInit_ex(block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) usedIv)) {
#endif
return APR_EINIT;
}
/* Clear up any read padding */
- if (!EVP_CIPHER_CTX_set_padding(&block->cipherCtx, key->doPad)) {
+ if (!EVP_CIPHER_CTX_set_padding(block->cipherCtx, key->doPad)) {
return APR_EPADDING;
}
@@ -582,11 +729,16 @@ static apr_status_t crypto_block_encrypt(unsigned char **out,
}
#if CRYPT_OPENSSL_CONST_BUFFERS
- if (!EVP_EncryptUpdate(&ctx->cipherCtx, (*out), &outl, in, inlen)) {
+ if (!EVP_EncryptUpdate(ctx->cipherCtx, (*out), &outl, in, inlen)) {
#else
- if (!EVP_EncryptUpdate(&ctx->cipherCtx, (*out), &outl,
+ if (!EVP_EncryptUpdate(ctx->cipherCtx, (*out), &outl,
(unsigned char *) in, inlen)) {
#endif
+#if APR_USE_OPENSSL_PRE_1_1_API
+ EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
+#else
+ EVP_CIPHER_CTX_reset(ctx->cipherCtx);
+#endif
return APR_ECRYPT;
}
*outlen = outl;
@@ -616,14 +768,22 @@ static apr_status_t crypto_block_encrypt(unsigned char **out,
static apr_status_t crypto_block_encrypt_finish(unsigned char *out,
apr_size_t *outlen, apr_crypto_block_t *ctx)
{
+ apr_status_t rc = APR_SUCCESS;
int len = *outlen;
- if (EVP_EncryptFinal_ex(&ctx->cipherCtx, out, &len) == 0) {
- return APR_EPADDING;
+ if (EVP_EncryptFinal_ex(ctx->cipherCtx, out, &len) == 0) {
+ rc = APR_EPADDING;
+ }
+ else {
+ *outlen = len;
}
- *outlen = len;
+#if APR_USE_OPENSSL_PRE_1_1_API
+ EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
+#else
+ EVP_CIPHER_CTX_reset(ctx->cipherCtx);
+#endif
- return APR_SUCCESS;
+ return rc;
}
@@ -662,8 +822,10 @@ static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
apr_pool_cleanup_null);
/* create a new context for encryption */
- EVP_CIPHER_CTX_init(&block->cipherCtx);
- block->initialised = 1;
+ if (!block->initialised) {
+ block->cipherCtx = EVP_CIPHER_CTX_new();
+ block->initialised = 1;
+ }
/* generate an IV, if necessary */
if (key->ivSize) {
@@ -674,16 +836,16 @@ static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
/* set up our encryption context */
#if CRYPTO_OPENSSL_CONST_BUFFERS
- if (!EVP_DecryptInit_ex(&block->cipherCtx, key->cipher, config->engine,
+ if (!EVP_DecryptInit_ex(block->cipherCtx, key->cipher, config->engine,
key->key, iv)) {
#else
- if (!EVP_DecryptInit_ex(&block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) iv)) {
+ if (!EVP_DecryptInit_ex(block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) iv)) {
#endif
return APR_EINIT;
}
/* Clear up any read padding */
- if (!EVP_CIPHER_CTX_set_padding(&block->cipherCtx, key->doPad)) {
+ if (!EVP_CIPHER_CTX_set_padding(block->cipherCtx, key->doPad)) {
return APR_EPADDING;
}
@@ -737,11 +899,16 @@ static apr_status_t crypto_block_decrypt(unsigned char **out,
}
#if CRYPT_OPENSSL_CONST_BUFFERS
- if (!EVP_DecryptUpdate(&ctx->cipherCtx, *out, &outl, in, inlen)) {
+ if (!EVP_DecryptUpdate(ctx->cipherCtx, *out, &outl, in, inlen)) {
#else
- if (!EVP_DecryptUpdate(&ctx->cipherCtx, *out, &outl, (unsigned char *) in,
+ if (!EVP_DecryptUpdate(ctx->cipherCtx, *out, &outl, (unsigned char *) in,
inlen)) {
#endif
+#if APR_USE_OPENSSL_PRE_1_1_API
+ EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
+#else
+ EVP_CIPHER_CTX_reset(ctx->cipherCtx);
+#endif
return APR_ECRYPT;
}
*outlen = outl;
@@ -771,15 +938,22 @@ static apr_status_t crypto_block_decrypt(unsigned char **out,
static apr_status_t crypto_block_decrypt_finish(unsigned char *out,
apr_size_t *outlen, apr_crypto_block_t *ctx)
{
-
+ apr_status_t rc = APR_SUCCESS;
int len = *outlen;
- if (EVP_DecryptFinal_ex(&ctx->cipherCtx, out, &len) == 0) {
- return APR_EPADDING;
+ if (EVP_DecryptFinal_ex(ctx->cipherCtx, out, &len) == 0) {
+ rc = APR_EPADDING;
+ }
+ else {
+ *outlen = len;
}
- *outlen = len;
+#if APR_USE_OPENSSL_PRE_1_1_API
+ EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
+#else
+ EVP_CIPHER_CTX_reset(ctx->cipherCtx);
+#endif
- return APR_SUCCESS;
+ return rc;
}
@@ -792,7 +966,8 @@ APU_MODULE_DECLARE_DATA const apr_crypto_driver_t apr_crypto_openssl_driver = {
crypto_block_encrypt_init, crypto_block_encrypt,
crypto_block_encrypt_finish, crypto_block_decrypt_init,
crypto_block_decrypt, crypto_block_decrypt_finish,
- crypto_block_cleanup, crypto_cleanup, crypto_shutdown, crypto_error
+ crypto_block_cleanup, crypto_cleanup, crypto_shutdown, crypto_error,
+ crypto_key
};
#endif
diff --git a/crypto/apr_siphash.c b/crypto/apr_siphash.c
new file mode 100644
index 0000000000000..c9cabe2d2d4c2
--- /dev/null
+++ b/crypto/apr_siphash.c
@@ -0,0 +1,196 @@
+/* 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
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * SipHash (C reference implementation, APR-ized), originating from:
+ * https://131002.net/siphash/siphash24.c.
+ */
+
+#include "apr_siphash.h"
+
+#define ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n))))
+
+#define U8TO64_LE(p) \
+ (((apr_uint64_t)((p)[0]) ) | \
+ ((apr_uint64_t)((p)[1]) << 8) | \
+ ((apr_uint64_t)((p)[2]) << 16) | \
+ ((apr_uint64_t)((p)[3]) << 24) | \
+ ((apr_uint64_t)((p)[4]) << 32) | \
+ ((apr_uint64_t)((p)[5]) << 40) | \
+ ((apr_uint64_t)((p)[6]) << 48) | \
+ ((apr_uint64_t)((p)[7]) << 56))
+
+#define U64TO8_LE(p, v) \
+do { \
+ (p)[0] = (unsigned char)((v) ); \
+ (p)[1] = (unsigned char)((v) >> 8); \
+ (p)[2] = (unsigned char)((v) >> 16); \
+ (p)[3] = (unsigned char)((v) >> 24); \
+ (p)[4] = (unsigned char)((v) >> 32); \
+ (p)[5] = (unsigned char)((v) >> 40); \
+ (p)[6] = (unsigned char)((v) >> 48); \
+ (p)[7] = (unsigned char)((v) >> 56); \
+} while (0)
+
+#define SIPROUND() \
+do { \
+ v0 += v1; v1=ROTL64(v1,13); v1 ^= v0; v0=ROTL64(v0,32); \
+ v2 += v3; v3=ROTL64(v3,16); v3 ^= v2; \
+ v0 += v3; v3=ROTL64(v3,21); v3 ^= v0; \
+ v2 += v1; v1=ROTL64(v1,17); v1 ^= v2; v2=ROTL64(v2,32); \
+} while(0)
+
+#define SIPHASH(r, s, n, k) \
+do { \
+ const unsigned char *ptr, *end; \
+ apr_uint64_t v0, v1, v2, v3, m; \
+ apr_uint64_t k0, k1; \
+ unsigned int rem; \
+ \
+ k0 = U8TO64_LE(k + 0); \
+ k1 = U8TO64_LE(k + 8); \
+ v3 = k1 ^ (apr_uint64_t)0x7465646279746573ULL; \
+ v2 = k0 ^ (apr_uint64_t)0x6c7967656e657261ULL; \
+ v1 = k1 ^ (apr_uint64_t)0x646f72616e646f6dULL; \
+ v0 = k0 ^ (apr_uint64_t)0x736f6d6570736575ULL; \
+ \
+ rem = (unsigned int)(n & 0x7); \
+ for (ptr = s, end = ptr + n - rem; ptr < end; ptr += 8) { \
+ m = U8TO64_LE(ptr); \
+ v3 ^= m; \
+ cROUNDS \
+ v0 ^= m; \
+ } \
+ m = (apr_uint64_t)(n & 0xff) << 56; \
+ switch (rem) { \
+ case 7: m |= (apr_uint64_t)ptr[6] << 48; \
+ case 6: m |= (apr_uint64_t)ptr[5] << 40; \
+ case 5: m |= (apr_uint64_t)ptr[4] << 32; \
+ case 4: m |= (apr_uint64_t)ptr[3] << 24; \
+ case 3: m |= (apr_uint64_t)ptr[2] << 16; \
+ case 2: m |= (apr_uint64_t)ptr[1] << 8; \
+ case 1: m |= (apr_uint64_t)ptr[0]; \
+ case 0: break; \
+ } \
+ v3 ^= m; \
+ cROUNDS \
+ v0 ^= m; \
+ \
+ v2 ^= 0xff; \
+ dROUNDS \
+ \
+ r = v0 ^ v1 ^ v2 ^ v3; \
+} while (0)
+
+APU_DECLARE(apr_uint64_t) apr_siphash(const void *src, apr_size_t len,
+ const unsigned char key[APR_SIPHASH_KSIZE],
+ unsigned int c, unsigned int d)
+{
+ apr_uint64_t h;
+ unsigned int i;
+
+#undef cROUNDS
+#define cROUNDS \
+ for (i = 0; i < c; ++i) { \
+ SIPROUND(); \
+ }
+
+#undef dROUNDS
+#define dROUNDS \
+ for (i = 0; i < d; ++i) { \
+ SIPROUND(); \
+ }
+
+ SIPHASH(h, src, len, key);
+ return h;
+}
+
+APU_DECLARE(void) apr_siphash_auth(unsigned char out[APR_SIPHASH_DSIZE],
+ const void *src, apr_size_t len,
+ const unsigned char key[APR_SIPHASH_KSIZE],
+ unsigned int c, unsigned int d)
+{
+ apr_uint64_t h;
+ h = apr_siphash(src, len, key, c, d);
+ U64TO8_LE(out, h);
+}
+
+APU_DECLARE(apr_uint64_t) apr_siphash24(const void *src, apr_size_t len,
+ const unsigned char key[APR_SIPHASH_KSIZE])
+{
+ apr_uint64_t h;
+
+#undef cROUNDS
+#define cROUNDS \
+ SIPROUND(); \
+ SIPROUND();
+
+#undef dROUNDS
+#define dROUNDS \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND();
+
+ SIPHASH(h, src, len, key);
+ return h;
+}
+
+APU_DECLARE(void) apr_siphash24_auth(unsigned char out[APR_SIPHASH_DSIZE],
+ const void *src, apr_size_t len,
+ const unsigned char key[APR_SIPHASH_KSIZE])
+{
+ apr_uint64_t h;
+ h = apr_siphash24(src, len, key);
+ U64TO8_LE(out, h);
+}
+
+APU_DECLARE(apr_uint64_t) apr_siphash48(const void *src, apr_size_t len,
+ const unsigned char key[APR_SIPHASH_KSIZE])
+{
+ apr_uint64_t h;
+
+#undef cROUNDS
+#define cROUNDS \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND();
+
+#undef dROUNDS
+#define dROUNDS \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND(); \
+ SIPROUND();
+
+ SIPHASH(h, src, len, key);
+ return h;
+}
+
+APU_DECLARE(void) apr_siphash48_auth(unsigned char out[APR_SIPHASH_DSIZE],
+ const void *src, apr_size_t len,
+ const unsigned char key[APR_SIPHASH_KSIZE])
+{
+ apr_uint64_t h;
+ h = apr_siphash48(src, len, key);
+ U64TO8_LE(out, h);
+}
+
diff --git a/crypto/crypt_blowfish.c b/crypto/crypt_blowfish.c
index ec9a188b3a288..3d306cf8d3f4d 100644
--- a/crypto/crypt_blowfish.c
+++ b/crypto/crypt_blowfish.c
@@ -675,9 +675,9 @@ static char *BF_crypt(const char *key, const char *setting,
setting[2] < 'a' || setting[2] > 'z' ||
!flags_by_subtype[(unsigned int)(unsigned char)setting[2] - 'a'] ||
setting[3] != '$' ||
- setting[4] < '0' || setting[4] > '3' ||
+ setting[4] < '0' || setting[4] > '1' ||
setting[5] < '0' || setting[5] > '9' ||
- (setting[4] == '3' && setting[5] > '1') ||
+ (setting[4] == '1' && setting[5] > '7') ||
setting[6] != '$') {
__set_errno(EINVAL);
return NULL;
@@ -877,7 +877,7 @@ char *_crypt_gensalt_blowfish_rn(const char *prefix, unsigned long count,
const char *input, int size, char *output, int output_size)
{
if (size < 16 || output_size < 7 + 22 + 1 ||
- (count && (count < 4 || count > 31)) ||
+ (count && (count < 4 || count > 17)) ||
prefix[0] != '$' || prefix[1] != '2' ||
(prefix[2] != 'a' && prefix[2] != 'y')) {
if (output_size > 0) output[0] = '\0';