bugfix with strerror_r - still not working but at least not using uninitialized data
[anytun.git] / src / openvpn / crypto.c
blob4f07651dea6641be5258cb261055f342cc5e4cfe
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #ifdef WIN32
26 #include "config-win32.h"
27 #else
28 #include "config.h"
29 #endif
31 #ifdef USE_CRYPTO
33 #include "syshead.h"
35 #include "crypto.h"
36 #include "error.h"
37 #include "misc.h"
38 #include "thread.h"
40 #include "memdbg.h"
43 * Check for key size creepage.
46 #if MAX_CIPHER_KEY_LENGTH < EVP_MAX_KEY_LENGTH
47 #warning Some OpenSSL EVP ciphers now support key lengths greater than MAX_CIPHER_KEY_LENGTH -- consider increasing MAX_CIPHER_KEY_LENGTH
48 #endif
50 #if MAX_HMAC_KEY_LENGTH < EVP_MAX_MD_SIZE
51 #warning Some OpenSSL HMAC message digests now support key lengths greater than MAX_HMAC_KEY_LENGTH -- consider increasing MAX_HMAC_KEY_LENGTH
52 #endif
55 * Encryption and Compression Routines.
57 * On entry, buf contains the input data and length.
58 * On exit, it should be set to the output data and length.
60 * If buf->len is <= 0 we should return
61 * If buf->len is set to 0 on exit it tells the caller to ignore the packet.
63 * work is a workspace buffer we are given of size BUF_SIZE.
64 * work may be used to return output data, or the input buffer
65 * may be modified and returned as output. If output data is
66 * returned in work, the data should start after FRAME_HEADROOM bytes
67 * of padding to leave room for downstream routines to prepend.
69 * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
70 * by all routines (encryption, decryption, compression, and decompression).
72 * Note that the buf_prepend return will assert if we try to
73 * make a header bigger than FRAME_HEADROOM. This should not
74 * happen unless the frame parameters are wrong.
77 #define CRYPT_ERROR(format) \
78 do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
80 void
81 openvpn_encrypt (struct buffer *buf, struct buffer work,
82 const struct crypto_options *opt,
83 const struct frame* frame)
85 struct gc_arena gc;
86 gc_init (&gc);
88 if (buf->len > 0 && opt->key_ctx_bi)
90 struct key_ctx *ctx = &opt->key_ctx_bi->encrypt;
92 /* Do Encrypt from buf -> work */
93 if (ctx->cipher)
95 uint8_t iv_buf[EVP_MAX_IV_LENGTH];
96 const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
97 const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);
98 int outlen;
100 if (mode == EVP_CIPH_CBC_MODE)
102 CLEAR (iv_buf);
104 /* generate pseudo-random IV */
105 if (opt->flags & CO_USE_IV)
106 prng_bytes (iv_buf, iv_size);
108 /* Put packet ID in plaintext buffer or IV, depending on cipher mode */
109 if (opt->packet_id)
111 struct packet_id_net pin;
112 packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM));
113 ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true));
116 else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
118 struct packet_id_net pin;
119 struct buffer b;
121 ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */
122 ASSERT (opt->packet_id); /* for this mode. */
124 packet_id_alloc_outgoing (&opt->packet_id->send, &pin, true);
125 memset (iv_buf, 0, iv_size);
126 buf_set_write (&b, iv_buf, iv_size);
127 ASSERT (packet_id_write (&pin, &b, true, false));
129 else /* We only support CBC, CFB, or OFB modes right now */
131 ASSERT (0);
134 /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
135 ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
137 /* set the IV pseudo-randomly */
138 if (opt->flags & CO_USE_IV)
139 dmsg (D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
141 dmsg (D_PACKET_CONTENT, "ENCRYPT FROM: %s",
142 format_hex (BPTR (buf), BLEN (buf), 80, &gc));
144 /* cipher_ctx was already initialized with key & keylen */
145 ASSERT (EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_ENCRYPT));
147 /* Buffer overflow check */
148 if (!buf_safe (&work, buf->len + EVP_CIPHER_CTX_block_size (ctx->cipher)))
150 msg (D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d",
151 buf->capacity,
152 buf->offset,
153 buf->len,
154 work.capacity,
155 work.offset,
156 work.len,
157 EVP_CIPHER_CTX_block_size (ctx->cipher));
158 goto err;
161 /* Encrypt packet ID, payload */
162 ASSERT (EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
163 work.len += outlen;
165 /* Flush the encryption buffer */
166 ASSERT (EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen));
167 work.len += outlen;
168 ASSERT (outlen == iv_size);
170 /* prepend the IV to the ciphertext */
171 if (opt->flags & CO_USE_IV)
173 uint8_t *output = buf_prepend (&work, iv_size);
174 ASSERT (output);
175 memcpy (output, iv_buf, iv_size);
178 dmsg (D_PACKET_CONTENT, "ENCRYPT TO: %s",
179 format_hex (BPTR (&work), BLEN (&work), 80, &gc));
181 else /* No Encryption */
183 if (opt->packet_id)
185 struct packet_id_net pin;
186 packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM));
187 ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true));
189 work = *buf;
192 /* HMAC the ciphertext (or plaintext if !cipher) */
193 if (ctx->hmac)
195 int hmac_len;
196 uint8_t *output;
198 HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
199 HMAC_Update (ctx->hmac, BPTR (&work), BLEN (&work));
200 output = buf_prepend (&work, HMAC_size (ctx->hmac));
201 ASSERT (output);
202 HMAC_Final (ctx->hmac, output, (unsigned int *)&hmac_len);
203 ASSERT (hmac_len == HMAC_size (ctx->hmac));
206 *buf = work;
209 gc_free (&gc);
210 return;
212 err:
213 ERR_clear_error ();
214 buf->len = 0;
215 gc_free (&gc);
216 return;
220 * If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet.
222 * Set buf->len to 0 and return false on decrypt error.
224 * On success, buf is set to point to plaintext, true
225 * is returned.
227 bool
228 openvpn_decrypt (struct buffer *buf, struct buffer work,
229 const struct crypto_options *opt,
230 const struct frame* frame)
232 static const char error_prefix[] = "Authenticate/Decrypt packet error";
233 struct gc_arena gc;
234 gc_init (&gc);
236 if (buf->len > 0 && opt->key_ctx_bi)
238 struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
239 struct packet_id_net pin;
240 bool have_pin = false;
242 /* Verify the HMAC */
243 if (ctx->hmac)
245 int hmac_len;
246 uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
247 int in_hmac_len;
249 HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
251 /* Assume the length of the input HMAC */
252 hmac_len = HMAC_size (ctx->hmac);
254 /* Authentication fails if insufficient data in packet for HMAC */
255 if (buf->len < hmac_len)
256 CRYPT_ERROR ("missing authentication info");
258 HMAC_Update (ctx->hmac, BPTR (buf) + hmac_len,
259 BLEN (buf) - hmac_len);
260 HMAC_Final (ctx->hmac, local_hmac, (unsigned int *)&in_hmac_len);
261 ASSERT (hmac_len == in_hmac_len);
263 /* Compare locally computed HMAC with packet HMAC */
264 if (memcmp (local_hmac, BPTR (buf), hmac_len))
265 CRYPT_ERROR ("packet HMAC authentication failed");
267 ASSERT (buf_advance (buf, hmac_len));
270 /* Decrypt packet ID + payload */
272 if (ctx->cipher)
274 const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);
275 const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
276 uint8_t iv_buf[EVP_MAX_IV_LENGTH];
277 int outlen;
279 /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
280 ASSERT (buf_init (&work, FRAME_HEADROOM_ADJ (frame, FRAME_HEADROOM_MARKER_DECRYPT)));
282 /* use IV if user requested it */
283 CLEAR (iv_buf);
284 if (opt->flags & CO_USE_IV)
286 if (buf->len < iv_size)
287 CRYPT_ERROR ("missing IV info");
288 memcpy (iv_buf, BPTR (buf), iv_size);
289 ASSERT (buf_advance (buf, iv_size));
292 /* show the IV's initial state */
293 if (opt->flags & CO_USE_IV)
294 dmsg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
296 if (buf->len < 1)
297 CRYPT_ERROR ("missing payload");
299 /* ctx->cipher was already initialized with key & keylen */
300 if (!EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_DECRYPT))
301 CRYPT_ERROR ("cipher init failed");
303 /* Buffer overflow check (should never happen) */
304 if (!buf_safe (&work, buf->len))
305 CRYPT_ERROR ("buffer overflow");
307 /* Decrypt packet ID, payload */
308 if (!EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)))
309 CRYPT_ERROR ("cipher update failed");
310 work.len += outlen;
312 /* Flush the decryption buffer */
313 if (!EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen))
314 CRYPT_ERROR ("cipher final failed");
315 work.len += outlen;
317 dmsg (D_PACKET_CONTENT, "DECRYPT TO: %s",
318 format_hex (BPTR (&work), BLEN (&work), 80, &gc));
320 /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
322 if (mode == EVP_CIPH_CBC_MODE)
324 if (opt->packet_id)
326 if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
327 CRYPT_ERROR ("error reading CBC packet-id");
328 have_pin = true;
331 else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
333 struct buffer b;
335 ASSERT (opt->flags & CO_USE_IV); /* IV and packet-ID required */
336 ASSERT (opt->packet_id); /* for this mode. */
338 buf_set_read (&b, iv_buf, iv_size);
339 if (!packet_id_read (&pin, &b, true))
340 CRYPT_ERROR ("error reading CFB/OFB packet-id");
341 have_pin = true;
343 else /* We only support CBC, CFB, or OFB modes right now */
345 ASSERT (0);
349 else
351 work = *buf;
352 if (opt->packet_id)
354 if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
355 CRYPT_ERROR ("error reading packet-id");
356 have_pin = !BOOL_CAST (opt->flags & CO_IGNORE_PACKET_ID);
360 if (have_pin)
362 packet_id_reap_test (&opt->packet_id->rec);
363 if (packet_id_test (&opt->packet_id->rec, &pin))
365 packet_id_add (&opt->packet_id->rec, &pin);
366 if (opt->pid_persist && (opt->flags & CO_PACKET_ID_LONG_FORM))
367 packet_id_persist_save_obj (opt->pid_persist, opt->packet_id);
369 else
371 if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS))
372 msg (D_REPLAY_ERRORS, "%s: bad packet ID (may be a replay): %s -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings",
373 error_prefix, packet_id_net_print (&pin, true, &gc));
374 goto error_exit;
377 *buf = work;
380 gc_free (&gc);
381 return true;
383 error_exit:
384 ERR_clear_error ();
385 buf->len = 0;
386 gc_free (&gc);
387 return false;
391 * How many bytes will we add to frame buffer for a given
392 * set of crypto options?
394 void
395 crypto_adjust_frame_parameters(struct frame *frame,
396 const struct key_type* kt,
397 bool cipher_defined,
398 bool use_iv,
399 bool packet_id,
400 bool packet_id_long_form)
402 frame_add_to_extra_frame (frame,
403 (packet_id ? packet_id_size (packet_id_long_form) : 0) +
404 ((cipher_defined && use_iv) ? EVP_CIPHER_iv_length (kt->cipher) : 0) +
405 (cipher_defined ? EVP_CIPHER_block_size (kt->cipher) : 0) + /* worst case padding expansion */
406 kt->hmac_length);
409 static const EVP_CIPHER *
410 get_cipher (const char *ciphername)
412 const EVP_CIPHER *cipher = NULL;
413 ASSERT (ciphername);
414 cipher = EVP_get_cipherbyname (ciphername);
415 if ( !(cipher && cipher_ok (OBJ_nid2sn (EVP_CIPHER_nid (cipher)))))
416 msg (M_SSLERR, "Cipher algorithm '%s' not found", ciphername);
417 if (EVP_CIPHER_key_length (cipher) > MAX_CIPHER_KEY_LENGTH)
418 msg (M_FATAL, "Cipher algorithm '%s' uses a default key size (%d bytes) which is larger than " PACKAGE_NAME "'s current maximum key size (%d bytes)",
419 ciphername,
420 EVP_CIPHER_key_length (cipher),
421 MAX_CIPHER_KEY_LENGTH);
422 return cipher;
425 static const EVP_MD *
426 get_md (const char *digest)
428 const EVP_MD *md = NULL;
429 ASSERT (digest);
430 md = EVP_get_digestbyname (digest);
431 if (!md)
432 msg (M_SSLERR, "Message hash algorithm '%s' not found", digest);
433 if (EVP_MD_size (md) > MAX_HMAC_KEY_LENGTH)
434 msg (M_FATAL, "Message hash algorithm '%s' uses a default hash size (%d bytes) which is larger than " PACKAGE_NAME "'s current maximum hash size (%d bytes)",
435 digest,
436 EVP_MD_size (md),
437 MAX_HMAC_KEY_LENGTH);
438 return md;
441 static void
442 init_cipher (EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
443 struct key *key, const struct key_type *kt, int enc,
444 const char *prefix)
446 struct gc_arena gc = gc_new ();
448 EVP_CIPHER_CTX_init (ctx);
449 if (!EVP_CipherInit_ov (ctx, cipher, NULL, NULL, enc))
450 msg (M_SSLERR, "EVP cipher init #1");
451 #ifdef HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH
452 if (!EVP_CIPHER_CTX_set_key_length (ctx, kt->cipher_length))
453 msg (M_SSLERR, "EVP set key size");
454 #endif
455 if (!EVP_CipherInit_ov (ctx, NULL, key->cipher, NULL, enc))
456 msg (M_SSLERR, "EVP cipher init #2");
458 msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
459 prefix,
460 OBJ_nid2sn (EVP_CIPHER_CTX_nid (ctx)),
461 EVP_CIPHER_CTX_key_length (ctx) * 8);
463 /* make sure we used a big enough key */
464 ASSERT (EVP_CIPHER_CTX_key_length (ctx) <= kt->cipher_length);
466 dmsg (D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
467 format_hex (key->cipher, kt->cipher_length, 0, &gc));
468 dmsg (D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d",
469 prefix,
470 EVP_CIPHER_CTX_block_size (ctx),
471 EVP_CIPHER_CTX_iv_length (ctx));
473 gc_free (&gc);
476 static void
477 init_hmac (HMAC_CTX *ctx, const EVP_MD *digest,
478 struct key *key, const struct key_type *kt, const char *prefix)
480 struct gc_arena gc = gc_new ();
482 HMAC_CTX_init (ctx);
483 HMAC_Init_ex (ctx, key->hmac, kt->hmac_length, digest, NULL);
484 msg (D_HANDSHAKE,
485 "%s: Using %d bit message hash '%s' for HMAC authentication",
486 prefix, HMAC_size (ctx) * 8, OBJ_nid2sn (EVP_MD_type (digest)));
488 /* make sure we used a big enough key */
489 ASSERT (HMAC_size (ctx) <= kt->hmac_length);
491 dmsg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
492 format_hex (key->hmac, kt->hmac_length, 0, &gc));
493 dmsg (D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d",
494 prefix,
495 EVP_MD_size (digest),
496 EVP_MD_block_size (digest));
498 gc_free (&gc);
502 * Build a struct key_type.
504 void
505 init_key_type (struct key_type *kt, const char *ciphername,
506 bool ciphername_defined, const char *authname,
507 bool authname_defined, int keysize,
508 bool cfb_ofb_allowed, bool warn)
510 CLEAR (*kt);
511 if (ciphername && ciphername_defined)
513 kt->cipher = get_cipher (ciphername);
514 kt->cipher_length = EVP_CIPHER_key_length (kt->cipher);
515 if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH)
516 kt->cipher_length = keysize;
518 /* check legal cipher mode */
520 const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
521 if (!(mode == EVP_CIPH_CBC_MODE
522 #ifdef ALLOW_NON_CBC_CIPHERS
523 || (cfb_ofb_allowed && (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE))
524 #endif
526 #ifdef ENABLE_SMALL
527 msg (M_FATAL, "Cipher '%s' mode not supported", ciphername);
528 #else
529 msg (M_FATAL, "Cipher '%s' uses a mode not supported by " PACKAGE_NAME " in your current configuration. CBC mode is always supported, while CFB and OFB modes are supported only when using SSL/TLS authentication and key exchange mode, and when " PACKAGE_NAME " has been built with ALLOW_NON_CBC_CIPHERS.", ciphername);
530 #endif
533 else
535 if (warn)
536 msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used");
538 if (authname && authname_defined)
540 kt->digest = get_md (authname);
541 kt->hmac_length = EVP_MD_size (kt->digest);
543 else
545 if (warn)
546 msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
550 const char *
551 kt_cipher_name (const struct key_type *kt)
553 if (kt->cipher)
554 return EVP_CIPHER_name (kt->cipher);
555 else
556 return "[null-cipher]";
559 const char *
560 kt_digest_name (const struct key_type *kt)
562 if (kt->digest)
563 return EVP_MD_name (kt->digest);
564 else
565 return "[null-digest]";
569 kt_key_size (const struct key_type *kt)
571 if (kt->cipher_length)
572 return kt->cipher_length * 8;
573 else if (kt->cipher)
574 return EVP_CIPHER_key_length (kt->cipher) * 8;
575 else
576 return 0;
579 /* given a key and key_type, build a key_ctx */
580 void
581 init_key_ctx (struct key_ctx *ctx, struct key *key,
582 const struct key_type *kt, int enc,
583 const char *prefix)
585 CLEAR (*ctx);
586 if (kt->cipher && kt->cipher_length > 0)
588 ALLOC_OBJ (ctx->cipher, EVP_CIPHER_CTX);
589 init_cipher (ctx->cipher, kt->cipher, key, kt, enc, prefix);
591 if (kt->digest && kt->hmac_length > 0)
593 ALLOC_OBJ (ctx->hmac, HMAC_CTX);
594 init_hmac (ctx->hmac, kt->digest, key, kt, prefix);
598 void
599 free_key_ctx (struct key_ctx *ctx)
601 if (ctx->cipher)
603 EVP_CIPHER_CTX_cleanup (ctx->cipher);
604 free (ctx->cipher);
605 ctx->cipher = NULL;
607 if (ctx->hmac)
609 HMAC_CTX_cleanup (ctx->hmac);
610 free (ctx->hmac);
611 ctx->hmac = NULL;
615 void
616 free_key_ctx_bi (struct key_ctx_bi *ctx)
618 free_key_ctx(&ctx->encrypt);
619 free_key_ctx(&ctx->decrypt);
623 * Return number of DES cblocks for the current
624 * key type or 0 if not a DES cipher.
626 static int
627 n_DES_cblocks (const struct key_type *kt)
629 int ret = 0;
630 const char *name = OBJ_nid2sn (EVP_CIPHER_nid (kt->cipher));
631 if (name)
633 if (!strncmp (name, "DES-", 4))
635 ret = EVP_CIPHER_key_length (kt->cipher) / sizeof (DES_cblock);
637 else if (!strncmp (name, "DESX-", 5))
639 ret = 1;
642 dmsg (D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret);
643 return ret;
646 static bool
647 check_key_DES (struct key *key, const struct key_type *kt, int ndc)
649 int i;
650 struct buffer b;
652 buf_set_read (&b, key->cipher, kt->cipher_length);
654 for (i = 0; i < ndc; ++i)
656 DES_cblock *dc = (DES_cblock*) buf_read_alloc (&b, sizeof (DES_cblock));
657 if (!dc)
659 msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: insufficient key material");
660 goto err;
662 if (DES_is_weak_key(dc))
664 msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: weak key detected");
665 goto err;
667 if (!DES_check_key_parity (dc))
669 msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: bad parity detected");
670 goto err;
673 return true;
675 err:
676 ERR_clear_error ();
677 return false;
680 static void
681 fixup_key_DES (struct key *key, const struct key_type *kt, int ndc)
683 int i;
684 struct buffer b;
686 buf_set_read (&b, key->cipher, kt->cipher_length);
687 for (i = 0; i < ndc; ++i)
689 DES_cblock *dc = (DES_cblock*) buf_read_alloc(&b, sizeof(DES_cblock));
690 if (!dc)
692 msg (D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material");
693 ERR_clear_error ();
694 return;
696 DES_set_odd_parity (dc);
700 static bool
701 key_is_zero (struct key *key, const struct key_type *kt)
703 int i;
704 for (i = 0; i < kt->cipher_length; ++i)
705 if (key->cipher[i])
706 return false;
707 msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
708 return true;
712 * Make sure that cipher key is a valid key for current key_type.
714 bool
715 check_key (struct key *key, const struct key_type *kt)
717 if (kt->cipher)
720 * Check for zero key
722 if (key_is_zero(key, kt))
723 return false;
726 * Check for weak or semi-weak DES keys.
729 const int ndc = n_DES_cblocks (kt);
730 if (ndc)
731 return check_key_DES (key, kt, ndc);
732 else
733 return true;
736 return true;
740 * Make safe mutations to key to ensure it is valid,
741 * such as ensuring correct parity on DES keys.
743 * This routine cannot guarantee it will generate a good
744 * key. You must always call check_key after this routine
745 * to make sure.
747 void
748 fixup_key (struct key *key, const struct key_type *kt)
750 struct gc_arena gc = gc_new ();
751 if (kt->cipher)
753 #ifdef ENABLE_DEBUG
754 const struct key orig = *key;
755 #endif
756 const int ndc = n_DES_cblocks (kt);
758 if (ndc)
759 fixup_key_DES (key, kt, ndc);
761 #ifdef ENABLE_DEBUG
762 if (check_debug_level (D_CRYPTO_DEBUG))
764 if (memcmp (orig.cipher, key->cipher, kt->cipher_length))
765 dmsg (D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s",
766 format_hex (orig.cipher, kt->cipher_length, 0, &gc),
767 format_hex (key->cipher, kt->cipher_length, 0, &gc));
769 #endif
771 gc_free (&gc);
774 void
775 check_replay_iv_consistency (const struct key_type *kt, bool packet_id, bool use_iv)
777 if (cfb_ofb_mode (kt) && !(packet_id && use_iv))
778 msg (M_FATAL, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
781 bool
782 cfb_ofb_mode (const struct key_type* kt)
784 if (kt->cipher) {
785 const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
786 return mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE;
787 } else
788 return false;
792 * Generate a random key. If key_type is provided, make
793 * sure generated key is valid for key_type.
795 void
796 generate_key_random (struct key *key, const struct key_type *kt)
798 int cipher_len = MAX_CIPHER_KEY_LENGTH;
799 int hmac_len = MAX_HMAC_KEY_LENGTH;
801 struct gc_arena gc = gc_new ();
803 do {
804 CLEAR (*key);
805 if (kt)
807 if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
808 cipher_len = kt->cipher_length;
810 if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
811 hmac_len = kt->hmac_length;
813 if (!RAND_bytes (key->cipher, cipher_len)
814 || !RAND_bytes (key->hmac, hmac_len))
815 msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation");
817 dmsg (D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex (key->cipher, cipher_len, 0, &gc));
818 dmsg (D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex (key->hmac, hmac_len, 0, &gc));
820 if (kt)
821 fixup_key (key, kt);
822 } while (kt && !check_key (key, kt));
824 gc_free (&gc);
828 * Print key material
830 void
831 key2_print (const struct key2* k,
832 const struct key_type *kt,
833 const char* prefix0,
834 const char* prefix1)
836 struct gc_arena gc = gc_new ();
837 ASSERT (k->n == 2);
838 dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
839 prefix0,
840 format_hex (k->keys[0].cipher, kt->cipher_length, 0, &gc));
841 dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
842 prefix0,
843 format_hex (k->keys[0].hmac, kt->hmac_length, 0, &gc));
844 dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
845 prefix1,
846 format_hex (k->keys[1].cipher, kt->cipher_length, 0, &gc));
847 dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
848 prefix1,
849 format_hex (k->keys[1].hmac, kt->hmac_length, 0, &gc));
850 gc_free (&gc);
853 void
854 test_crypto (const struct crypto_options *co, struct frame* frame)
856 int i, j;
857 struct gc_arena gc = gc_new ();
858 struct buffer src = alloc_buf_gc (TUN_MTU_SIZE (frame), &gc);
859 struct buffer work = alloc_buf_gc (BUF_SIZE (frame), &gc);
860 struct buffer encrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc);
861 struct buffer decrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc);
862 struct buffer buf = clear_buf();
864 /* init work */
865 ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
867 msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
868 for (i = 1; i <= TUN_MTU_SIZE (frame); ++i)
870 update_time ();
872 msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
875 * Load src with random data.
877 ASSERT (buf_init (&src, 0));
878 ASSERT (i <= src.capacity);
879 src.len = i;
880 ASSERT (RAND_pseudo_bytes (BPTR (&src), BLEN (&src)));
882 /* copy source to input buf */
883 buf = work;
884 memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
886 /* encrypt */
887 openvpn_encrypt (&buf, encrypt_workspace, co, frame);
889 /* decrypt */
890 openvpn_decrypt (&buf, decrypt_workspace, co, frame);
892 /* compare */
893 if (buf.len != src.len)
894 msg (M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
895 for (j = 0; j < i; ++j)
897 const uint8_t in = *(BPTR (&src) + j);
898 const uint8_t out = *(BPTR (&buf) + j);
899 if (in != out)
900 msg (M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
903 msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
904 gc_free (&gc);
907 #ifdef USE_SSL
908 void
909 get_tls_handshake_key (const struct key_type *key_type,
910 struct key_ctx_bi *ctx,
911 const char *passphrase_file,
912 bool key_direction)
914 if (passphrase_file && key_type->hmac_length)
916 struct key2 key2;
917 struct key_type kt = *key_type;
918 struct key_direction_state kds;
920 /* for control channel we are only authenticating, not encrypting */
921 kt.cipher_length = 0;
922 kt.cipher = NULL;
924 /* first try to parse as an OpenVPN static key file */
925 read_key_file (&key2, passphrase_file, false);
927 /* succeeded? */
928 if (key2.n == 2)
930 msg (M_INFO,
931 "Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
932 passphrase_file);
934 else
936 int hash_size;
938 CLEAR (key2);
940 /* failed, now try to get hash from a freeform file */
941 hash_size = read_passphrase_hash (passphrase_file,
942 kt.digest,
943 key2.keys[0].hmac,
944 MAX_HMAC_KEY_LENGTH);
945 ASSERT (hash_size == kt.hmac_length);
947 /* suceeded */
948 key2.n = 1;
950 msg (M_INFO,
951 "Control Channel Authentication: using '%s' as a free-form passphrase file",
952 passphrase_file);
955 /* handle key direction */
957 key_direction_state_init (&kds, key_direction);
958 must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
960 /* initialize hmac key in both directions */
962 init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, DO_ENCRYPT,
963 "Outgoing Control Channel Authentication");
964 init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, DO_DECRYPT,
965 "Incoming Control Channel Authentication");
967 CLEAR (key2);
969 else
971 CLEAR (*ctx);
974 #endif
976 /* header and footer for static key file */
977 static const char static_key_head[] = "-----BEGIN " PACKAGE_NAME " Static key V1-----";
978 static const char static_key_foot[] = "-----END " PACKAGE_NAME " Static key V1-----";
980 static const char printable_char_fmt[] =
981 "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
983 static const char unprintable_char_fmt[] =
984 "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
986 /* read key from file */
987 void
988 read_key_file (struct key2 *key2, const char *filename, bool must_succeed)
990 struct gc_arena gc = gc_new ();
991 struct buffer in = alloc_buf_gc (64, &gc);
992 int fd, size;
993 uint8_t hex_byte[3] = {0, 0, 0};
995 /* parse info */
996 int hb_index = 0;
997 int line_num = 1;
998 int line_index = 0;
999 int match = 0;
1001 /* output */
1002 uint8_t* out = (uint8_t*) &key2->keys;
1003 const int keylen = sizeof (key2->keys);
1004 int count = 0;
1006 /* parse states */
1007 # define PARSE_INITIAL 0
1008 # define PARSE_HEAD 1
1009 # define PARSE_DATA 2
1010 # define PARSE_DATA_COMPLETE 3
1011 # define PARSE_FOOT 4
1012 # define PARSE_FINISHED 5
1013 int state = PARSE_INITIAL;
1015 /* constants */
1016 const int hlen = strlen (static_key_head);
1017 const int flen = strlen (static_key_foot);
1018 const int onekeylen = sizeof (key2->keys[0]);
1020 CLEAR (*key2);
1022 fd = open (filename, O_RDONLY);
1023 if (fd == -1)
1024 msg (M_ERR, "Cannot open file key file '%s'", filename);
1026 while ((size = read (fd, in.data, in.capacity)))
1028 const char *cp = (char *)in.data;
1029 while (size)
1031 const char c = *cp;
1033 #if 0
1034 msg (M_INFO, "char='%c' s=%d ln=%d li=%d m=%d c=%d",
1035 c, state, line_num, line_index, match, count);
1036 #endif
1038 if (c == '\n')
1040 line_index = match = 0;
1041 ++line_num;
1043 else
1045 /* first char of new line */
1046 if (!line_index)
1048 /* first char of line after header line? */
1049 if (state == PARSE_HEAD)
1050 state = PARSE_DATA;
1052 /* first char of footer */
1053 if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
1054 state = PARSE_FOOT;
1057 /* compare read chars with header line */
1058 if (state == PARSE_INITIAL)
1060 if (line_index < hlen && c == static_key_head[line_index])
1062 if (++match == hlen)
1063 state = PARSE_HEAD;
1067 /* compare read chars with footer line */
1068 if (state == PARSE_FOOT)
1070 if (line_index < flen && c == static_key_foot[line_index])
1072 if (++match == flen)
1073 state = PARSE_FINISHED;
1077 /* reading key */
1078 if (state == PARSE_DATA)
1080 if (isxdigit(c))
1082 ASSERT (hb_index >= 0 && hb_index < 2);
1083 hex_byte[hb_index++] = c;
1084 if (hb_index == 2)
1086 unsigned int u;
1087 ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
1088 *out++ = u;
1089 hb_index = 0;
1090 if (++count == keylen)
1091 state = PARSE_DATA_COMPLETE;
1094 else if (isspace(c))
1096 else
1098 msg (M_FATAL,
1099 (isprint (c) ? printable_char_fmt : unprintable_char_fmt),
1100 c, line_num, filename, count, onekeylen, keylen);
1103 ++line_index;
1105 ++cp;
1106 --size;
1110 close (fd);
1113 * Normally we will read either 1 or 2 keys from file.
1115 key2->n = count / onekeylen;
1117 ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys));
1119 if (must_succeed)
1121 if (!key2->n)
1122 msg (M_FATAL, "Insufficient key material or header text not found found in file '%s' (%d/%d/%d bytes found/min/max)",
1123 filename, count, onekeylen, keylen);
1125 if (state != PARSE_FINISHED)
1126 msg (M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1127 filename, count, onekeylen, keylen);
1130 /* zero file read buffer */
1131 buf_clear (&in);
1133 if (key2->n)
1134 warn_if_group_others_accessible (filename);
1136 #if 0
1137 /* DEBUGGING */
1139 int i;
1140 printf ("KEY READ, n=%d\n", key2->n);
1141 for (i = 0; i < (int) SIZE (key2->keys); ++i)
1143 /* format key as ascii */
1144 const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i],
1145 sizeof (key2->keys[i]),
1148 "\n",
1149 &gc);
1150 printf ("[%d]\n%s\n\n", i, fmt);
1153 #endif
1155 /* pop our garbage collection level */
1156 gc_free (&gc);
1160 read_passphrase_hash (const char *passphrase_file,
1161 const EVP_MD *digest,
1162 uint8_t *output,
1163 int len)
1165 unsigned int outlen = 0;
1166 EVP_MD_CTX md;
1168 ASSERT (len >= EVP_MD_size (digest));
1169 memset (output, 0, len);
1171 EVP_DigestInit (&md, digest);
1173 /* read passphrase file */
1175 const int min_passphrase_size = 8;
1176 uint8_t buf[64];
1177 int total_size = 0;
1178 int fd = open (passphrase_file, O_RDONLY);
1180 if (fd == -1)
1181 msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
1183 for (;;)
1185 int size = read (fd, buf, sizeof (buf));
1186 if (size == 0)
1187 break;
1188 if (size == -1)
1189 msg (M_ERR, "Read error on passphrase file: '%s'",
1190 passphrase_file);
1191 EVP_DigestUpdate (&md, buf, size);
1192 total_size += size;
1194 close (fd);
1196 warn_if_group_others_accessible (passphrase_file);
1198 if (total_size < min_passphrase_size)
1199 msg (M_FATAL,
1200 "Passphrase file '%s' is too small (must have at least %d characters)",
1201 passphrase_file, min_passphrase_size);
1204 EVP_DigestFinal (&md, output, &outlen);
1205 EVP_MD_CTX_cleanup (&md);
1206 return outlen;
1210 * Write key to file, return number of random bits
1211 * written.
1214 write_key_file (const int nkeys, const char *filename)
1216 struct gc_arena gc = gc_new ();
1218 int fd, i;
1219 int nbits = 0;
1221 /* must be large enough to hold full key file */
1222 struct buffer out = alloc_buf_gc (2048, &gc);
1223 struct buffer nbits_head_text = alloc_buf_gc (128, &gc);
1225 /* how to format the ascii file representation of key */
1226 const int bytes_per_line = 16;
1228 /* open key file */
1229 fd = open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
1231 if (fd == -1)
1232 msg (M_ERR, "Cannot open shared secret file '%s' for write", filename);
1234 buf_printf (&out, "%s\n", static_key_head);
1236 for (i = 0; i < nkeys; ++i)
1238 struct key key;
1239 char* fmt;
1241 /* generate random bits */
1242 generate_key_random (&key, NULL);
1244 /* format key as ascii */
1245 fmt = format_hex_ex ((const uint8_t*)&key,
1246 sizeof (key),
1248 bytes_per_line,
1249 "\n",
1250 &gc);
1252 /* increment random bits counter */
1253 nbits += sizeof (key) * 8;
1255 /* write to holding buffer */
1256 buf_printf (&out, "%s\n", fmt);
1258 /* zero memory which held key component (will be freed by GC) */
1259 memset (fmt, 0, strlen(fmt));
1260 CLEAR (key);
1263 buf_printf (&out, "%s\n", static_key_foot);
1265 /* write number of bits */
1266 buf_printf (&nbits_head_text, "#\n# %d bit " PACKAGE_NAME " static key\n#\n", nbits);
1267 buf_write_string_file (&nbits_head_text, filename, fd);
1269 /* write key file, now formatted in out, to file */
1270 buf_write_string_file (&out, filename, fd);
1272 if (close (fd))
1273 msg (M_ERR, "Close error on shared secret file %s", filename);
1275 /* zero memory which held file content (memory will be freed by GC) */
1276 buf_clear (&out);
1278 /* pop our garbage collection level */
1279 gc_free (&gc);
1281 return nbits;
1284 void
1285 must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
1287 if (key2->n < n)
1289 #ifdef ENABLE_SMALL
1290 msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n);
1291 #else
1292 msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d] -- try generating a new key file with '" PACKAGE " --genkey --secret [file]', or use the existing key file in bidirectional mode by specifying --%s without a key direction parameter", filename, option, key2->n, n, option);
1293 #endif
1298 ascii2keydirection (int msglevel, const char *str)
1300 if (!str)
1301 return KEY_DIRECTION_BIDIRECTIONAL;
1302 else if (!strcmp (str, "0"))
1303 return KEY_DIRECTION_NORMAL;
1304 else if (!strcmp (str, "1"))
1305 return KEY_DIRECTION_INVERSE;
1306 else
1308 msg (msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1309 return -1;
1311 return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1314 const char *
1315 keydirection2ascii (int kd, bool remote)
1317 if (kd == KEY_DIRECTION_BIDIRECTIONAL)
1318 return NULL;
1319 else if (kd == KEY_DIRECTION_NORMAL)
1320 return remote ? "1" : "0";
1321 else if (kd == KEY_DIRECTION_INVERSE)
1322 return remote ? "0" : "1";
1323 else
1325 ASSERT (0);
1327 return NULL; /* NOTREACHED */
1330 void
1331 key_direction_state_init (struct key_direction_state *kds, int key_direction)
1333 CLEAR (*kds);
1334 switch (key_direction)
1336 case KEY_DIRECTION_NORMAL:
1337 kds->out_key = 0;
1338 kds->in_key = 1;
1339 kds->need_keys = 2;
1340 break;
1341 case KEY_DIRECTION_INVERSE:
1342 kds->out_key = 1;
1343 kds->in_key = 0;
1344 kds->need_keys = 2;
1345 break;
1346 case KEY_DIRECTION_BIDIRECTIONAL:
1347 kds->out_key = 0;
1348 kds->in_key = 0;
1349 kds->need_keys = 1;
1350 break;
1351 default:
1352 ASSERT (0);
1356 void
1357 verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1359 int i;
1361 for (i = 0; i < key2->n; ++i)
1363 /* Fix parity for DES keys and make sure not a weak key */
1364 fixup_key (&key2->keys[i], kt);
1366 /* This should be a very improbable failure */
1367 if (!check_key (&key2->keys[i], kt))
1368 msg (M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
1369 i+1, shared_secret_file);
1373 /* given a key and key_type, write key to buffer */
1374 bool
1375 write_key (const struct key *key, const struct key_type *kt,
1376 struct buffer *buf)
1378 ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH
1379 && kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
1381 if (!buf_write (buf, &kt->cipher_length, 1))
1382 return false;
1383 if (!buf_write (buf, &kt->hmac_length, 1))
1384 return false;
1385 if (!buf_write (buf, key->cipher, kt->cipher_length))
1386 return false;
1387 if (!buf_write (buf, key->hmac, kt->hmac_length))
1388 return false;
1390 return true;
1394 * Given a key_type and buffer, read key from buffer.
1395 * Return: 1 on success
1396 * -1 read failure
1397 * 0 on key length mismatch
1400 read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
1402 uint8_t cipher_length;
1403 uint8_t hmac_length;
1405 CLEAR (*key);
1406 if (!buf_read (buf, &cipher_length, 1))
1407 goto read_err;
1408 if (!buf_read (buf, &hmac_length, 1))
1409 goto read_err;
1411 if (!buf_read (buf, key->cipher, cipher_length))
1412 goto read_err;
1413 if (!buf_read (buf, key->hmac, hmac_length))
1414 goto read_err;
1416 if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1417 goto key_len_err;
1419 return 1;
1421 read_err:
1422 msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
1423 return -1;
1425 key_len_err:
1426 msg (D_TLS_ERRORS,
1427 "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1428 kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
1429 return 0;
1432 void
1433 show_available_ciphers ()
1435 int nid;
1438 #ifndef ENABLE_SMALL
1439 printf ("The following ciphers and cipher modes are available\n"
1440 "for use with " PACKAGE_NAME ". Each cipher shown below may be\n"
1441 "used as a parameter to the --cipher option. The default\n"
1442 "key size is shown as well as whether or not it can be\n"
1443 "changed with the --keysize directive. Using a CBC mode\n"
1444 "is recommended.\n\n");
1445 #endif
1447 for (nid = 0; nid < 10000; ++nid) /* is there a better way to get the size of the nid list? */
1449 const EVP_CIPHER *cipher = EVP_get_cipherbynid (nid);
1450 if (cipher && cipher_ok (OBJ_nid2sn (nid)))
1452 const unsigned int mode = EVP_CIPHER_mode (cipher);
1453 if (mode == EVP_CIPH_CBC_MODE
1454 #ifdef ALLOW_NON_CBC_CIPHERS
1455 || mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE
1456 #endif
1458 printf ("%s %d bit default key (%s)\n",
1459 OBJ_nid2sn (nid),
1460 EVP_CIPHER_key_length (cipher) * 8,
1461 ((EVP_CIPHER_flags (cipher) & EVP_CIPH_VARIABLE_LENGTH) ?
1462 "variable" : "fixed"));
1465 printf ("\n");
1468 void
1469 show_available_digests ()
1471 int nid;
1473 #ifndef ENABLE_SMALL
1474 printf ("The following message digests are available for use with\n"
1475 PACKAGE_NAME ". A message digest is used in conjunction with\n"
1476 "the HMAC function, to authenticate received packets.\n"
1477 "You can specify a message digest as parameter to\n"
1478 "the --auth option.\n\n");
1479 #endif
1481 for (nid = 0; nid < 10000; ++nid)
1483 const EVP_MD *digest = EVP_get_digestbynid (nid);
1484 if (digest)
1486 printf ("%s %d bit digest size\n",
1487 OBJ_nid2sn (nid), EVP_MD_size (digest) * 8);
1490 printf ("\n");
1493 void
1494 show_available_engines ()
1496 #if CRYPTO_ENGINE
1497 ENGINE *e;
1499 printf ("OpenSSL Crypto Engines\n\n");
1501 ENGINE_load_builtin_engines ();
1503 e = ENGINE_get_first ();
1504 while (e)
1506 printf ("%s [%s]\n",
1507 ENGINE_get_name (e),
1508 ENGINE_get_id (e));
1509 e = ENGINE_get_next (e);
1511 ENGINE_cleanup ();
1512 #else
1513 printf ("Sorry, OpenSSL hardware crypto engine functionality is not available.\n");
1514 #endif
1518 * Enable crypto acceleration, if available
1521 static bool engine_initialized = false; /* GLOBAL */
1523 #if CRYPTO_ENGINE
1525 static ENGINE *engine_persist = NULL; /* GLOBAL */
1527 /* Try to load an engine in a shareable library */
1528 static ENGINE *
1529 try_load_engine (const char *engine)
1531 ENGINE *e = ENGINE_by_id ("dynamic");
1532 if (e)
1534 if (!ENGINE_ctrl_cmd_string (e, "SO_PATH", engine, 0)
1535 || !ENGINE_ctrl_cmd_string (e, "LOAD", NULL, 0))
1537 ENGINE_free (e);
1538 e = NULL;
1541 return e;
1544 static ENGINE *
1545 setup_engine (const char *engine)
1547 ENGINE *e = NULL;
1549 ENGINE_load_builtin_engines ();
1551 if (engine)
1553 if (strcmp (engine, "auto") == 0)
1555 msg (M_INFO, "Initializing OpenSSL auto engine support");
1556 ENGINE_register_all_complete ();
1557 return NULL;
1559 if ((e = ENGINE_by_id (engine)) == NULL
1560 && (e = try_load_engine (engine)) == NULL)
1562 msg (M_FATAL, "OpenSSL error: cannot load engine '%s'", engine);
1565 if (!ENGINE_set_default (e, ENGINE_METHOD_ALL))
1567 msg (M_FATAL, "OpenSSL error: ENGINE_set_default failed on engine '%s'",
1568 engine);
1571 msg (M_INFO, "Initializing OpenSSL support for engine '%s'",
1572 ENGINE_get_id (e));
1574 return e;
1576 #endif
1578 void
1579 init_crypto_lib_engine (const char *engine_name)
1581 if (!engine_initialized)
1583 #if CRYPTO_ENGINE
1584 ASSERT (engine_name);
1585 ASSERT (!engine_persist);
1586 engine_persist = setup_engine (engine_name);
1587 #else
1588 msg (M_WARN, "Note: OpenSSL hardware crypto engine functionality is not available");
1589 #endif
1590 engine_initialized = true;
1595 * This routine should have additional OpenSSL crypto library initialisations
1596 * used by both crypto and ssl components of OpenVPN.
1598 void init_crypto_lib ()
1602 void uninit_crypto_lib ()
1604 #if CRYPTO_ENGINE
1605 if (engine_initialized)
1607 ENGINE_cleanup ();
1608 engine_persist = NULL;
1609 engine_initialized = false;
1611 #endif
1615 * Random number functions, used in cases where we want
1616 * reasonably strong cryptographic random number generation
1617 * without depleting our entropy pool. Used for random
1618 * IV values and a number of other miscellaneous tasks.
1621 #define NONCE_SECRET_LEN 16
1623 static uint8_t nonce_data [SHA_DIGEST_LENGTH + NONCE_SECRET_LEN]; /* GLOBAL */
1625 void
1626 prng_init (void)
1628 if (!RAND_bytes (nonce_data, sizeof(nonce_data)))
1629 msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG");
1632 void
1633 prng_bytes (uint8_t *output, int len)
1635 SHA_CTX ctx;
1636 mutex_lock_static (L_PRNG);
1637 while (len > 0)
1639 const int blen = min_int (len, SHA_DIGEST_LENGTH);
1640 SHA1_Init (&ctx);
1641 SHA1_Update (&ctx, nonce_data, sizeof (nonce_data));
1642 SHA1_Final (nonce_data, &ctx);
1643 memcpy (output, nonce_data, blen);
1644 output += blen;
1645 len -= blen;
1647 mutex_unlock_static (L_PRNG);
1650 /* an analogue to the random() function, but use prng_bytes */
1651 long int
1652 get_random()
1654 long int l;
1655 prng_bytes ((unsigned char *)&l, sizeof(l));
1656 if (l < 0)
1657 l = -l;
1658 return l;
1661 const char *
1662 md5sum (uint8_t *buf, int len, int n_print_chars, struct gc_arena *gc)
1664 uint8_t digest[MD5_DIGEST_LENGTH];
1665 MD5 (buf, len, digest);
1666 return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars, gc);
1670 * OpenSSL memory debugging. If dmalloc debugging is enabled, tell
1671 * OpenSSL to use our private malloc/realloc/free functions so that
1672 * we can dispatch them to dmalloc.
1675 #ifdef DMALLOC
1677 static void *
1678 crypto_malloc (size_t size, const char *file, int line)
1680 return dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
1683 static void *
1684 crypto_realloc (void *ptr, size_t size, const char *file, int line)
1686 return dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
1689 static void
1690 crypto_free (void *ptr)
1692 dmalloc_free (__FILE__, __LINE__, ptr, DMALLOC_FUNC_FREE);
1695 void
1696 openssl_dmalloc_init (void)
1698 CRYPTO_set_mem_ex_functions (crypto_malloc,
1699 crypto_realloc,
1700 crypto_free);
1703 #endif /* DMALLOC */
1705 #ifndef USE_SSL
1707 void
1708 init_ssl_lib (void)
1710 ERR_load_crypto_strings ();
1711 OpenSSL_add_all_algorithms ();
1712 init_crypto_lib ();
1715 void
1716 free_ssl_lib (void)
1718 uninit_crypto_lib ();
1719 EVP_cleanup ();
1720 ERR_free_strings ();
1723 #endif /* USE_SSL */
1724 #endif /* USE_CRYPTO */