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
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "apr_lib.h"
18#include "apu.h"
19#include "apu_config.h"
20#include "apu_errno.h"
21
22#include <ctype.h>
23#include <stdlib.h>
24
25#include "apr_strings.h"
26#include "apr_time.h"
27#include "apr_buckets.h"
28
29#include "apr_crypto_internal.h"
30
31#if APU_HAVE_CRYPTO
32
33#include <prerror.h>
34
35#ifdef HAVE_NSS_NSS_H
36#include <nss/nss.h>
37#endif
38#ifdef HAVE_NSS_H
39#include <nss.h>
40#endif
41
42#ifdef HAVE_NSS_PK11PUB_H
43#include <nss/pk11pub.h>
44#endif
45#ifdef HAVE_PK11PUB_H
46#include <pk11pub.h>
47#endif
48
49struct apr_crypto_t {
50    apr_pool_t *pool;
51    const apr_crypto_driver_t *provider;
52    apu_err_t *result;
53    apr_array_header_t *keys;
54    apr_crypto_config_t *config;
55    apr_hash_t *types;
56    apr_hash_t *modes;
57};
58
59struct apr_crypto_config_t {
60       void *opaque;
61};
62
63struct apr_crypto_key_t {
64    apr_pool_t *pool;
65    const apr_crypto_driver_t *provider;
66    const apr_crypto_t *f;
67    CK_MECHANISM_TYPE cipherMech;
68    SECOidTag cipherOid;
69    PK11SymKey *symKey;
70    int ivSize;
71};
72
73struct apr_crypto_block_t {
74    apr_pool_t *pool;
75    const apr_crypto_driver_t *provider;
76    const apr_crypto_t *f;
77    PK11Context *ctx;
78    apr_crypto_key_t *key;
79    int blockSize;
80};
81
82static int key_3des_192 = APR_KEY_3DES_192;
83static int key_aes_128 = APR_KEY_AES_128;
84static int key_aes_192 = APR_KEY_AES_192;
85static int key_aes_256 = APR_KEY_AES_256;
86
87static int mode_ecb = APR_MODE_ECB;
88static int mode_cbc = APR_MODE_CBC;
89
90/**
91 * Fetch the most recent error from this driver.
92 */
93static apr_status_t crypto_error(const apu_err_t **result,
94        const apr_crypto_t *f)
95{
96    *result = f->result;
97    return APR_SUCCESS;
98}
99
100/**
101 * Shutdown the crypto library and release resources.
102 *
103 * It is safe to shut down twice.
104 */
105static apr_status_t crypto_shutdown(void)
106{
107    if (NSS_IsInitialized()) {
108        SECStatus s = NSS_Shutdown();
109        if (s != SECSuccess) {
110            return APR_EINIT;
111        }
112    }
113    return APR_SUCCESS;
114}
115
116static apr_status_t crypto_shutdown_helper(void *data)
117{
118    return crypto_shutdown();
119}
120
121/**
122 * Initialise the crypto library and perform one time initialisation.
123 */
124static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
125        const apu_err_t **result)
126{
127    SECStatus s;
128    const char *dir = NULL;
129    const char *keyPrefix = NULL;
130    const char *certPrefix = NULL;
131    const char *secmod = NULL;
132    int noinit = 0;
133    PRUint32 flags = 0;
134
135    struct {
136        const char *field;
137        const char *value;
138        int set;
139    } fields[] = {
140        { "dir", NULL, 0 },
141        { "key3", NULL, 0 },
142        { "cert7", NULL, 0 },
143        { "secmod", NULL, 0 },
144        { "noinit", NULL, 0 },
145        { NULL, NULL, 0 }
146    };
147    const char *ptr;
148    size_t klen;
149    char **elts = NULL;
150    char *elt;
151    int i = 0, j;
152    apr_status_t status;
153
154    if (params) {
155        if (APR_SUCCESS != (status = apr_tokenize_to_argv(params, &elts, pool))) {
156            return status;
157        }
158        while ((elt = elts[i])) {
159            ptr = strchr(elt, '=');
160            if (ptr) {
161                for (klen = ptr - elt; klen && apr_isspace(elt[klen - 1]); --klen)
162                    ;
163                ptr++;
164            }
165            else {
166                for (klen = strlen(elt); klen && apr_isspace(elt[klen - 1]); --klen)
167                    ;
168            }
169            elt[klen] = 0;
170
171            for (j = 0; fields[j].field != NULL; ++j) {
172                if (klen && !strcasecmp(fields[j].field, elt)) {
173                    fields[j].set = 1;
174                    if (ptr) {
175                        fields[j].value = ptr;
176                    }
177                    break;
178                }
179            }
180
181            i++;
182        }
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;
188    }
189
190    /* if we've been asked to bypass, do so here */
191    if (noinit) {
192        return APR_SUCCESS;
193    }
194
195    /* sanity check - we can only initialise NSS once */
196    if (NSS_IsInitialized()) {
197        return APR_EREINIT;
198    }
199
200    apr_pool_cleanup_register(pool, pool, crypto_shutdown_helper,
201            apr_pool_cleanup_null);
202
203    if (keyPrefix || certPrefix || secmod) {
204        s = NSS_Initialize(dir, certPrefix, keyPrefix, secmod, flags);
205    }
206    else if (dir) {
207        s = NSS_InitReadWrite(dir);
208    }
209    else {
210        s = NSS_NoDB_Init(NULL);
211    }
212    if (s != SECSuccess) {
213        if (result) {
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";
218            *result = err;
219        }
220        return APR_ECRYPT;
221    }
222
223    return APR_SUCCESS;
224
225}
226
227/**
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.
232 */
233static apr_status_t crypto_block_cleanup(apr_crypto_block_t *block)
234{
235
236    if (block->ctx) {
237        PK11_DestroyContext(block->ctx, PR_TRUE);
238        block->ctx = NULL;
239    }
240
241    return APR_SUCCESS;
242
243}
244
245static apr_status_t crypto_block_cleanup_helper(void *data)
246{
247    apr_crypto_block_t *block = (apr_crypto_block_t *) data;
248    return crypto_block_cleanup(block);
249}
250
251/**
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.
256 */
257static apr_status_t crypto_cleanup(apr_crypto_t *f)
258{
259    apr_crypto_key_t *key;
260    if (f->keys) {
261        while ((key = apr_array_pop(f->keys))) {
262            if (key->symKey) {
263                PK11_FreeSymKey(key->symKey);
264                key->symKey = NULL;
265            }
266        }
267    }
268    return APR_SUCCESS;
269}
270
271static apr_status_t crypto_cleanup_helper(void *data)
272{
273    apr_crypto_t *f = (apr_crypto_t *) data;
274    return crypto_cleanup(f);
275}
276
277/**
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.
288 */
289static apr_status_t crypto_make(apr_crypto_t **ff,
290        const apr_crypto_driver_t *provider, const char *params,
291        apr_pool_t *pool)
292{
293    apr_crypto_config_t *config = NULL;
294    apr_crypto_t *f;
295
296    f = apr_pcalloc(pool, sizeof(apr_crypto_t));
297    if (!f) {
298        return APR_ENOMEM;
299    }
300    *ff = f;
301    f->pool = pool;
302    f->provider = provider;
303    config = f->config = apr_pcalloc(pool, sizeof(apr_crypto_config_t));
304    if (!config) {
305        return APR_ENOMEM;
306    }
307    f->result = apr_pcalloc(pool, sizeof(apu_err_t));
308    if (!f->result) {
309        return APR_ENOMEM;
310    }
311    f->keys = apr_array_make(pool, 10, sizeof(apr_crypto_key_t));
312
313    f->types = apr_hash_make(pool);
314    if (!f->types) {
315        return APR_ENOMEM;
316    }
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));
321
322    f->modes = apr_hash_make(pool);
323    if (!f->modes) {
324        return APR_ENOMEM;
325    }
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));
328
329    apr_pool_cleanup_register(pool, f, crypto_cleanup_helper,
330            apr_pool_cleanup_null);
331
332    return APR_SUCCESS;
333
334}
335
336/**
337 * @brief Get a hash table of key types, keyed by the name of the type against
338 * an integer pointer constant.
339 *
340 * @param types - hashtable of key types keyed to constants.
341 * @param f - encryption context
342 * @return APR_SUCCESS for success
343 */
344static apr_status_t crypto_get_block_key_types(apr_hash_t **types,
345        const apr_crypto_t *f)
346{
347    *types = f->types;
348    return APR_SUCCESS;
349}
350
351/**
352 * @brief Get a hash table of key modes, keyed by the name of the mode against
353 * an integer pointer constant.
354 *
355 * @param modes - hashtable of key modes keyed to constants.
356 * @param f - encryption context
357 * @return APR_SUCCESS for success
358 */
359static apr_status_t crypto_get_block_key_modes(apr_hash_t **modes,
360        const apr_crypto_t *f)
361{
362    *modes = f->modes;
363    return APR_SUCCESS;
364}
365
366/**
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
372 *        operations.
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.
393 */
394static 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)
399{
400    apr_status_t rv = APR_SUCCESS;
401    PK11SlotInfo * slot;
402    SECItem passItem;
403    SECItem saltItem;
404    SECAlgorithmID *algid;
405    void *wincx = NULL; /* what is wincx? */
406    apr_crypto_key_t *key = *k;
407
408    if (!key) {
409        *k = key = apr_array_push(f->keys);
410    }
411    if (!key) {
412        return APR_ENOMEM;
413    }
414
415    key->f = f;
416    key->provider = f->provider;
417
418    /* decide on what cipher mechanism we will be using */
419    switch (type) {
420
421    case (APR_KEY_3DES_192):
422        if (APR_MODE_CBC == mode) {
423            key->cipherOid = SEC_OID_DES_EDE3_CBC;
424        }
425        else if (APR_MODE_ECB == mode) {
426            return APR_ENOCIPHER;
427            /* No OID for CKM_DES3_ECB; */
428        }
429        break;
430    case (APR_KEY_AES_128):
431        if (APR_MODE_CBC == mode) {
432            key->cipherOid = SEC_OID_AES_128_CBC;
433        }
434        else {
435            key->cipherOid = SEC_OID_AES_128_ECB;
436        }
437        break;
438    case (APR_KEY_AES_192):
439        if (APR_MODE_CBC == mode) {
440            key->cipherOid = SEC_OID_AES_192_CBC;
441        }
442        else {
443            key->cipherOid = SEC_OID_AES_192_ECB;
444        }
445        break;
446    case (APR_KEY_AES_256):
447        if (APR_MODE_CBC == mode) {
448            key->cipherOid = SEC_OID_AES_256_CBC;
449        }
450        else {
451            key->cipherOid = SEC_OID_AES_256_ECB;
452        }
453        break;
454    default:
455        /* unknown key type, give up */
456        return APR_EKEYTYPE;
457    }
458
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;
463    }
464    if (doPad) {
465        CK_MECHANISM_TYPE paddedMech;
466        paddedMech = PK11_GetPadMechanism(key->cipherMech);
467        if (CKM_INVALID_MECHANISM == paddedMech || key->cipherMech
468                == paddedMech) {
469            return APR_EPADDING;
470        }
471        key->cipherMech = paddedMech;
472    }
473
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;
479
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);
484    if (algid) {
485        slot = PK11_GetBestSlot(key->cipherMech, wincx);
486        if (slot) {
487            key->symKey = PK11_PBEKeyGen(slot, algid, &passItem, PR_FALSE,
488                    wincx);
489            PK11_FreeSlot(slot);
490        }
491        SECOID_DestroyAlgorithmID(algid, PR_TRUE);
492    }
493
494    /* sanity check? */
495    if (!key->symKey) {
496        PRErrorCode perr = PORT_GetError();
497        if (perr) {
498            f->result->rc = perr;
499            f->result->msg = PR_ErrorToName(perr);
500            rv = APR_ENOKEY;
501        }
502    }
503
504    key->ivSize = PK11_GetIVLength(key->cipherMech);
505    if (ivSize) {
506        *ivSize = key->ivSize;
507    }
508
509    return rv;
510}
511
512/**
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
520 *           used.
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.
527 */
528static 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)
531{
532    PRErrorCode perr;
533    SECItem * secParam;
534    SECItem ivItem;
535    unsigned char * usedIv;
536    apr_crypto_block_t *block = *ctx;
537    if (!block) {
538        *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
539    }
540    if (!block) {
541        return APR_ENOMEM;
542    }
543    block->f = key->f;
544    block->pool = p;
545    block->provider = key->provider;
546
547    apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
548            apr_pool_cleanup_null);
549
550    if (key->ivSize) {
551        if (iv == NULL) {
552            return APR_ENOIV;
553        }
554        if (*iv == NULL) {
555            SECStatus s;
556            usedIv = apr_pcalloc(p, key->ivSize);
557            if (!usedIv) {
558                return APR_ENOMEM;
559            }
560            apr_crypto_clear(p, usedIv, key->ivSize);
561            s = PK11_GenerateRandom(usedIv, key->ivSize);
562            if (s != SECSuccess) {
563                return APR_ENOIV;
564            }
565            *iv = usedIv;
566        }
567        else {
568            usedIv = (unsigned char *) *iv;
569        }
570        ivItem.data = usedIv;
571        ivItem.len = key->ivSize;
572        secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
573    }
574    else {
575        secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
576    }
577    block->blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
578    block->ctx = PK11_CreateContextBySymKey(key->cipherMech, CKA_ENCRYPT,
579            key->symKey, secParam);
580
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);
586        return APR_EINIT;
587    }
588
589    if (blockSize) {
590        *blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
591    }
592
593    return APR_SUCCESS;
594
595}
596
597/**
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,
607 *        see note.
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
613 *         not implemented.
614 */
615static 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)
618{
619
620    unsigned char *buffer;
621    int outl = (int) *outlen;
622    SECStatus s;
623    if (!out) {
624        *outlen = inlen + block->blockSize;
625        return APR_SUCCESS;
626    }
627    if (!*out) {
628        buffer = apr_palloc(block->pool, inlen + block->blockSize);
629        if (!buffer) {
630            return APR_ENOMEM;
631        }
632        apr_crypto_clear(block->pool, buffer, inlen + block->blockSize);
633        *out = buffer;
634    }
635
636    s = PK11_CipherOp(block->ctx, *out, &outl, inlen, (unsigned char*) in,
637            inlen);
638    if (s != SECSuccess) {
639        PRErrorCode perr = PORT_GetError();
640        if (perr) {
641            block->f->result->rc = perr;
642            block->f->result->msg = PR_ErrorToName(perr);
643        }
644        return APR_ECRYPT;
645    }
646    *outlen = outl;
647
648    return APR_SUCCESS;
649
650}
651
652/**
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
667 *         formatted.
668 * @return APR_ENOTIMPL if not implemented.
669 */
670static apr_status_t crypto_block_encrypt_finish(unsigned char *out,
671        apr_size_t *outlen, apr_crypto_block_t *block)
672{
673
674    apr_status_t rv = APR_SUCCESS;
675    unsigned int outl = *outlen;
676
677    SECStatus s = PK11_DigestFinal(block->ctx, out, &outl, block->blockSize);
678    *outlen = outl;
679
680    if (s != SECSuccess) {
681        PRErrorCode perr = PORT_GetError();
682        if (perr) {
683            block->f->result->rc = perr;
684            block->f->result->msg = PR_ErrorToName(perr);
685        }
686        rv = APR_ECRYPT;
687    }
688    crypto_block_cleanup(block);
689
690    return rv;
691
692}
693
694/**
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.
708 */
709static 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)
712{
713    PRErrorCode perr;
714    SECItem * secParam;
715    apr_crypto_block_t *block = *ctx;
716    if (!block) {
717        *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
718    }
719    if (!block) {
720        return APR_ENOMEM;
721    }
722    block->f = key->f;
723    block->pool = p;
724    block->provider = key->provider;
725
726    apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
727            apr_pool_cleanup_null);
728
729    if (key->ivSize) {
730        SECItem ivItem;
731        if (iv == NULL) {
732            return APR_ENOIV; /* Cannot initialise without an IV */
733        }
734        ivItem.data = (unsigned char*) iv;
735        ivItem.len = key->ivSize;
736        secParam = PK11_ParamFromIV(key->cipherMech, &ivItem);
737    }
738    else {
739        secParam = PK11_GenerateNewParam(key->cipherMech, key->symKey);
740    }
741    block->blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
742    block->ctx = PK11_CreateContextBySymKey(key->cipherMech, CKA_DECRYPT,
743            key->symKey, secParam);
744
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);
750        return APR_EINIT;
751    }
752
753    if (blockSize) {
754        *blockSize = PK11_GetBlockSize(key->cipherMech, secParam);
755    }
756
757    return APR_SUCCESS;
758
759}
760
761/**
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,
771 *        see note.
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
777 *         not implemented.
778 */
779static 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)
782{
783
784    unsigned char *buffer;
785    int outl = (int) *outlen;
786    SECStatus s;
787    if (!out) {
788        *outlen = inlen + block->blockSize;
789        return APR_SUCCESS;
790    }
791    if (!*out) {
792        buffer = apr_palloc(block->pool, inlen + block->blockSize);
793        if (!buffer) {
794            return APR_ENOMEM;
795        }
796        apr_crypto_clear(block->pool, buffer, inlen + block->blockSize);
797        *out = buffer;
798    }
799
800    s = PK11_CipherOp(block->ctx, *out, &outl, inlen, (unsigned char*) in,
801            inlen);
802    if (s != SECSuccess) {
803        PRErrorCode perr = PORT_GetError();
804        if (perr) {
805            block->f->result->rc = perr;
806            block->f->result->msg = PR_ErrorToName(perr);
807        }
808        return APR_ECRYPT;
809    }
810    *outlen = outl;
811
812    return APR_SUCCESS;
813
814}
815
816/**
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
831 *         formatted.
832 * @return APR_ENOTIMPL if not implemented.
833 */
834static apr_status_t crypto_block_decrypt_finish(unsigned char *out,
835        apr_size_t *outlen, apr_crypto_block_t *block)
836{
837
838    apr_status_t rv = APR_SUCCESS;
839    unsigned int outl = *outlen;
840
841    SECStatus s = PK11_DigestFinal(block->ctx, out, &outl, block->blockSize);
842    *outlen = outl;
843
844    if (s != SECSuccess) {
845        PRErrorCode perr = PORT_GetError();
846        if (perr) {
847            block->f->result->rc = perr;
848            block->f->result->msg = PR_ErrorToName(perr);
849        }
850        rv = APR_ECRYPT;
851    }
852    crypto_block_cleanup(block);
853
854    return rv;
855
856}
857
858/**
859 * NSS module.
860 */
861APU_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
868};
869
870#endif
871