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