1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include "apu_config.h"
20 #include "apu_errno.h"
25 #include "apr_strings.h"
27 #include "apr_buckets.h"
29 #include "apr_crypto_internal.h"
42 #ifdef HAVE_NSS_PK11PUB_H
43 #include <nss/pk11pub.h>
51 const apr_crypto_driver_t *provider;
53 apr_array_header_t *keys;
54 apr_crypto_config_t *config;
59 struct apr_crypto_config_t {
63 struct apr_crypto_key_t {
65 const apr_crypto_driver_t *provider;
66 const apr_crypto_t *f;
67 CK_MECHANISM_TYPE cipherMech;
73 struct apr_crypto_block_t {
75 const apr_crypto_driver_t *provider;
76 const apr_crypto_t *f;
78 apr_crypto_key_t *key;
82 static int key_3des_192 = APR_KEY_3DES_192;
83 static int key_aes_128 = APR_KEY_AES_128;
84 static int key_aes_192 = APR_KEY_AES_192;
85 static int key_aes_256 = APR_KEY_AES_256;
87 static int mode_ecb = APR_MODE_ECB;
88 static int mode_cbc = APR_MODE_CBC;
91 * Fetch the most recent error from this driver.
93 static apr_status_t crypto_error(const apu_err_t **result,
94 const apr_crypto_t *f)
101 * Shutdown the crypto library and release resources.
103 * It is safe to shut down twice.
105 static apr_status_t crypto_shutdown(void)
107 if (NSS_IsInitialized()) {
108 SECStatus s = NSS_Shutdown();
109 if (s != SECSuccess) {
116 static apr_status_t crypto_shutdown_helper(void *data)
118 return crypto_shutdown();
122 * Initialise the crypto library and perform one time initialisation.
124 static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
125 const apu_err_t **result)
128 const char *dir = NULL;
129 const char *keyPrefix = NULL;
130 const char *certPrefix = NULL;
131 const char *secmod = NULL;
142 { "cert7", NULL, 0 },
143 { "secmod", NULL, 0 },
144 { "noinit", NULL, 0 },
155 if (APR_SUCCESS != (status = apr_tokenize_to_argv(params, &elts, pool))) {
158 while ((elt = elts[i])) {
159 ptr = strchr(elt, '=');
161 for (klen = ptr - elt; klen && apr_isspace(elt[klen - 1]); --klen)
166 for (klen = strlen(elt); klen && apr_isspace(elt[klen - 1]); --klen)
171 for (j = 0; fields[j].field != NULL; ++j) {
172 if (klen && !strcasecmp(fields[j].field, elt)) {
175 fields[j].value = ptr;
183 dir = fields[0].value;
184 keyPrefix = fields[1].value;
185 certPrefix = fields[2].value;
186 secmod = fields[3].value;
187 noinit = fields[4].set;
190 /* if we've been asked to bypass, do so here */
195 /* sanity check - we can only initialise NSS once */
196 if (NSS_IsInitialized()) {
200 apr_pool_cleanup_register(pool, pool, crypto_shutdown_helper,
201 apr_pool_cleanup_null);
203 if (keyPrefix || certPrefix || secmod) {
204 s = NSS_Initialize(dir, certPrefix, keyPrefix, secmod, flags);
207 s = NSS_InitReadWrite(dir);
210 s = NSS_NoDB_Init(NULL);
212 if (s != SECSuccess) {
214 apu_err_t *err = apr_pcalloc(pool, sizeof(apu_err_t));
215 err->rc = PR_GetError();
216 err->msg = PR_ErrorToName(s);
217 err->reason = "Error during 'nss' initialisation";
228 * @brief Clean encryption / decryption context.
229 * @note After cleanup, a context is free to be reused if necessary.
230 * @param f The context to use.
231 * @return Returns APR_ENOTIMPL if not supported.
233 static apr_status_t crypto_block_cleanup(apr_crypto_block_t *block)
237 PK11_DestroyContext(block->ctx, PR_TRUE);
245 static apr_status_t crypto_block_cleanup_helper(void *data)
247 apr_crypto_block_t *block = (apr_crypto_block_t *) data;
248 return crypto_block_cleanup(block);
252 * @brief Clean encryption / decryption context.
253 * @note After cleanup, a context is free to be reused if necessary.
254 * @param f The context to use.
255 * @return Returns APR_ENOTIMPL if not supported.
257 static apr_status_t crypto_cleanup(apr_crypto_t *f)
259 apr_crypto_key_t *key;
261 while ((key = apr_array_pop(f->keys))) {
263 PK11_FreeSymKey(key->symKey);
271 static apr_status_t crypto_cleanup_helper(void *data)
273 apr_crypto_t *f = (apr_crypto_t *) data;
274 return crypto_cleanup(f);
278 * @brief Create a context for supporting encryption. Keys, certificates,
279 * algorithms and other parameters will be set per context. More than
280 * one context can be created at one time. A cleanup will be automatically
281 * registered with the given pool to guarantee a graceful shutdown.
282 * @param f - context pointer will be written here
283 * @param provider - provider to use
284 * @param params - parameter string
285 * @param pool - process pool
286 * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE
287 * if the engine cannot be initialised.
289 static apr_status_t crypto_make(apr_crypto_t **ff,
290 const apr_crypto_driver_t *provider, const char *params,
293 apr_crypto_config_t *config = NULL;
296 f = apr_pcalloc(pool, sizeof(apr_crypto_t));
302 f->provider = provider;
303 config = f->config = apr_pcalloc(pool, sizeof(apr_crypto_config_t));
307 f->result = apr_pcalloc(pool, sizeof(apu_err_t));
311 f->keys = apr_array_make(pool, 10, sizeof(apr_crypto_key_t));
313 f->types = apr_hash_make(pool);
317 apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_3des_192));
318 apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_aes_128));
319 apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_aes_192));
320 apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_aes_256));
322 f->modes = apr_hash_make(pool);
326 apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(mode_ecb));
327 apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(mode_cbc));
329 apr_pool_cleanup_register(pool, f, crypto_cleanup_helper,
330 apr_pool_cleanup_null);
337 * @brief Get a hash table of key types, keyed by the name of the type against
338 * an integer pointer constant.
340 * @param types - hashtable of key types keyed to constants.
341 * @param f - encryption context
342 * @return APR_SUCCESS for success
344 static apr_status_t crypto_get_block_key_types(apr_hash_t **types,
345 const apr_crypto_t *f)
352 * @brief Get a hash table of key modes, keyed by the name of the mode against
353 * an integer pointer constant.
355 * @param modes - hashtable of key modes keyed to constants.
356 * @param f - encryption context
357 * @return APR_SUCCESS for success
359 static apr_status_t crypto_get_block_key_modes(apr_hash_t **modes,
360 const apr_crypto_t *f)
367 * @brief Create a key from the given passphrase. By default, the PBKDF2
368 * algorithm is used to generate the key from the passphrase. It is expected
369 * that the same pass phrase will generate the same key, regardless of the
370 * backend crypto platform used. The key is cleaned up when the context
371 * is cleaned, and may be reused with multiple encryption or decryption
373 * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
374 * *key is not NULL, *key must point at a previously created structure.
375 * @param key The key returned, see note.
376 * @param ivSize The size of the initialisation vector will be returned, based
377 * on whether an IV is relevant for this type of crypto.
378 * @param pass The passphrase to use.
379 * @param passLen The passphrase length in bytes
380 * @param salt The salt to use.
381 * @param saltLen The salt length in bytes
382 * @param type 3DES_192, AES_128, AES_192, AES_256.
383 * @param mode Electronic Code Book / Cipher Block Chaining.
384 * @param doPad Pad if necessary.
385 * @param iterations Iteration count
386 * @param f The context to use.
387 * @param p The pool to use.
388 * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
389 * error occurred while generating the key. APR_ENOCIPHER if the type or mode
390 * is not supported by the particular backend. APR_EKEYTYPE if the key type is
391 * not known. APR_EPADDING if padding was requested but is not supported.
392 * APR_ENOTIMPL if not implemented.
394 static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
395 const char *pass, apr_size_t passLen, const unsigned char * salt,
396 apr_size_t saltLen, const apr_crypto_block_key_type_e type,
397 const apr_crypto_block_key_mode_e mode, const int doPad,
398 const int iterations, const apr_crypto_t *f, apr_pool_t *p)
400 apr_status_t rv = APR_SUCCESS;
404 SECAlgorithmID *algid;
405 void *wincx = NULL; /* what is wincx? */
406 apr_crypto_key_t *key = *k;
409 *k = key = apr_array_push(f->keys);
416 key->provider = f->provider;
418 /* decide on what cipher mechanism we will be using */
421 case (APR_KEY_3DES_192):
422 if (APR_MODE_CBC == mode) {
423 key->cipherOid = SEC_OID_DES_EDE3_CBC;
425 else if (APR_MODE_ECB == mode) {
426 return APR_ENOCIPHER;
427 /* No OID for CKM_DES3_ECB; */
430 case (APR_KEY_AES_128):
431 if (APR_MODE_CBC == mode) {
432 key->cipherOid = SEC_OID_AES_128_CBC;
435 key->cipherOid = SEC_OID_AES_128_ECB;
438 case (APR_KEY_AES_192):
439 if (APR_MODE_CBC == mode) {
440 key->cipherOid = SEC_OID_AES_192_CBC;
443 key->cipherOid = SEC_OID_AES_192_ECB;
446 case (APR_KEY_AES_256):
447 if (APR_MODE_CBC == mode) {
448 key->cipherOid = SEC_OID_AES_256_CBC;
451 key->cipherOid = SEC_OID_AES_256_ECB;
455 /* unknown key type, give up */
459 /* AES_128_CBC --> CKM_AES_CBC --> CKM_AES_CBC_PAD */
460 key->cipherMech = PK11_AlgtagToMechanism(key->cipherOid);
461 if (key->cipherMech == CKM_INVALID_MECHANISM) {
462 return APR_ENOCIPHER;
465 CK_MECHANISM_TYPE paddedMech;
466 paddedMech = PK11_GetPadMechanism(key->cipherMech);
467 if (CKM_INVALID_MECHANISM == paddedMech || key->cipherMech
471 key->cipherMech = paddedMech;
474 /* Turn the raw passphrase and salt into SECItems */
475 passItem.data = (unsigned char*) pass;
476 passItem.len = passLen;
477 saltItem.data = (unsigned char*) salt;
478 saltItem.len = saltLen;
480 /* generate the key */
481 /* pbeAlg and cipherAlg are the same. NSS decides the keylength. */
482 algid = PK11_CreatePBEV2AlgorithmID(key->cipherOid, key->cipherOid,
483 SEC_OID_HMAC_SHA1, 0, iterations, &saltItem);
485 slot = PK11_GetBestSlot(key->cipherMech, wincx);
487 key->symKey = PK11_PBEKeyGen(slot, algid, &passItem, PR_FALSE,
491 SECOID_DestroyAlgorithmID(algid, PR_TRUE);
496 PRErrorCode perr = PORT_GetError();
498 f->result->rc = perr;
499 f->result->msg = PR_ErrorToName(perr);
504 key->ivSize = PK11_GetIVLength(key->cipherMech);
506 *ivSize = key->ivSize;
513 * @brief Initialise a context for encrypting arbitrary data using the given key.
514 * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
515 * *ctx is not NULL, *ctx must point at a previously created structure.
516 * @param ctx The block context returned, see note.
517 * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
518 * an IV will be created at random, in space allocated from the pool.
519 * If the buffer pointed to is not NULL, the IV in the buffer will be
521 * @param key The key structure.
522 * @param blockSize The block size of the cipher.
523 * @param p The pool to use.
524 * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
525 * Returns APR_EINIT if the backend failed to initialise the context. Returns
526 * APR_ENOTIMPL if not implemented.
528 static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
529 const unsigned char **iv, const apr_crypto_key_t *key,
530 apr_size_t *blockSize, apr_pool_t *p)
535 unsigned char * usedIv;
536 apr_crypto_block_t *block = *ctx;
538 *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
545 block->provider = key->provider;
547 apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
548 apr_pool_cleanup_null);
556 usedIv = apr_pcalloc(p, key->ivSize);
560 apr_crypto_clear(p, usedIv, key->ivSize);
561 s = PK11_GenerateRandom(usedIv, key->ivSize);
562 if (s != SECSuccess) {
568 usedIv = (unsigned char *) *iv;
570 ivItem.data = usedIv;
571 ivItem.len = key->ivSize;
572 secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
575 secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
577 block->blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
578 block->ctx = PK11_CreateContextBySymKey(key->cipherMech, CKA_ENCRYPT,
579 key->symKey, secParam);
581 /* did an error occur? */
582 perr = PORT_GetError();
583 if (perr || !block->ctx) {
584 key->f->result->rc = perr;
585 key->f->result->msg = PR_ErrorToName(perr);
590 *blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
598 * @brief Encrypt data provided by in, write it to out.
599 * @note The number of bytes written will be written to outlen. If
600 * out is NULL, outlen will contain the maximum size of the
601 * buffer needed to hold the data, including any data
602 * generated by apr_crypto_block_encrypt_finish below. If *out points
603 * to NULL, a buffer sufficiently large will be created from
604 * the pool provided. If *out points to a not-NULL value, this
605 * value will be used as a buffer instead.
606 * @param out Address of a buffer to which data will be written,
608 * @param outlen Length of the output will be written here.
609 * @param in Address of the buffer to read.
610 * @param inlen Length of the buffer to read.
611 * @param ctx The block context to use.
612 * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
615 static apr_status_t crypto_block_encrypt(unsigned char **out,
616 apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
617 apr_crypto_block_t *block)
620 unsigned char *buffer;
621 int outl = (int) *outlen;
624 *outlen = inlen + block->blockSize;
628 buffer = apr_palloc(block->pool, inlen + block->blockSize);
632 apr_crypto_clear(block->pool, buffer, inlen + block->blockSize);
636 s = PK11_CipherOp(block->ctx, *out, &outl, inlen, (unsigned char*) in,
638 if (s != SECSuccess) {
639 PRErrorCode perr = PORT_GetError();
641 block->f->result->rc = perr;
642 block->f->result->msg = PR_ErrorToName(perr);
653 * @brief Encrypt final data block, write it to out.
654 * @note If necessary the final block will be written out after being
655 * padded. Typically the final block will be written to the
656 * same buffer used by apr_crypto_block_encrypt, offset by the
657 * number of bytes returned as actually written by the
658 * apr_crypto_block_encrypt() call. After this call, the context
659 * is cleaned and can be reused by apr_crypto_block_encrypt_init().
660 * @param out Address of a buffer to which data will be written. This
661 * buffer must already exist, and is usually the same
662 * buffer used by apr_evp_crypt(). See note.
663 * @param outlen Length of the output will be written here.
664 * @param ctx The block context to use.
665 * @return APR_ECRYPT if an error occurred.
666 * @return APR_EPADDING if padding was enabled and the block was incorrectly
668 * @return APR_ENOTIMPL if not implemented.
670 static apr_status_t crypto_block_encrypt_finish(unsigned char *out,
671 apr_size_t *outlen, apr_crypto_block_t *block)
674 apr_status_t rv = APR_SUCCESS;
675 unsigned int outl = *outlen;
677 SECStatus s = PK11_DigestFinal(block->ctx, out, &outl, block->blockSize);
680 if (s != SECSuccess) {
681 PRErrorCode perr = PORT_GetError();
683 block->f->result->rc = perr;
684 block->f->result->msg = PR_ErrorToName(perr);
688 crypto_block_cleanup(block);
695 * @brief Initialise a context for decrypting arbitrary data using the given key.
696 * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
697 * *ctx is not NULL, *ctx must point at a previously created structure.
698 * @param ctx The block context returned, see note.
699 * @param blockSize The block size of the cipher.
700 * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
701 * an IV will be created at random, in space allocated from the pool.
702 * If the buffer is not NULL, the IV in the buffer will be used.
703 * @param key The key structure.
704 * @param p The pool to use.
705 * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
706 * Returns APR_EINIT if the backend failed to initialise the context. Returns
707 * APR_ENOTIMPL if not implemented.
709 static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
710 apr_size_t *blockSize, const unsigned char *iv,
711 const apr_crypto_key_t *key, apr_pool_t *p)
715 apr_crypto_block_t *block = *ctx;
717 *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
724 block->provider = key->provider;
726 apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
727 apr_pool_cleanup_null);
732 return APR_ENOIV; /* Cannot initialise without an IV */
734 ivItem.data = (unsigned char*) iv;
735 ivItem.len = key->ivSize;
736 secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
739 secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
741 block->blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
742 block->ctx = PK11_CreateContextBySymKey(key->cipherMech, CKA_DECRYPT,
743 key->symKey, secParam);
745 /* did an error occur? */
746 perr = PORT_GetError();
747 if (perr || !block->ctx) {
748 key->f->result->rc = perr;
749 key->f->result->msg = PR_ErrorToName(perr);
754 *blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
762 * @brief Decrypt data provided by in, write it to out.
763 * @note The number of bytes written will be written to outlen. If
764 * out is NULL, outlen will contain the maximum size of the
765 * buffer needed to hold the data, including any data
766 * generated by apr_crypto_block_decrypt_finish below. If *out points
767 * to NULL, a buffer sufficiently large will be created from
768 * the pool provided. If *out points to a not-NULL value, this
769 * value will be used as a buffer instead.
770 * @param out Address of a buffer to which data will be written,
772 * @param outlen Length of the output will be written here.
773 * @param in Address of the buffer to read.
774 * @param inlen Length of the buffer to read.
775 * @param ctx The block context to use.
776 * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
779 static apr_status_t crypto_block_decrypt(unsigned char **out,
780 apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
781 apr_crypto_block_t *block)
784 unsigned char *buffer;
785 int outl = (int) *outlen;
788 *outlen = inlen + block->blockSize;
792 buffer = apr_palloc(block->pool, inlen + block->blockSize);
796 apr_crypto_clear(block->pool, buffer, inlen + block->blockSize);
800 s = PK11_CipherOp(block->ctx, *out, &outl, inlen, (unsigned char*) in,
802 if (s != SECSuccess) {
803 PRErrorCode perr = PORT_GetError();
805 block->f->result->rc = perr;
806 block->f->result->msg = PR_ErrorToName(perr);
817 * @brief Decrypt final data block, write it to out.
818 * @note If necessary the final block will be written out after being
819 * padded. Typically the final block will be written to the
820 * same buffer used by apr_crypto_block_decrypt, offset by the
821 * number of bytes returned as actually written by the
822 * apr_crypto_block_decrypt() call. After this call, the context
823 * is cleaned and can be reused by apr_crypto_block_decrypt_init().
824 * @param out Address of a buffer to which data will be written. This
825 * buffer must already exist, and is usually the same
826 * buffer used by apr_evp_crypt(). See note.
827 * @param outlen Length of the output will be written here.
828 * @param ctx The block context to use.
829 * @return APR_ECRYPT if an error occurred.
830 * @return APR_EPADDING if padding was enabled and the block was incorrectly
832 * @return APR_ENOTIMPL if not implemented.
834 static apr_status_t crypto_block_decrypt_finish(unsigned char *out,
835 apr_size_t *outlen, apr_crypto_block_t *block)
838 apr_status_t rv = APR_SUCCESS;
839 unsigned int outl = *outlen;
841 SECStatus s = PK11_DigestFinal(block->ctx, out, &outl, block->blockSize);
844 if (s != SECSuccess) {
845 PRErrorCode perr = PORT_GetError();
847 block->f->result->rc = perr;
848 block->f->result->msg = PR_ErrorToName(perr);
852 crypto_block_cleanup(block);
861 APU_MODULE_DECLARE_DATA const apr_crypto_driver_t apr_crypto_nss_driver = {
862 "nss", crypto_init, crypto_make, crypto_get_block_key_types,
863 crypto_get_block_key_modes, crypto_passphrase,
864 crypto_block_encrypt_init, crypto_block_encrypt,
865 crypto_block_encrypt_finish, crypto_block_decrypt_init,
866 crypto_block_decrypt, crypto_block_decrypt_finish,
867 crypto_block_cleanup, crypto_cleanup, crypto_shutdown, crypto_error