]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/apr-util/crypto/apr_crypto_openssl.c
allwinner: clk: Fix nm clock calculation
[FreeBSD/FreeBSD.git] / contrib / apr-util / crypto / apr_crypto_openssl.c
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_errno.h"
20
21 #include <ctype.h>
22 #include <assert.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 <openssl/evp.h>
34 #include <openssl/rand.h>
35 #include <openssl/engine.h>
36
37 #define LOG_PREFIX "apr_crypto_openssl: "
38
39 #ifndef APR_USE_OPENSSL_PRE_1_1_API
40 #if defined(LIBRESSL_VERSION_NUMBER)
41 /* LibreSSL declares OPENSSL_VERSION_NUMBER == 2.0 but does not include most
42  * changes from OpenSSL >= 1.1 (new functions, macros, deprecations, ...), so
43  * we have to work around this...
44  */
45 #define APR_USE_OPENSSL_PRE_1_1_API (1)
46 #else
47 #define APR_USE_OPENSSL_PRE_1_1_API (OPENSSL_VERSION_NUMBER < 0x10100000L)
48 #endif
49 #endif
50
51 struct apr_crypto_t {
52     apr_pool_t *pool;
53     const apr_crypto_driver_t *provider;
54     apu_err_t *result;
55     apr_crypto_config_t *config;
56     apr_hash_t *types;
57     apr_hash_t *modes;
58 };
59
60 struct apr_crypto_config_t {
61     ENGINE *engine;
62 };
63
64 struct apr_crypto_key_t {
65     apr_pool_t *pool;
66     const apr_crypto_driver_t *provider;
67     const apr_crypto_t *f;
68     const EVP_CIPHER * cipher;
69     unsigned char *key;
70     int keyLen;
71     int doPad;
72     int ivSize;
73 };
74
75 struct apr_crypto_block_t {
76     apr_pool_t *pool;
77     const apr_crypto_driver_t *provider;
78     const apr_crypto_t *f;
79     EVP_CIPHER_CTX *cipherCtx;
80     int initialised;
81     int ivSize;
82     int blockSize;
83     int doPad;
84 };
85
86 static struct apr_crypto_block_key_type_t key_types[] =
87 {
88 { APR_KEY_3DES_192, 24, 8, 8 },
89 { APR_KEY_AES_128, 16, 16, 16 },
90 { APR_KEY_AES_192, 24, 16, 16 },
91 { APR_KEY_AES_256, 32, 16, 16 } };
92
93 static struct apr_crypto_block_key_mode_t key_modes[] =
94 {
95 { APR_MODE_ECB },
96 { APR_MODE_CBC } };
97
98 /* sufficient space to wrap a key */
99 #define BUFFER_SIZE 128
100
101 /**
102  * Fetch the most recent error from this driver.
103  */
104 static apr_status_t crypto_error(const apu_err_t **result,
105         const apr_crypto_t *f)
106 {
107     *result = f->result;
108     return APR_SUCCESS;
109 }
110
111 /**
112  * Shutdown the crypto library and release resources.
113  */
114 static apr_status_t crypto_shutdown(void)
115 {
116     ERR_free_strings();
117     EVP_cleanup();
118     ENGINE_cleanup();
119     return APR_SUCCESS;
120 }
121
122 static apr_status_t crypto_shutdown_helper(void *data)
123 {
124     return crypto_shutdown();
125 }
126
127 /**
128  * Initialise the crypto library and perform one time initialisation.
129  */
130 static apr_status_t crypto_init(apr_pool_t *pool, const char *params,
131         const apu_err_t **result)
132 {
133 #if APR_USE_OPENSSL_PRE_1_1_API
134     (void)CRYPTO_malloc_init();
135 #else
136     OPENSSL_malloc_init();
137 #endif
138     ERR_load_crypto_strings();
139     /* SSL_load_error_strings(); */
140     OpenSSL_add_all_algorithms();
141     ENGINE_load_builtin_engines();
142     ENGINE_register_all_complete();
143
144     apr_pool_cleanup_register(pool, pool, crypto_shutdown_helper,
145             apr_pool_cleanup_null);
146
147     return APR_SUCCESS;
148 }
149
150 #if OPENSSL_VERSION_NUMBER < 0x0090802fL
151
152 /* Code taken from OpenSSL 0.9.8b, see
153  * https://github.com/openssl/openssl/commit/cf6bc84148cb15af09b292394aaf2b45f0d5af0d
154  */
155
156 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
157 {
158      EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
159      if (ctx)
160          EVP_CIPHER_CTX_init(ctx);
161      return ctx;
162 }
163
164 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
165 {
166     if (ctx) {
167         EVP_CIPHER_CTX_cleanup(ctx);
168         OPENSSL_free(ctx);
169     }
170 }
171
172 #endif
173
174 /**
175  * @brief Clean encryption / decryption context.
176  * @note After cleanup, a context is free to be reused if necessary.
177  * @param ctx The block context to use.
178  * @return Returns APR_ENOTIMPL if not supported.
179  */
180 static apr_status_t crypto_block_cleanup(apr_crypto_block_t *ctx)
181 {
182
183     if (ctx->initialised) {
184         EVP_CIPHER_CTX_free(ctx->cipherCtx);
185         ctx->initialised = 0;
186     }
187
188     return APR_SUCCESS;
189
190 }
191
192 static apr_status_t crypto_block_cleanup_helper(void *data)
193 {
194     apr_crypto_block_t *block = (apr_crypto_block_t *) data;
195     return crypto_block_cleanup(block);
196 }
197
198 /**
199  * @brief Clean encryption / decryption context.
200  * @note After cleanup, a context is free to be reused if necessary.
201  * @param f The context to use.
202  * @return Returns APR_ENOTIMPL if not supported.
203  */
204 static apr_status_t crypto_cleanup(apr_crypto_t *f)
205 {
206
207     if (f->config->engine) {
208         ENGINE_finish(f->config->engine);
209         ENGINE_free(f->config->engine);
210         f->config->engine = NULL;
211     }
212     return APR_SUCCESS;
213
214 }
215
216 static apr_status_t crypto_cleanup_helper(void *data)
217 {
218     apr_crypto_t *f = (apr_crypto_t *) data;
219     return crypto_cleanup(f);
220 }
221
222 /**
223  * @brief Create a context for supporting encryption. Keys, certificates,
224  *        algorithms and other parameters will be set per context. More than
225  *        one context can be created at one time. A cleanup will be automatically
226  *        registered with the given pool to guarantee a graceful shutdown.
227  * @param f - context pointer will be written here
228  * @param provider - provider to use
229  * @param params - array of key parameters
230  * @param pool - process pool
231  * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE
232  * if the engine cannot be initialised.
233  */
234 static apr_status_t crypto_make(apr_crypto_t **ff,
235         const apr_crypto_driver_t *provider, const char *params,
236         apr_pool_t *pool)
237 {
238     apr_crypto_config_t *config = NULL;
239     apr_crypto_t *f = apr_pcalloc(pool, sizeof(apr_crypto_t));
240
241     const char *engine = NULL;
242
243     struct {
244         const char *field;
245         const char *value;
246         int set;
247     } fields[] = {
248         { "engine", NULL, 0 },
249         { NULL, NULL, 0 }
250     };
251     const char *ptr;
252     size_t klen;
253     char **elts = NULL;
254     char *elt;
255     int i = 0, j;
256     apr_status_t status;
257
258     if (params) {
259         if (APR_SUCCESS != (status = apr_tokenize_to_argv(params, &elts, pool))) {
260             return status;
261         }
262         while ((elt = elts[i])) {
263             ptr = strchr(elt, '=');
264             if (ptr) {
265                 for (klen = ptr - elt; klen && apr_isspace(elt[klen - 1]); --klen)
266                     ;
267                 ptr++;
268             }
269             else {
270                 for (klen = strlen(elt); klen && apr_isspace(elt[klen - 1]); --klen)
271                     ;
272             }
273             elt[klen] = 0;
274
275             for (j = 0; fields[j].field != NULL; ++j) {
276                 if (!strcasecmp(fields[j].field, elt)) {
277                     fields[j].set = 1;
278                     if (ptr) {
279                         fields[j].value = ptr;
280                     }
281                     break;
282                 }
283             }
284
285             i++;
286         }
287         engine = fields[0].value;
288     }
289
290     if (!f) {
291         return APR_ENOMEM;
292     }
293     *ff = f;
294     f->pool = pool;
295     f->provider = provider;
296     config = f->config = apr_pcalloc(pool, sizeof(apr_crypto_config_t));
297     if (!config) {
298         return APR_ENOMEM;
299     }
300
301     f->result = apr_pcalloc(pool, sizeof(apu_err_t));
302     if (!f->result) {
303         return APR_ENOMEM;
304     }
305
306     f->types = apr_hash_make(pool);
307     if (!f->types) {
308         return APR_ENOMEM;
309     }
310     apr_hash_set(f->types, "3des192", APR_HASH_KEY_STRING, &(key_types[0]));
311     apr_hash_set(f->types, "aes128", APR_HASH_KEY_STRING, &(key_types[1]));
312     apr_hash_set(f->types, "aes192", APR_HASH_KEY_STRING, &(key_types[2]));
313     apr_hash_set(f->types, "aes256", APR_HASH_KEY_STRING, &(key_types[3]));
314
315     f->modes = apr_hash_make(pool);
316     if (!f->modes) {
317         return APR_ENOMEM;
318     }
319     apr_hash_set(f->modes, "ecb", APR_HASH_KEY_STRING, &(key_modes[0]));
320     apr_hash_set(f->modes, "cbc", APR_HASH_KEY_STRING, &(key_modes[1]));
321
322     apr_pool_cleanup_register(pool, f, crypto_cleanup_helper,
323             apr_pool_cleanup_null);
324
325     if (engine) {
326         config->engine = ENGINE_by_id(engine);
327         if (!config->engine) {
328             return APR_ENOENGINE;
329         }
330         if (!ENGINE_init(config->engine)) {
331             ENGINE_free(config->engine);
332             config->engine = NULL;
333             return APR_EINITENGINE;
334         }
335     }
336
337     return APR_SUCCESS;
338
339 }
340
341 /**
342  * @brief Get a hash table of key types, keyed by the name of the type against
343  * a pointer to apr_crypto_block_key_type_t.
344  *
345  * @param types - hashtable of key types keyed to constants.
346  * @param f - encryption context
347  * @return APR_SUCCESS for success
348  */
349 static apr_status_t crypto_get_block_key_types(apr_hash_t **types,
350         const apr_crypto_t *f)
351 {
352     *types = f->types;
353     return APR_SUCCESS;
354 }
355
356 /**
357  * @brief Get a hash table of key modes, keyed by the name of the mode against
358  * a pointer to apr_crypto_block_key_mode_t.
359  *
360  * @param modes - hashtable of key modes keyed to constants.
361  * @param f - encryption context
362  * @return APR_SUCCESS for success
363  */
364 static apr_status_t crypto_get_block_key_modes(apr_hash_t **modes,
365         const apr_crypto_t *f)
366 {
367     *modes = f->modes;
368     return APR_SUCCESS;
369 }
370
371 /*
372  * Work out which mechanism to use.
373  */
374 static apr_status_t crypto_cipher_mechanism(apr_crypto_key_t *key,
375         const apr_crypto_block_key_type_e type,
376         const apr_crypto_block_key_mode_e mode, const int doPad, apr_pool_t *p)
377 {
378     /* determine the cipher to be used */
379     switch (type) {
380
381     case (APR_KEY_3DES_192):
382
383         /* A 3DES key */
384         if (mode == APR_MODE_CBC) {
385             key->cipher = EVP_des_ede3_cbc();
386         }
387         else {
388             key->cipher = EVP_des_ede3_ecb();
389         }
390         break;
391
392     case (APR_KEY_AES_128):
393
394         if (mode == APR_MODE_CBC) {
395             key->cipher = EVP_aes_128_cbc();
396         }
397         else {
398             key->cipher = EVP_aes_128_ecb();
399         }
400         break;
401
402     case (APR_KEY_AES_192):
403
404         if (mode == APR_MODE_CBC) {
405             key->cipher = EVP_aes_192_cbc();
406         }
407         else {
408             key->cipher = EVP_aes_192_ecb();
409         }
410         break;
411
412     case (APR_KEY_AES_256):
413
414         if (mode == APR_MODE_CBC) {
415             key->cipher = EVP_aes_256_cbc();
416         }
417         else {
418             key->cipher = EVP_aes_256_ecb();
419         }
420         break;
421
422     default:
423
424         /* unknown key type, give up */
425         return APR_EKEYTYPE;
426
427     }
428
429     /* find the length of the key we need */
430     key->keyLen = EVP_CIPHER_key_length(key->cipher);
431
432     /* make space for the key */
433     key->key = apr_pcalloc(p, key->keyLen);
434     if (!key->key) {
435         return APR_ENOMEM;
436     }
437     apr_crypto_clear(p, key->key, key->keyLen);
438
439     return APR_SUCCESS;
440 }
441
442 /**
443  * @brief Create a key from the provided secret or passphrase. The key is cleaned
444  *        up when the context is cleaned, and may be reused with multiple encryption
445  *        or decryption operations.
446  * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
447  *       *key is not NULL, *key must point at a previously created structure.
448  * @param key The key returned, see note.
449  * @param rec The key record, from which the key will be derived.
450  * @param f The context to use.
451  * @param p The pool to use.
452  * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
453  *         error occurred while generating the key. APR_ENOCIPHER if the type or mode
454  *         is not supported by the particular backend. APR_EKEYTYPE if the key type is
455  *         not known. APR_EPADDING if padding was requested but is not supported.
456  *         APR_ENOTIMPL if not implemented.
457  */
458 static apr_status_t crypto_key(apr_crypto_key_t **k,
459         const apr_crypto_key_rec_t *rec, const apr_crypto_t *f, apr_pool_t *p)
460 {
461     apr_crypto_key_t *key = *k;
462     apr_status_t rv;
463
464     if (!key) {
465         *k = key = apr_pcalloc(p, sizeof *key);
466         if (!key) {
467             return APR_ENOMEM;
468         }
469     }
470
471     key->f = f;
472     key->provider = f->provider;
473
474     /* decide on what cipher mechanism we will be using */
475     rv = crypto_cipher_mechanism(key, rec->type, rec->mode, rec->pad, p);
476     if (APR_SUCCESS != rv) {
477         return rv;
478     }
479
480     switch (rec->ktype) {
481
482     case APR_CRYPTO_KTYPE_PASSPHRASE: {
483
484         /* generate the key */
485         if (PKCS5_PBKDF2_HMAC_SHA1(rec->k.passphrase.pass,
486                 rec->k.passphrase.passLen,
487                 (unsigned char *) rec->k.passphrase.salt,
488                 rec->k.passphrase.saltLen, rec->k.passphrase.iterations,
489                 key->keyLen, key->key) == 0) {
490             return APR_ENOKEY;
491         }
492
493         break;
494     }
495
496     case APR_CRYPTO_KTYPE_SECRET: {
497
498         /* sanity check - key correct size? */
499         if (rec->k.secret.secretLen != key->keyLen) {
500             return APR_EKEYLENGTH;
501         }
502
503         /* copy the key */
504         memcpy(key->key, rec->k.secret.secret, rec->k.secret.secretLen);
505
506         break;
507     }
508
509     default: {
510
511         return APR_ENOKEY;
512
513     }
514     }
515
516     key->doPad = rec->pad;
517
518     /* note: openssl incorrectly returns non zero IV size values for ECB
519      * algorithms, so work around this by ignoring the IV size.
520      */
521     if (APR_MODE_ECB != rec->mode) {
522         key->ivSize = EVP_CIPHER_iv_length(key->cipher);
523     }
524
525     return APR_SUCCESS;
526 }
527
528 /**
529  * @brief Create a key from the given passphrase. By default, the PBKDF2
530  *        algorithm is used to generate the key from the passphrase. It is expected
531  *        that the same pass phrase will generate the same key, regardless of the
532  *        backend crypto platform used. The key is cleaned up when the context
533  *        is cleaned, and may be reused with multiple encryption or decryption
534  *        operations.
535  * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
536  *       *key is not NULL, *key must point at a previously created structure.
537  * @param key The key returned, see note.
538  * @param ivSize The size of the initialisation vector will be returned, based
539  *               on whether an IV is relevant for this type of crypto.
540  * @param pass The passphrase to use.
541  * @param passLen The passphrase length in bytes
542  * @param salt The salt to use.
543  * @param saltLen The salt length in bytes
544  * @param type 3DES_192, AES_128, AES_192, AES_256.
545  * @param mode Electronic Code Book / Cipher Block Chaining.
546  * @param doPad Pad if necessary.
547  * @param iterations Iteration count
548  * @param f The context to use.
549  * @param p The pool to use.
550  * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
551  *         error occurred while generating the key. APR_ENOCIPHER if the type or mode
552  *         is not supported by the particular backend. APR_EKEYTYPE if the key type is
553  *         not known. APR_EPADDING if padding was requested but is not supported.
554  *         APR_ENOTIMPL if not implemented.
555  */
556 static apr_status_t crypto_passphrase(apr_crypto_key_t **k, apr_size_t *ivSize,
557         const char *pass, apr_size_t passLen, const unsigned char * salt,
558         apr_size_t saltLen, const apr_crypto_block_key_type_e type,
559         const apr_crypto_block_key_mode_e mode, const int doPad,
560         const int iterations, const apr_crypto_t *f, apr_pool_t *p)
561 {
562     apr_crypto_key_t *key = *k;
563     apr_status_t rv;
564
565     if (!key) {
566         *k = key = apr_pcalloc(p, sizeof *key);
567         if (!key) {
568             return APR_ENOMEM;
569         }
570     }
571
572     key->f = f;
573     key->provider = f->provider;
574
575     /* decide on what cipher mechanism we will be using */
576     rv = crypto_cipher_mechanism(key, type, mode, doPad, p);
577     if (APR_SUCCESS != rv) {
578         return rv;
579     }
580
581     /* generate the key */
582     if (PKCS5_PBKDF2_HMAC_SHA1(pass, passLen, (unsigned char *) salt, saltLen,
583             iterations, key->keyLen, key->key) == 0) {
584         return APR_ENOKEY;
585     }
586
587     key->doPad = doPad;
588
589     /* note: openssl incorrectly returns non zero IV size values for ECB
590      * algorithms, so work around this by ignoring the IV size.
591      */
592     if (APR_MODE_ECB != mode) {
593         key->ivSize = EVP_CIPHER_iv_length(key->cipher);
594     }
595     if (ivSize) {
596         *ivSize = key->ivSize;
597     }
598
599     return APR_SUCCESS;
600 }
601
602 /**
603  * @brief Initialise a context for encrypting arbitrary data using the given key.
604  * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
605  *       *ctx is not NULL, *ctx must point at a previously created structure.
606  * @param ctx The block context returned, see note.
607  * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
608  *           an IV will be created at random, in space allocated from the pool.
609  *           If the buffer pointed to is not NULL, the IV in the buffer will be
610  *           used.
611  * @param key The key structure.
612  * @param blockSize The block size of the cipher.
613  * @param p The pool to use.
614  * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
615  *         Returns APR_EINIT if the backend failed to initialise the context. Returns
616  *         APR_ENOTIMPL if not implemented.
617  */
618 static apr_status_t crypto_block_encrypt_init(apr_crypto_block_t **ctx,
619         const unsigned char **iv, const apr_crypto_key_t *key,
620         apr_size_t *blockSize, apr_pool_t *p)
621 {
622     unsigned char *usedIv;
623     apr_crypto_config_t *config = key->f->config;
624     apr_crypto_block_t *block = *ctx;
625     if (!block) {
626         *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
627     }
628     if (!block) {
629         return APR_ENOMEM;
630     }
631     block->f = key->f;
632     block->pool = p;
633     block->provider = key->provider;
634
635     apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
636             apr_pool_cleanup_null);
637
638     /* create a new context for encryption */
639     if (!block->initialised) {
640         block->cipherCtx = EVP_CIPHER_CTX_new();
641         block->initialised = 1;
642     }
643
644     /* generate an IV, if necessary */
645     usedIv = NULL;
646     if (key->ivSize) {
647         if (iv == NULL) {
648             return APR_ENOIV;
649         }
650         if (*iv == NULL) {
651             usedIv = apr_pcalloc(p, key->ivSize);
652             if (!usedIv) {
653                 return APR_ENOMEM;
654             }
655             apr_crypto_clear(p, usedIv, key->ivSize);
656             if (!((RAND_status() == 1)
657                     && (RAND_bytes(usedIv, key->ivSize) == 1))) {
658                 return APR_ENOIV;
659             }
660             *iv = usedIv;
661         }
662         else {
663             usedIv = (unsigned char *) *iv;
664         }
665     }
666
667     /* set up our encryption context */
668 #if CRYPTO_OPENSSL_CONST_BUFFERS
669     if (!EVP_EncryptInit_ex(block->cipherCtx, key->cipher, config->engine,
670             key->key, usedIv)) {
671 #else
672         if (!EVP_EncryptInit_ex(block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) usedIv)) {
673 #endif
674         return APR_EINIT;
675     }
676
677     /* Clear up any read padding */
678     if (!EVP_CIPHER_CTX_set_padding(block->cipherCtx, key->doPad)) {
679         return APR_EPADDING;
680     }
681
682     if (blockSize) {
683         *blockSize = EVP_CIPHER_block_size(key->cipher);
684     }
685
686     return APR_SUCCESS;
687
688 }
689
690 /**
691  * @brief Encrypt data provided by in, write it to out.
692  * @note The number of bytes written will be written to outlen. If
693  *       out is NULL, outlen will contain the maximum size of the
694  *       buffer needed to hold the data, including any data
695  *       generated by apr_crypto_block_encrypt_finish below. If *out points
696  *       to NULL, a buffer sufficiently large will be created from
697  *       the pool provided. If *out points to a not-NULL value, this
698  *       value will be used as a buffer instead.
699  * @param out Address of a buffer to which data will be written,
700  *        see note.
701  * @param outlen Length of the output will be written here.
702  * @param in Address of the buffer to read.
703  * @param inlen Length of the buffer to read.
704  * @param ctx The block context to use.
705  * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
706  *         not implemented.
707  */
708 static apr_status_t crypto_block_encrypt(unsigned char **out,
709         apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
710         apr_crypto_block_t *ctx)
711 {
712     int outl = *outlen;
713     unsigned char *buffer;
714
715     /* are we after the maximum size of the out buffer? */
716     if (!out) {
717         *outlen = inlen + EVP_MAX_BLOCK_LENGTH;
718         return APR_SUCCESS;
719     }
720
721     /* must we allocate the output buffer from a pool? */
722     if (!*out) {
723         buffer = apr_palloc(ctx->pool, inlen + EVP_MAX_BLOCK_LENGTH);
724         if (!buffer) {
725             return APR_ENOMEM;
726         }
727         apr_crypto_clear(ctx->pool, buffer, inlen + EVP_MAX_BLOCK_LENGTH);
728         *out = buffer;
729     }
730
731 #if CRYPT_OPENSSL_CONST_BUFFERS
732     if (!EVP_EncryptUpdate(ctx->cipherCtx, (*out), &outl, in, inlen)) {
733 #else
734     if (!EVP_EncryptUpdate(ctx->cipherCtx, (*out), &outl,
735             (unsigned char *) in, inlen)) {
736 #endif
737 #if APR_USE_OPENSSL_PRE_1_1_API
738         EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
739 #else
740         EVP_CIPHER_CTX_reset(ctx->cipherCtx);
741 #endif
742         return APR_ECRYPT;
743     }
744     *outlen = outl;
745
746     return APR_SUCCESS;
747
748 }
749
750 /**
751  * @brief Encrypt final data block, write it to out.
752  * @note If necessary the final block will be written out after being
753  *       padded. Typically the final block will be written to the
754  *       same buffer used by apr_crypto_block_encrypt, offset by the
755  *       number of bytes returned as actually written by the
756  *       apr_crypto_block_encrypt() call. After this call, the context
757  *       is cleaned and can be reused by apr_crypto_block_encrypt_init().
758  * @param out Address of a buffer to which data will be written. This
759  *            buffer must already exist, and is usually the same
760  *            buffer used by apr_evp_crypt(). See note.
761  * @param outlen Length of the output will be written here.
762  * @param ctx The block context to use.
763  * @return APR_ECRYPT if an error occurred.
764  * @return APR_EPADDING if padding was enabled and the block was incorrectly
765  *         formatted.
766  * @return APR_ENOTIMPL if not implemented.
767  */
768 static apr_status_t crypto_block_encrypt_finish(unsigned char *out,
769         apr_size_t *outlen, apr_crypto_block_t *ctx)
770 {
771     apr_status_t rc = APR_SUCCESS;
772     int len = *outlen;
773
774     if (EVP_EncryptFinal_ex(ctx->cipherCtx, out, &len) == 0) {
775         rc = APR_EPADDING;
776     }
777     else {
778         *outlen = len;
779     }
780 #if APR_USE_OPENSSL_PRE_1_1_API
781     EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
782 #else
783     EVP_CIPHER_CTX_reset(ctx->cipherCtx);
784 #endif
785
786     return rc;
787
788 }
789
790 /**
791  * @brief Initialise a context for decrypting arbitrary data using the given key.
792  * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
793  *       *ctx is not NULL, *ctx must point at a previously created structure.
794  * @param ctx The block context returned, see note.
795  * @param blockSize The block size of the cipher.
796  * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
797  *           an IV will be created at random, in space allocated from the pool.
798  *           If the buffer is not NULL, the IV in the buffer will be used.
799  * @param key The key structure.
800  * @param p The pool to use.
801  * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
802  *         Returns APR_EINIT if the backend failed to initialise the context. Returns
803  *         APR_ENOTIMPL if not implemented.
804  */
805 static apr_status_t crypto_block_decrypt_init(apr_crypto_block_t **ctx,
806         apr_size_t *blockSize, const unsigned char *iv,
807         const apr_crypto_key_t *key, apr_pool_t *p)
808 {
809     apr_crypto_config_t *config = key->f->config;
810     apr_crypto_block_t *block = *ctx;
811     if (!block) {
812         *ctx = block = apr_pcalloc(p, sizeof(apr_crypto_block_t));
813     }
814     if (!block) {
815         return APR_ENOMEM;
816     }
817     block->f = key->f;
818     block->pool = p;
819     block->provider = key->provider;
820
821     apr_pool_cleanup_register(p, block, crypto_block_cleanup_helper,
822             apr_pool_cleanup_null);
823
824     /* create a new context for encryption */
825     if (!block->initialised) {
826         block->cipherCtx = EVP_CIPHER_CTX_new();
827         block->initialised = 1;
828     }
829
830     /* generate an IV, if necessary */
831     if (key->ivSize) {
832         if (iv == NULL) {
833             return APR_ENOIV;
834         }
835     }
836
837     /* set up our encryption context */
838 #if CRYPTO_OPENSSL_CONST_BUFFERS
839     if (!EVP_DecryptInit_ex(block->cipherCtx, key->cipher, config->engine,
840             key->key, iv)) {
841 #else
842         if (!EVP_DecryptInit_ex(block->cipherCtx, key->cipher, config->engine, (unsigned char *) key->key, (unsigned char *) iv)) {
843 #endif
844         return APR_EINIT;
845     }
846
847     /* Clear up any read padding */
848     if (!EVP_CIPHER_CTX_set_padding(block->cipherCtx, key->doPad)) {
849         return APR_EPADDING;
850     }
851
852     if (blockSize) {
853         *blockSize = EVP_CIPHER_block_size(key->cipher);
854     }
855
856     return APR_SUCCESS;
857
858 }
859
860 /**
861  * @brief Decrypt data provided by in, write it to out.
862  * @note The number of bytes written will be written to outlen. If
863  *       out is NULL, outlen will contain the maximum size of the
864  *       buffer needed to hold the data, including any data
865  *       generated by apr_crypto_block_decrypt_finish below. If *out points
866  *       to NULL, a buffer sufficiently large will be created from
867  *       the pool provided. If *out points to a not-NULL value, this
868  *       value will be used as a buffer instead.
869  * @param out Address of a buffer to which data will be written,
870  *        see note.
871  * @param outlen Length of the output will be written here.
872  * @param in Address of the buffer to read.
873  * @param inlen Length of the buffer to read.
874  * @param ctx The block context to use.
875  * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
876  *         not implemented.
877  */
878 static apr_status_t crypto_block_decrypt(unsigned char **out,
879         apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
880         apr_crypto_block_t *ctx)
881 {
882     int outl = *outlen;
883     unsigned char *buffer;
884
885     /* are we after the maximum size of the out buffer? */
886     if (!out) {
887         *outlen = inlen + EVP_MAX_BLOCK_LENGTH;
888         return APR_SUCCESS;
889     }
890
891     /* must we allocate the output buffer from a pool? */
892     if (!(*out)) {
893         buffer = apr_palloc(ctx->pool, inlen + EVP_MAX_BLOCK_LENGTH);
894         if (!buffer) {
895             return APR_ENOMEM;
896         }
897         apr_crypto_clear(ctx->pool, buffer, inlen + EVP_MAX_BLOCK_LENGTH);
898         *out = buffer;
899     }
900
901 #if CRYPT_OPENSSL_CONST_BUFFERS
902     if (!EVP_DecryptUpdate(ctx->cipherCtx, *out, &outl, in, inlen)) {
903 #else
904     if (!EVP_DecryptUpdate(ctx->cipherCtx, *out, &outl, (unsigned char *) in,
905             inlen)) {
906 #endif
907 #if APR_USE_OPENSSL_PRE_1_1_API
908         EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
909 #else
910         EVP_CIPHER_CTX_reset(ctx->cipherCtx);
911 #endif
912         return APR_ECRYPT;
913     }
914     *outlen = outl;
915
916     return APR_SUCCESS;
917
918 }
919
920 /**
921  * @brief Decrypt final data block, write it to out.
922  * @note If necessary the final block will be written out after being
923  *       padded. Typically the final block will be written to the
924  *       same buffer used by apr_crypto_block_decrypt, offset by the
925  *       number of bytes returned as actually written by the
926  *       apr_crypto_block_decrypt() call. After this call, the context
927  *       is cleaned and can be reused by apr_crypto_block_decrypt_init().
928  * @param out Address of a buffer to which data will be written. This
929  *            buffer must already exist, and is usually the same
930  *            buffer used by apr_evp_crypt(). See note.
931  * @param outlen Length of the output will be written here.
932  * @param ctx The block context to use.
933  * @return APR_ECRYPT if an error occurred.
934  * @return APR_EPADDING if padding was enabled and the block was incorrectly
935  *         formatted.
936  * @return APR_ENOTIMPL if not implemented.
937  */
938 static apr_status_t crypto_block_decrypt_finish(unsigned char *out,
939         apr_size_t *outlen, apr_crypto_block_t *ctx)
940 {
941     apr_status_t rc = APR_SUCCESS;
942     int len = *outlen;
943
944     if (EVP_DecryptFinal_ex(ctx->cipherCtx, out, &len) == 0) {
945         rc = APR_EPADDING;
946     }
947     else {
948         *outlen = len;
949     }
950 #if APR_USE_OPENSSL_PRE_1_1_API
951     EVP_CIPHER_CTX_cleanup(ctx->cipherCtx);
952 #else
953     EVP_CIPHER_CTX_reset(ctx->cipherCtx);
954 #endif
955
956     return rc;
957
958 }
959
960 /**
961  * OpenSSL module.
962  */
963 APU_MODULE_DECLARE_DATA const apr_crypto_driver_t apr_crypto_openssl_driver = {
964     "openssl", crypto_init, crypto_make, crypto_get_block_key_types,
965     crypto_get_block_key_modes, crypto_passphrase,
966     crypto_block_encrypt_init, crypto_block_encrypt,
967     crypto_block_encrypt_finish, crypto_block_decrypt_init,
968     crypto_block_decrypt, crypto_block_decrypt_finish,
969     crypto_block_cleanup, crypto_cleanup, crypto_shutdown, crypto_error,
970     crypto_key
971 };
972
973 #endif