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