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 <ctype.h>
18#include <stdio.h>
19
20#include "apu_config.h"
21#include "apu.h"
22#include "apr_pools.h"
23#include "apr_dso.h"
24#include "apr_strings.h"
25#include "apr_hash.h"
26#include "apr_thread_mutex.h"
27#include "apr_lib.h"
28
29#if APU_HAVE_CRYPTO
30
31#include "apu_internal.h"
32#include "apr_crypto_internal.h"
33#include "apr_crypto.h"
34#include "apu_version.h"
35
36static apr_hash_t *drivers = NULL;
37
38#define ERROR_SIZE 1024
39
40#define CLEANUP_CAST (apr_status_t (*)(void*))
41
42#define APR_TYPEDEF_STRUCT(type, incompletion) \
43struct type { \
44   incompletion \
45   void *unk[]; \
46};
47
48APR_TYPEDEF_STRUCT(apr_crypto_t,
49    apr_pool_t *pool;
50    apr_crypto_driver_t *provider;
51)
52
53APR_TYPEDEF_STRUCT(apr_crypto_key_t,
54    apr_pool_t *pool;
55    apr_crypto_driver_t *provider;
56    const apr_crypto_t *f;
57)
58
59APR_TYPEDEF_STRUCT(apr_crypto_block_t,
60    apr_pool_t *pool;
61    apr_crypto_driver_t *provider;
62    const apr_crypto_t *f;
63)
64
65typedef struct apr_crypto_clear_t {
66    void *buffer;
67    apr_size_t size;
68} apr_crypto_clear_t;
69
70#if !APU_DSO_BUILD
71#define DRIVER_LOAD(name,driver_name,pool,params,rv,result) \
72    {   \
73        extern const apr_crypto_driver_t driver_name; \
74        apr_hash_set(drivers,name,APR_HASH_KEY_STRING,&driver_name); \
75        if (driver_name.init) {     \
76            rv = driver_name.init(pool, params, result); \
77        }  \
78        *driver = &driver_name; \
79    }
80#endif
81
82static apr_status_t apr_crypto_term(void *ptr)
83{
84    /* set drivers to NULL so init can work again */
85    drivers = NULL;
86
87    /* Everything else we need is handled by cleanups registered
88     * when we created mutexes and loaded DSOs
89     */
90    return APR_SUCCESS;
91}
92
93APU_DECLARE(apr_status_t) apr_crypto_init(apr_pool_t *pool)
94{
95    apr_status_t ret = APR_SUCCESS;
96    apr_pool_t *parent;
97
98    if (drivers != NULL) {
99        return APR_SUCCESS;
100    }
101
102    /* Top level pool scope, need process-scope lifetime */
103    for (parent = pool; parent; parent = apr_pool_parent_get(pool))
104        pool = parent;
105#if APU_DSO_BUILD
106    /* deprecate in 2.0 - permit implicit initialization */
107    apu_dso_init(pool);
108#endif
109    drivers = apr_hash_make(pool);
110
111    apr_pool_cleanup_register(pool, NULL, apr_crypto_term,
112            apr_pool_cleanup_null);
113
114    return ret;
115}
116
117static apr_status_t crypto_clear(void *ptr)
118{
119    apr_crypto_clear_t *clear = (apr_crypto_clear_t *)ptr;
120
121    memset(clear->buffer, 0, clear->size);
122    clear->buffer = NULL;
123    clear->size = 0;
124
125    return APR_SUCCESS;
126}
127
128APU_DECLARE(apr_status_t) apr_crypto_clear(apr_pool_t *pool,
129        void *buffer, apr_size_t size)
130{
131    apr_crypto_clear_t *clear = apr_palloc(pool, sizeof(apr_crypto_clear_t));
132
133    clear->buffer = buffer;
134    clear->size = size;
135
136    apr_pool_cleanup_register(pool, clear, crypto_clear,
137            apr_pool_cleanup_null);
138
139    return APR_SUCCESS;
140}
141
142APU_DECLARE(apr_status_t) apr_crypto_get_driver(
143        const apr_crypto_driver_t **driver, const char *name,
144        const char *params, const apu_err_t **result, apr_pool_t *pool)
145{
146#if APU_DSO_BUILD
147    char modname[32];
148    char symname[34];
149    apr_dso_handle_t *dso;
150    apr_dso_handle_sym_t symbol;
151#endif
152    apr_status_t rv;
153
154    if (result) {
155        *result = NULL; /* until further notice */
156    }
157
158#if APU_DSO_BUILD
159    rv = apu_dso_mutex_lock();
160    if (rv) {
161        return rv;
162    }
163#endif
164    *driver = apr_hash_get(drivers, name, APR_HASH_KEY_STRING);
165    if (*driver) {
166#if APU_DSO_BUILD
167        apu_dso_mutex_unlock();
168#endif
169        return APR_SUCCESS;
170    }
171
172#if APU_DSO_BUILD
173    /* The driver DSO must have exactly the same lifetime as the
174     * drivers hash table; ignore the passed-in pool */
175    pool = apr_hash_pool_get(drivers);
176
177#if defined(NETWARE)
178    apr_snprintf(modname, sizeof(modname), "crypto%s.nlm", name);
179#elif defined(WIN32)
180    apr_snprintf(modname, sizeof(modname),
181            "apr_crypto_%s-" APU_STRINGIFY(APU_MAJOR_VERSION) ".dll", name);
182#else
183    apr_snprintf(modname, sizeof(modname),
184            "apr_crypto_%s-" APU_STRINGIFY(APU_MAJOR_VERSION) ".so", name);
185#endif
186    apr_snprintf(symname, sizeof(symname), "apr_crypto_%s_driver", name);
187    rv = apu_dso_load(&dso, &symbol, modname, symname, pool);
188    if (rv == APR_SUCCESS || rv == APR_EINIT) { /* previously loaded?!? */
189        *driver = symbol;
190        name = apr_pstrdup(pool, name);
191        apr_hash_set(drivers, name, APR_HASH_KEY_STRING, *driver);
192        rv = APR_SUCCESS;
193        if ((*driver)->init) {
194            rv = (*driver)->init(pool, params, result);
195        }
196    }
197    apu_dso_mutex_unlock();
198
199    if (APR_SUCCESS != rv && result && !*result) {
200        char *buffer = apr_pcalloc(pool, ERROR_SIZE);
201        apu_err_t *err = apr_pcalloc(pool, sizeof(apu_err_t));
202        if (err && buffer) {
203            apr_dso_error(dso, buffer, ERROR_SIZE - 1);
204            err->msg = buffer;
205            err->reason = modname;
206            *result = err;
207        }
208    }
209
210#else /* not builtin and !APR_HAS_DSO => not implemented */
211    rv = APR_ENOTIMPL;
212
213    /* Load statically-linked drivers: */
214#if APU_HAVE_OPENSSL
215    if (name[0] == 'o' && !strcmp(name, "openssl")) {
216        DRIVER_LOAD("openssl", apr_crypto_openssl_driver, pool, params, rv, result);
217    }
218#endif
219#if APU_HAVE_NSS
220    if (name[0] == 'n' && !strcmp(name, "nss")) {
221        DRIVER_LOAD("nss", apr_crypto_nss_driver, pool, params, rv, result);
222    }
223#endif
224#if APU_HAVE_MSCAPI
225    if (name[0] == 'm' && !strcmp(name, "mscapi")) {
226        DRIVER_LOAD("mscapi", apr_crypto_mscapi_driver, pool, params, rv, result);
227    }
228#endif
229#if APU_HAVE_MSCNG
230    if (name[0] == 'm' && !strcmp(name, "mscng")) {
231        DRIVER_LOAD("mscng", apr_crypto_mscng_driver, pool, params, rv, result);
232    }
233#endif
234
235#endif
236
237    return rv;
238}
239
240/**
241 * @brief Return the name of the driver.
242 *
243 * @param driver - The driver in use.
244 * @return The name of the driver.
245 */
246APU_DECLARE(const char *)apr_crypto_driver_name (
247        const apr_crypto_driver_t *driver)
248{
249    return driver->name;
250}
251
252/**
253 * @brief Get the result of the last operation on a context. If the result
254 *        is NULL, the operation was successful.
255 * @param result - the result structure
256 * @param f - context pointer
257 * @return APR_SUCCESS for success
258 */
259APU_DECLARE(apr_status_t) apr_crypto_error(const apu_err_t **result,
260        const apr_crypto_t *f)
261{
262    return f->provider->error(result, f);
263}
264
265/**
266 * @brief Create a context for supporting encryption. Keys, certificates,
267 *        algorithms and other parameters will be set per context. More than
268 *        one context can be created at one time. A cleanup will be automatically
269 *        registered with the given pool to guarantee a graceful shutdown.
270 * @param f - context pointer will be written here
271 * @param driver - driver to use
272 * @param params - array of key parameters
273 * @param pool - process pool
274 * @return APR_ENOENGINE when the engine specified does not exist. APR_EINITENGINE
275 * if the engine cannot be initialised.
276 * @remarks NSS: currently no params are supported.
277 * @remarks OpenSSL: the params can have "engine" as a key, followed by an equal
278 *  sign and a value.
279 */
280APU_DECLARE(apr_status_t) apr_crypto_make(apr_crypto_t **f,
281        const apr_crypto_driver_t *driver, const char *params, apr_pool_t *pool)
282{
283    return driver->make(f, driver, params, pool);
284}
285
286/**
287 * @brief Get a hash table of key types, keyed by the name of the type against
288 * an integer pointer constant.
289 *
290 * @param types - hashtable of key types keyed to constants.
291 * @param f - encryption context
292 * @return APR_SUCCESS for success
293 */
294APU_DECLARE(apr_status_t) apr_crypto_get_block_key_types(apr_hash_t **types,
295        const apr_crypto_t *f)
296{
297    return f->provider->get_block_key_types(types, f);
298}
299
300/**
301 * @brief Get a hash table of key modes, keyed by the name of the mode against
302 * an integer pointer constant.
303 *
304 * @param modes - hashtable of key modes keyed to constants.
305 * @param f - encryption context
306 * @return APR_SUCCESS for success
307 */
308APU_DECLARE(apr_status_t) apr_crypto_get_block_key_modes(apr_hash_t **modes,
309        const apr_crypto_t *f)
310{
311    return f->provider->get_block_key_modes(modes, f);
312}
313
314/**
315 * @brief Create a key from the given passphrase. By default, the PBKDF2
316 *        algorithm is used to generate the key from the passphrase. It is expected
317 *        that the same pass phrase will generate the same key, regardless of the
318 *        backend crypto platform used. The key is cleaned up when the context
319 *        is cleaned, and may be reused with multiple encryption or decryption
320 *        operations.
321 * @note If *key is NULL, a apr_crypto_key_t will be created from a pool. If
322 *       *key is not NULL, *key must point at a previously created structure.
323 * @param key The key returned, see note.
324 * @param ivSize The size of the initialisation vector will be returned, based
325 *               on whether an IV is relevant for this type of crypto.
326 * @param pass The passphrase to use.
327 * @param passLen The passphrase length in bytes
328 * @param salt The salt to use.
329 * @param saltLen The salt length in bytes
330 * @param type 3DES_192, AES_128, AES_192, AES_256.
331 * @param mode Electronic Code Book / Cipher Block Chaining.
332 * @param doPad Pad if necessary.
333 * @param iterations Number of iterations to use in algorithm
334 * @param f The context to use.
335 * @param p The pool to use.
336 * @return Returns APR_ENOKEY if the pass phrase is missing or empty, or if a backend
337 *         error occurred while generating the key. APR_ENOCIPHER if the type or mode
338 *         is not supported by the particular backend. APR_EKEYTYPE if the key type is
339 *         not known. APR_EPADDING if padding was requested but is not supported.
340 *         APR_ENOTIMPL if not implemented.
341 */
342APU_DECLARE(apr_status_t) apr_crypto_passphrase(apr_crypto_key_t **key,
343        apr_size_t *ivSize, const char *pass, apr_size_t passLen,
344        const unsigned char * salt, apr_size_t saltLen,
345        const apr_crypto_block_key_type_e type,
346        const apr_crypto_block_key_mode_e mode, const int doPad,
347        const int iterations, const apr_crypto_t *f, apr_pool_t *p)
348{
349    return f->provider->passphrase(key, ivSize, pass, passLen, salt, saltLen,
350            type, mode, doPad, iterations, f, p);
351}
352
353/**
354 * @brief Initialise a context for encrypting arbitrary data using the given key.
355 * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
356 *       *ctx is not NULL, *ctx must point at a previously created structure.
357 * @param ctx The block context returned, see note.
358 * @param iv Optional initialisation vector. If the buffer pointed to is NULL,
359 *           an IV will be created at random, in space allocated from the pool.
360 *           If the buffer pointed to is not NULL, the IV in the buffer will be
361 *           used.
362 * @param key The key structure to use.
363 * @param blockSize The block size of the cipher.
364 * @param p The pool to use.
365 * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
366 *         Returns APR_EINIT if the backend failed to initialise the context. Returns
367 *         APR_ENOTIMPL if not implemented.
368 */
369APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_init(
370        apr_crypto_block_t **ctx, const unsigned char **iv,
371        const apr_crypto_key_t *key, apr_size_t *blockSize, apr_pool_t *p)
372{
373    return key->provider->block_encrypt_init(ctx, iv, key, blockSize, p);
374}
375
376/**
377 * @brief Encrypt data provided by in, write it to out.
378 * @note The number of bytes written will be written to outlen. If
379 *       out is NULL, outlen will contain the maximum size of the
380 *       buffer needed to hold the data, including any data
381 *       generated by apr_crypto_block_encrypt_finish below. If *out points
382 *       to NULL, a buffer sufficiently large will be created from
383 *       the pool provided. If *out points to a not-NULL value, this
384 *       value will be used as a buffer instead.
385 * @param out Address of a buffer to which data will be written,
386 *        see note.
387 * @param outlen Length of the output will be written here.
388 * @param in Address of the buffer to read.
389 * @param inlen Length of the buffer to read.
390 * @param ctx The block context to use.
391 * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
392 *         not implemented.
393 */
394APU_DECLARE(apr_status_t) apr_crypto_block_encrypt(unsigned char **out,
395        apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
396        apr_crypto_block_t *ctx)
397{
398    return ctx->provider->block_encrypt(out, outlen, in, inlen, ctx);
399}
400
401/**
402 * @brief Encrypt final data block, write it to out.
403 * @note If necessary the final block will be written out after being
404 *       padded. Typically the final block will be written to the
405 *       same buffer used by apr_crypto_block_encrypt, offset by the
406 *       number of bytes returned as actually written by the
407 *       apr_crypto_block_encrypt() call. After this call, the context
408 *       is cleaned and can be reused by apr_crypto_block_encrypt_init().
409 * @param out Address of a buffer to which data will be written. This
410 *            buffer must already exist, and is usually the same
411 *            buffer used by apr_evp_crypt(). See note.
412 * @param outlen Length of the output will be written here.
413 * @param ctx The block context to use.
414 * @return APR_ECRYPT if an error occurred.
415 * @return APR_EPADDING if padding was enabled and the block was incorrectly
416 *         formatted.
417 * @return APR_ENOTIMPL if not implemented.
418 */
419APU_DECLARE(apr_status_t) apr_crypto_block_encrypt_finish(unsigned char *out,
420        apr_size_t *outlen, apr_crypto_block_t *ctx)
421{
422    return ctx->provider->block_encrypt_finish(out, outlen, ctx);
423}
424
425/**
426 * @brief Initialise a context for decrypting arbitrary data using the given key.
427 * @note If *ctx is NULL, a apr_crypto_block_t will be created from a pool. If
428 *       *ctx is not NULL, *ctx must point at a previously created structure.
429 * @param ctx The block context returned, see note.
430 * @param blockSize The block size of the cipher.
431 * @param iv Optional initialisation vector.
432 * @param key The key structure to use.
433 * @param p The pool to use.
434 * @return Returns APR_ENOIV if an initialisation vector is required but not specified.
435 *         Returns APR_EINIT if the backend failed to initialise the context. Returns
436 *         APR_ENOTIMPL if not implemented.
437 */
438APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_init(
439        apr_crypto_block_t **ctx, apr_size_t *blockSize,
440        const unsigned char *iv, const apr_crypto_key_t *key, apr_pool_t *p)
441{
442    return key->provider->block_decrypt_init(ctx, blockSize, iv, key, p);
443}
444
445/**
446 * @brief Decrypt data provided by in, write it to out.
447 * @note The number of bytes written will be written to outlen. If
448 *       out is NULL, outlen will contain the maximum size of the
449 *       buffer needed to hold the data, including any data
450 *       generated by apr_crypto_block_decrypt_finish below. If *out points
451 *       to NULL, a buffer sufficiently large will be created from
452 *       the pool provided. If *out points to a not-NULL value, this
453 *       value will be used as a buffer instead.
454 * @param out Address of a buffer to which data will be written,
455 *        see note.
456 * @param outlen Length of the output will be written here.
457 * @param in Address of the buffer to read.
458 * @param inlen Length of the buffer to read.
459 * @param ctx The block context to use.
460 * @return APR_ECRYPT if an error occurred. Returns APR_ENOTIMPL if
461 *         not implemented.
462 */
463APU_DECLARE(apr_status_t) apr_crypto_block_decrypt(unsigned char **out,
464        apr_size_t *outlen, const unsigned char *in, apr_size_t inlen,
465        apr_crypto_block_t *ctx)
466{
467    return ctx->provider->block_decrypt(out, outlen, in, inlen, ctx);
468}
469
470/**
471 * @brief Decrypt final data block, write it to out.
472 * @note If necessary the final block will be written out after being
473 *       padded. Typically the final block will be written to the
474 *       same buffer used by apr_crypto_block_decrypt, offset by the
475 *       number of bytes returned as actually written by the
476 *       apr_crypto_block_decrypt() call. After this call, the context
477 *       is cleaned and can be reused by apr_crypto_block_decrypt_init().
478 * @param out Address of a buffer to which data will be written. This
479 *            buffer must already exist, and is usually the same
480 *            buffer used by apr_evp_crypt(). See note.
481 * @param outlen Length of the output will be written here.
482 * @param ctx The block context to use.
483 * @return APR_ECRYPT if an error occurred.
484 * @return APR_EPADDING if padding was enabled and the block was incorrectly
485 *         formatted.
486 * @return APR_ENOTIMPL if not implemented.
487 */
488APU_DECLARE(apr_status_t) apr_crypto_block_decrypt_finish(unsigned char *out,
489        apr_size_t *outlen, apr_crypto_block_t *ctx)
490{
491    return ctx->provider->block_decrypt_finish(out, outlen, ctx);
492}
493
494/**
495 * @brief Clean encryption / decryption context.
496 * @note After cleanup, a context is free to be reused if necessary.
497 * @param ctx The block context to use.
498 * @return Returns APR_ENOTIMPL if not supported.
499 */
500APU_DECLARE(apr_status_t) apr_crypto_block_cleanup(apr_crypto_block_t *ctx)
501{
502    return ctx->provider->block_cleanup(ctx);
503}
504
505/**
506 * @brief Clean encryption / decryption context.
507 * @note After cleanup, a context is free to be reused if necessary.
508 * @param f The context to use.
509 * @return Returns APR_ENOTIMPL if not supported.
510 */
511APU_DECLARE(apr_status_t) apr_crypto_cleanup(apr_crypto_t *f)
512{
513    return f->provider->cleanup(f);
514}
515
516/**
517 * @brief Shutdown the crypto library.
518 * @note After shutdown, it is expected that the init function can be called again.
519 * @param driver - driver to use
520 * @return Returns APR_ENOTIMPL if not supported.
521 */
522APU_DECLARE(apr_status_t) apr_crypto_shutdown(const apr_crypto_driver_t *driver)
523{
524    return driver->shutdown();
525}
526
527#endif /* APU_HAVE_CRYPTO */
528