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
8 * Copyright (C) 2002-2009 OpenVPN Technologies, Inc. <sales@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
37 * Check for key size creepage.
40 #if MAX_CIPHER_KEY_LENGTH < EVP_MAX_KEY_LENGTH
41 #warning Some OpenSSL EVP ciphers now support key lengths greater than MAX_CIPHER_KEY_LENGTH -- consider increasing MAX_CIPHER_KEY_LENGTH
44 #if MAX_HMAC_KEY_LENGTH < EVP_MAX_MD_SIZE
45 #warning Some OpenSSL HMAC message digests now support key lengths greater than MAX_HMAC_KEY_LENGTH -- consider increasing MAX_HMAC_KEY_LENGTH
49 * Encryption and Compression Routines.
51 * On entry, buf contains the input data and length.
52 * On exit, it should be set to the output data and length.
54 * If buf->len is <= 0 we should return
55 * If buf->len is set to 0 on exit it tells the caller to ignore the packet.
57 * work is a workspace buffer we are given of size BUF_SIZE.
58 * work may be used to return output data, or the input buffer
59 * may be modified and returned as output. If output data is
60 * returned in work, the data should start after FRAME_HEADROOM bytes
61 * of padding to leave room for downstream routines to prepend.
63 * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
64 * by all routines (encryption, decryption, compression, and decompression).
66 * Note that the buf_prepend return will assert if we try to
67 * make a header bigger than FRAME_HEADROOM. This should not
68 * happen unless the frame parameters are wrong.
71 #define CRYPT_ERROR(format) \
72 do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
75 openvpn_encrypt (struct buffer
*buf
, struct buffer work
,
76 const struct crypto_options
*opt
,
77 const struct frame
* frame
)
82 if (buf
->len
> 0 && opt
->key_ctx_bi
)
84 struct key_ctx
*ctx
= &opt
->key_ctx_bi
->encrypt
;
86 /* Do Encrypt from buf -> work */
89 uint8_t iv_buf
[EVP_MAX_IV_LENGTH
];
90 const int iv_size
= EVP_CIPHER_CTX_iv_length (ctx
->cipher
);
91 const unsigned int mode
= EVP_CIPHER_CTX_mode (ctx
->cipher
);
94 if (mode
== EVP_CIPH_CBC_MODE
)
98 /* generate pseudo-random IV */
99 if (opt
->flags
& CO_USE_IV
)
100 prng_bytes (iv_buf
, iv_size
);
102 /* Put packet ID in plaintext buffer or IV, depending on cipher mode */
105 struct packet_id_net pin
;
106 packet_id_alloc_outgoing (&opt
->packet_id
->send
, &pin
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
));
107 ASSERT (packet_id_write (&pin
, buf
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
), true));
110 else if (mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
)
112 struct packet_id_net pin
;
115 ASSERT (opt
->flags
& CO_USE_IV
); /* IV and packet-ID required */
116 ASSERT (opt
->packet_id
); /* for this mode. */
118 packet_id_alloc_outgoing (&opt
->packet_id
->send
, &pin
, true);
119 memset (iv_buf
, 0, iv_size
);
120 buf_set_write (&b
, iv_buf
, iv_size
);
121 ASSERT (packet_id_write (&pin
, &b
, true, false));
123 else /* We only support CBC, CFB, or OFB modes right now */
128 /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
129 ASSERT (buf_init (&work
, FRAME_HEADROOM (frame
)));
131 /* set the IV pseudo-randomly */
132 if (opt
->flags
& CO_USE_IV
)
133 dmsg (D_PACKET_CONTENT
, "ENCRYPT IV: %s", format_hex (iv_buf
, iv_size
, 0, &gc
));
135 dmsg (D_PACKET_CONTENT
, "ENCRYPT FROM: %s",
136 format_hex (BPTR (buf
), BLEN (buf
), 80, &gc
));
138 /* cipher_ctx was already initialized with key & keylen */
139 ASSERT (EVP_CipherInit_ov (ctx
->cipher
, NULL
, NULL
, iv_buf
, DO_ENCRYPT
));
141 /* Buffer overflow check */
142 if (!buf_safe (&work
, buf
->len
+ EVP_CIPHER_CTX_block_size (ctx
->cipher
)))
144 msg (D_CRYPT_ERRORS
, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d",
151 EVP_CIPHER_CTX_block_size (ctx
->cipher
));
155 /* Encrypt packet ID, payload */
156 ASSERT (EVP_CipherUpdate_ov (ctx
->cipher
, BPTR (&work
), &outlen
, BPTR (buf
), BLEN (buf
)));
159 /* Flush the encryption buffer */
160 ASSERT (EVP_CipherFinal (ctx
->cipher
, BPTR (&work
) + outlen
, &outlen
));
163 /* prepend the IV to the ciphertext */
164 if (opt
->flags
& CO_USE_IV
)
166 uint8_t *output
= buf_prepend (&work
, iv_size
);
168 memcpy (output
, iv_buf
, iv_size
);
171 dmsg (D_PACKET_CONTENT
, "ENCRYPT TO: %s",
172 format_hex (BPTR (&work
), BLEN (&work
), 80, &gc
));
174 else /* No Encryption */
178 struct packet_id_net pin
;
179 packet_id_alloc_outgoing (&opt
->packet_id
->send
, &pin
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
));
180 ASSERT (packet_id_write (&pin
, buf
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
), true));
185 /* HMAC the ciphertext (or plaintext if !cipher) */
191 HMAC_Init_ex (ctx
->hmac
, NULL
, 0, NULL
, NULL
);
192 HMAC_Update (ctx
->hmac
, BPTR (&work
), BLEN (&work
));
193 output
= buf_prepend (&work
, HMAC_size (ctx
->hmac
));
195 HMAC_Final (ctx
->hmac
, output
, (unsigned int *)&hmac_len
);
196 ASSERT (hmac_len
== HMAC_size (ctx
->hmac
));
213 * If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet.
215 * Set buf->len to 0 and return false on decrypt error.
217 * On success, buf is set to point to plaintext, true
221 openvpn_decrypt (struct buffer
*buf
, struct buffer work
,
222 const struct crypto_options
*opt
,
223 const struct frame
* frame
)
225 static const char error_prefix
[] = "Authenticate/Decrypt packet error";
229 if (buf
->len
> 0 && opt
->key_ctx_bi
)
231 struct key_ctx
*ctx
= &opt
->key_ctx_bi
->decrypt
;
232 struct packet_id_net pin
;
233 bool have_pin
= false;
235 /* Verify the HMAC */
239 uint8_t local_hmac
[MAX_HMAC_KEY_LENGTH
]; /* HMAC of ciphertext computed locally */
242 HMAC_Init_ex (ctx
->hmac
, NULL
, 0, NULL
, NULL
);
244 /* Assume the length of the input HMAC */
245 hmac_len
= HMAC_size (ctx
->hmac
);
247 /* Authentication fails if insufficient data in packet for HMAC */
248 if (buf
->len
< hmac_len
)
249 CRYPT_ERROR ("missing authentication info");
251 HMAC_Update (ctx
->hmac
, BPTR (buf
) + hmac_len
,
252 BLEN (buf
) - hmac_len
);
253 HMAC_Final (ctx
->hmac
, local_hmac
, (unsigned int *)&in_hmac_len
);
254 ASSERT (hmac_len
== in_hmac_len
);
256 /* Compare locally computed HMAC with packet HMAC */
257 if (memcmp (local_hmac
, BPTR (buf
), hmac_len
))
258 CRYPT_ERROR ("packet HMAC authentication failed");
260 ASSERT (buf_advance (buf
, hmac_len
));
263 /* Decrypt packet ID + payload */
267 const unsigned int mode
= EVP_CIPHER_CTX_mode (ctx
->cipher
);
268 const int iv_size
= EVP_CIPHER_CTX_iv_length (ctx
->cipher
);
269 uint8_t iv_buf
[EVP_MAX_IV_LENGTH
];
272 /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
273 ASSERT (buf_init (&work
, FRAME_HEADROOM_ADJ (frame
, FRAME_HEADROOM_MARKER_DECRYPT
)));
275 /* use IV if user requested it */
277 if (opt
->flags
& CO_USE_IV
)
279 if (buf
->len
< iv_size
)
280 CRYPT_ERROR ("missing IV info");
281 memcpy (iv_buf
, BPTR (buf
), iv_size
);
282 ASSERT (buf_advance (buf
, iv_size
));
285 /* show the IV's initial state */
286 if (opt
->flags
& CO_USE_IV
)
287 dmsg (D_PACKET_CONTENT
, "DECRYPT IV: %s", format_hex (iv_buf
, iv_size
, 0, &gc
));
290 CRYPT_ERROR ("missing payload");
292 /* ctx->cipher was already initialized with key & keylen */
293 if (!EVP_CipherInit_ov (ctx
->cipher
, NULL
, NULL
, iv_buf
, DO_DECRYPT
))
294 CRYPT_ERROR ("cipher init failed");
296 /* Buffer overflow check (should never happen) */
297 if (!buf_safe (&work
, buf
->len
))
298 CRYPT_ERROR ("buffer overflow");
300 /* Decrypt packet ID, payload */
301 if (!EVP_CipherUpdate_ov (ctx
->cipher
, BPTR (&work
), &outlen
, BPTR (buf
), BLEN (buf
)))
302 CRYPT_ERROR ("cipher update failed");
305 /* Flush the decryption buffer */
306 if (!EVP_CipherFinal (ctx
->cipher
, BPTR (&work
) + outlen
, &outlen
))
307 CRYPT_ERROR ("cipher final failed");
310 dmsg (D_PACKET_CONTENT
, "DECRYPT TO: %s",
311 format_hex (BPTR (&work
), BLEN (&work
), 80, &gc
));
313 /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
315 if (mode
== EVP_CIPH_CBC_MODE
)
319 if (!packet_id_read (&pin
, &work
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
)))
320 CRYPT_ERROR ("error reading CBC packet-id");
324 else if (mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
)
328 ASSERT (opt
->flags
& CO_USE_IV
); /* IV and packet-ID required */
329 ASSERT (opt
->packet_id
); /* for this mode. */
331 buf_set_read (&b
, iv_buf
, iv_size
);
332 if (!packet_id_read (&pin
, &b
, true))
333 CRYPT_ERROR ("error reading CFB/OFB packet-id");
336 else /* We only support CBC, CFB, or OFB modes right now */
347 if (!packet_id_read (&pin
, &work
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
)))
348 CRYPT_ERROR ("error reading packet-id");
349 have_pin
= !BOOL_CAST (opt
->flags
& CO_IGNORE_PACKET_ID
);
355 packet_id_reap_test (&opt
->packet_id
->rec
);
356 if (packet_id_test (&opt
->packet_id
->rec
, &pin
))
358 packet_id_add (&opt
->packet_id
->rec
, &pin
);
359 if (opt
->pid_persist
&& (opt
->flags
& CO_PACKET_ID_LONG_FORM
))
360 packet_id_persist_save_obj (opt
->pid_persist
, opt
->packet_id
);
364 if (!(opt
->flags
& CO_MUTE_REPLAY_WARNINGS
))
365 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",
366 error_prefix
, packet_id_net_print (&pin
, true, &gc
));
384 * How many bytes will we add to frame buffer for a given
385 * set of crypto options?
388 crypto_adjust_frame_parameters(struct frame
*frame
,
389 const struct key_type
* kt
,
393 bool packet_id_long_form
)
395 frame_add_to_extra_frame (frame
,
396 (packet_id
? packet_id_size (packet_id_long_form
) : 0) +
397 ((cipher_defined
&& use_iv
) ? EVP_CIPHER_iv_length (kt
->cipher
) : 0) +
398 (cipher_defined
? EVP_CIPHER_block_size (kt
->cipher
) : 0) + /* worst case padding expansion */
402 static const EVP_CIPHER
*
403 get_cipher (const char *ciphername
)
405 const EVP_CIPHER
*cipher
= NULL
;
407 cipher
= EVP_get_cipherbyname (ciphername
);
408 if ( !(cipher
&& cipher_ok (OBJ_nid2sn (EVP_CIPHER_nid (cipher
)))))
409 msg (M_SSLERR
, "Cipher algorithm '%s' not found", ciphername
);
410 if (EVP_CIPHER_key_length (cipher
) > MAX_CIPHER_KEY_LENGTH
)
411 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)",
413 EVP_CIPHER_key_length (cipher
),
414 MAX_CIPHER_KEY_LENGTH
);
418 static const EVP_MD
*
419 get_md (const char *digest
)
421 const EVP_MD
*md
= NULL
;
423 md
= EVP_get_digestbyname (digest
);
425 msg (M_SSLERR
, "Message hash algorithm '%s' not found", digest
);
426 if (EVP_MD_size (md
) > MAX_HMAC_KEY_LENGTH
)
427 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)",
430 MAX_HMAC_KEY_LENGTH
);
435 init_cipher (EVP_CIPHER_CTX
*ctx
, const EVP_CIPHER
*cipher
,
436 struct key
*key
, const struct key_type
*kt
, int enc
,
439 struct gc_arena gc
= gc_new ();
441 EVP_CIPHER_CTX_init (ctx
);
442 if (!EVP_CipherInit_ov (ctx
, cipher
, NULL
, NULL
, enc
))
443 msg (M_SSLERR
, "EVP cipher init #1");
444 #ifdef HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH
445 if (!EVP_CIPHER_CTX_set_key_length (ctx
, kt
->cipher_length
))
446 msg (M_SSLERR
, "EVP set key size");
448 if (!EVP_CipherInit_ov (ctx
, NULL
, key
->cipher
, NULL
, enc
))
449 msg (M_SSLERR
, "EVP cipher init #2");
451 msg (D_HANDSHAKE
, "%s: Cipher '%s' initialized with %d bit key",
453 OBJ_nid2sn (EVP_CIPHER_CTX_nid (ctx
)),
454 EVP_CIPHER_CTX_key_length (ctx
) * 8);
456 /* make sure we used a big enough key */
457 ASSERT (EVP_CIPHER_CTX_key_length (ctx
) <= kt
->cipher_length
);
459 dmsg (D_SHOW_KEYS
, "%s: CIPHER KEY: %s", prefix
,
460 format_hex (key
->cipher
, kt
->cipher_length
, 0, &gc
));
461 dmsg (D_CRYPTO_DEBUG
, "%s: CIPHER block_size=%d iv_size=%d",
463 EVP_CIPHER_CTX_block_size (ctx
),
464 EVP_CIPHER_CTX_iv_length (ctx
));
470 init_hmac (HMAC_CTX
*ctx
, const EVP_MD
*digest
,
471 struct key
*key
, const struct key_type
*kt
, const char *prefix
)
473 struct gc_arena gc
= gc_new ();
476 HMAC_Init_ex (ctx
, key
->hmac
, kt
->hmac_length
, digest
, NULL
);
478 "%s: Using %d bit message hash '%s' for HMAC authentication",
479 prefix
, HMAC_size (ctx
) * 8, OBJ_nid2sn (EVP_MD_type (digest
)));
481 /* make sure we used a big enough key */
482 ASSERT (HMAC_size (ctx
) <= kt
->hmac_length
);
484 dmsg (D_SHOW_KEYS
, "%s: HMAC KEY: %s", prefix
,
485 format_hex (key
->hmac
, kt
->hmac_length
, 0, &gc
));
486 dmsg (D_CRYPTO_DEBUG
, "%s: HMAC size=%d block_size=%d",
488 EVP_MD_size (digest
),
489 EVP_MD_block_size (digest
));
495 * Build a struct key_type.
498 init_key_type (struct key_type
*kt
, const char *ciphername
,
499 bool ciphername_defined
, const char *authname
,
500 bool authname_defined
, int keysize
,
501 bool cfb_ofb_allowed
, bool warn
)
504 if (ciphername
&& ciphername_defined
)
506 kt
->cipher
= get_cipher (ciphername
);
507 kt
->cipher_length
= EVP_CIPHER_key_length (kt
->cipher
);
508 if (keysize
> 0 && keysize
<= MAX_CIPHER_KEY_LENGTH
)
509 kt
->cipher_length
= keysize
;
511 /* check legal cipher mode */
513 const unsigned int mode
= EVP_CIPHER_mode (kt
->cipher
);
514 if (!(mode
== EVP_CIPH_CBC_MODE
515 #ifdef ALLOW_NON_CBC_CIPHERS
516 || (cfb_ofb_allowed
&& (mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
))
520 msg (M_FATAL
, "Cipher '%s' mode not supported", ciphername
);
522 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
);
529 msg (M_WARN
, "******* WARNING *******: null cipher specified, no encryption will be used");
531 if (authname
&& authname_defined
)
533 kt
->digest
= get_md (authname
);
534 kt
->hmac_length
= EVP_MD_size (kt
->digest
);
539 msg (M_WARN
, "******* WARNING *******: null MAC specified, no authentication will be used");
544 kt_cipher_name (const struct key_type
*kt
)
547 return EVP_CIPHER_name (kt
->cipher
);
549 return "[null-cipher]";
553 kt_digest_name (const struct key_type
*kt
)
556 return EVP_MD_name (kt
->digest
);
558 return "[null-digest]";
562 kt_key_size (const struct key_type
*kt
)
564 if (kt
->cipher_length
)
565 return kt
->cipher_length
* 8;
567 return EVP_CIPHER_key_length (kt
->cipher
) * 8;
572 /* given a key and key_type, build a key_ctx */
574 init_key_ctx (struct key_ctx
*ctx
, struct key
*key
,
575 const struct key_type
*kt
, int enc
,
579 if (kt
->cipher
&& kt
->cipher_length
> 0)
581 ALLOC_OBJ (ctx
->cipher
, EVP_CIPHER_CTX
);
582 init_cipher (ctx
->cipher
, kt
->cipher
, key
, kt
, enc
, prefix
);
584 if (kt
->digest
&& kt
->hmac_length
> 0)
586 ALLOC_OBJ (ctx
->hmac
, HMAC_CTX
);
587 init_hmac (ctx
->hmac
, kt
->digest
, key
, kt
, prefix
);
592 free_key_ctx (struct key_ctx
*ctx
)
596 EVP_CIPHER_CTX_cleanup (ctx
->cipher
);
602 HMAC_CTX_cleanup (ctx
->hmac
);
609 free_key_ctx_bi (struct key_ctx_bi
*ctx
)
611 free_key_ctx(&ctx
->encrypt
);
612 free_key_ctx(&ctx
->decrypt
);
616 * Return number of DES cblocks for the current
617 * key type or 0 if not a DES cipher.
620 n_DES_cblocks (const struct key_type
*kt
)
623 const char *name
= OBJ_nid2sn (EVP_CIPHER_nid (kt
->cipher
));
626 if (!strncmp (name
, "DES-", 4))
628 ret
= EVP_CIPHER_key_length (kt
->cipher
) / sizeof (DES_cblock
);
630 else if (!strncmp (name
, "DESX-", 5))
635 dmsg (D_CRYPTO_DEBUG
, "CRYPTO INFO: n_DES_cblocks=%d", ret
);
640 check_key_DES (struct key
*key
, const struct key_type
*kt
, int ndc
)
645 buf_set_read (&b
, key
->cipher
, kt
->cipher_length
);
647 for (i
= 0; i
< ndc
; ++i
)
649 DES_cblock
*dc
= (DES_cblock
*) buf_read_alloc (&b
, sizeof (DES_cblock
));
652 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: check_key_DES: insufficient key material");
655 if (DES_is_weak_key(dc
))
657 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: check_key_DES: weak key detected");
660 if (!DES_check_key_parity (dc
))
662 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: check_key_DES: bad parity detected");
674 fixup_key_DES (struct key
*key
, const struct key_type
*kt
, int ndc
)
679 buf_set_read (&b
, key
->cipher
, kt
->cipher_length
);
680 for (i
= 0; i
< ndc
; ++i
)
682 DES_cblock
*dc
= (DES_cblock
*) buf_read_alloc(&b
, sizeof(DES_cblock
));
685 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: fixup_key_DES: insufficient key material");
689 DES_set_odd_parity (dc
);
694 key_is_zero (struct key
*key
, const struct key_type
*kt
)
697 for (i
= 0; i
< kt
->cipher_length
; ++i
)
700 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: WARNING: zero key detected");
705 * Make sure that cipher key is a valid key for current key_type.
708 check_key (struct key
*key
, const struct key_type
*kt
)
715 if (key_is_zero(key
, kt
))
719 * Check for weak or semi-weak DES keys.
722 const int ndc
= n_DES_cblocks (kt
);
724 return check_key_DES (key
, kt
, ndc
);
733 * Make safe mutations to key to ensure it is valid,
734 * such as ensuring correct parity on DES keys.
736 * This routine cannot guarantee it will generate a good
737 * key. You must always call check_key after this routine
741 fixup_key (struct key
*key
, const struct key_type
*kt
)
743 struct gc_arena gc
= gc_new ();
747 const struct key orig
= *key
;
749 const int ndc
= n_DES_cblocks (kt
);
752 fixup_key_DES (key
, kt
, ndc
);
755 if (check_debug_level (D_CRYPTO_DEBUG
))
757 if (memcmp (orig
.cipher
, key
->cipher
, kt
->cipher_length
))
758 dmsg (D_CRYPTO_DEBUG
, "CRYPTO INFO: fixup_key: before=%s after=%s",
759 format_hex (orig
.cipher
, kt
->cipher_length
, 0, &gc
),
760 format_hex (key
->cipher
, kt
->cipher_length
, 0, &gc
));
768 check_replay_iv_consistency (const struct key_type
*kt
, bool packet_id
, bool use_iv
)
770 if (cfb_ofb_mode (kt
) && !(packet_id
&& use_iv
))
771 msg (M_FATAL
, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
775 cfb_ofb_mode (const struct key_type
* kt
)
778 const unsigned int mode
= EVP_CIPHER_mode (kt
->cipher
);
779 return mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
;
785 * Generate a random key. If key_type is provided, make
786 * sure generated key is valid for key_type.
789 generate_key_random (struct key
*key
, const struct key_type
*kt
)
791 int cipher_len
= MAX_CIPHER_KEY_LENGTH
;
792 int hmac_len
= MAX_HMAC_KEY_LENGTH
;
794 struct gc_arena gc
= gc_new ();
800 if (kt
->cipher
&& kt
->cipher_length
> 0 && kt
->cipher_length
<= cipher_len
)
801 cipher_len
= kt
->cipher_length
;
803 if (kt
->digest
&& kt
->hmac_length
> 0 && kt
->hmac_length
<= hmac_len
)
804 hmac_len
= kt
->hmac_length
;
806 if (!RAND_bytes (key
->cipher
, cipher_len
)
807 || !RAND_bytes (key
->hmac
, hmac_len
))
808 msg (M_FATAL
, "ERROR: Random number generator cannot obtain entropy for key generation");
810 dmsg (D_SHOW_KEY_SOURCE
, "Cipher source entropy: %s", format_hex (key
->cipher
, cipher_len
, 0, &gc
));
811 dmsg (D_SHOW_KEY_SOURCE
, "HMAC source entropy: %s", format_hex (key
->hmac
, hmac_len
, 0, &gc
));
815 } while (kt
&& !check_key (key
, kt
));
824 key2_print (const struct key2
* k
,
825 const struct key_type
*kt
,
829 struct gc_arena gc
= gc_new ();
831 dmsg (D_SHOW_KEY_SOURCE
, "%s (cipher): %s",
833 format_hex (k
->keys
[0].cipher
, kt
->cipher_length
, 0, &gc
));
834 dmsg (D_SHOW_KEY_SOURCE
, "%s (hmac): %s",
836 format_hex (k
->keys
[0].hmac
, kt
->hmac_length
, 0, &gc
));
837 dmsg (D_SHOW_KEY_SOURCE
, "%s (cipher): %s",
839 format_hex (k
->keys
[1].cipher
, kt
->cipher_length
, 0, &gc
));
840 dmsg (D_SHOW_KEY_SOURCE
, "%s (hmac): %s",
842 format_hex (k
->keys
[1].hmac
, kt
->hmac_length
, 0, &gc
));
847 test_crypto (const struct crypto_options
*co
, struct frame
* frame
)
850 struct gc_arena gc
= gc_new ();
851 struct buffer src
= alloc_buf_gc (TUN_MTU_SIZE (frame
), &gc
);
852 struct buffer work
= alloc_buf_gc (BUF_SIZE (frame
), &gc
);
853 struct buffer encrypt_workspace
= alloc_buf_gc (BUF_SIZE (frame
), &gc
);
854 struct buffer decrypt_workspace
= alloc_buf_gc (BUF_SIZE (frame
), &gc
);
855 struct buffer buf
= clear_buf();
858 ASSERT (buf_init (&work
, FRAME_HEADROOM (frame
)));
860 msg (M_INFO
, "Entering " PACKAGE_NAME
" crypto self-test mode.");
861 for (i
= 1; i
<= TUN_MTU_SIZE (frame
); ++i
)
865 msg (M_INFO
, "TESTING ENCRYPT/DECRYPT of packet length=%d", i
);
868 * Load src with random data.
870 ASSERT (buf_init (&src
, 0));
871 ASSERT (i
<= src
.capacity
);
873 ASSERT (RAND_pseudo_bytes (BPTR (&src
), BLEN (&src
)));
875 /* copy source to input buf */
877 memcpy (buf_write_alloc (&buf
, BLEN (&src
)), BPTR (&src
), BLEN (&src
));
880 openvpn_encrypt (&buf
, encrypt_workspace
, co
, frame
);
883 openvpn_decrypt (&buf
, decrypt_workspace
, co
, frame
);
886 if (buf
.len
!= src
.len
)
887 msg (M_FATAL
, "SELF TEST FAILED, src.len=%d buf.len=%d", src
.len
, buf
.len
);
888 for (j
= 0; j
< i
; ++j
)
890 const uint8_t in
= *(BPTR (&src
) + j
);
891 const uint8_t out
= *(BPTR (&buf
) + j
);
893 msg (M_FATAL
, "SELF TEST FAILED, pos=%d in=%d out=%d", j
, in
, out
);
896 msg (M_INFO
, PACKAGE_NAME
" crypto self-test mode SUCCEEDED.");
903 get_tls_handshake_key (const struct key_type
*key_type
,
904 struct key_ctx_bi
*ctx
,
905 const char *passphrase_file
,
906 const int key_direction
,
907 const unsigned int flags
)
909 if (passphrase_file
&& key_type
->hmac_length
)
912 struct key_type kt
= *key_type
;
913 struct key_direction_state kds
;
915 /* for control channel we are only authenticating, not encrypting */
916 kt
.cipher_length
= 0;
919 #if ENABLE_INLINE_FILES
920 if (flags
& GHK_INLINE
)
922 /* key was specified inline, key text is in passphrase_file */
923 read_key_file (&key2
, passphrase_file
, RKF_INLINE
|RKF_MUST_SUCCEED
);
927 msg (M_INFO
, "Control Channel Authentication: tls-auth using INLINE static key file");
929 msg (M_FATAL
, "INLINE tls-auth file lacks the requisite 2 keys");
934 /* first try to parse as an OpenVPN static key file */
935 read_key_file (&key2
, passphrase_file
, 0);
941 "Control Channel Authentication: using '%s' as a " PACKAGE_NAME
" static key file",
950 /* failed, now try to get hash from a freeform file */
951 hash_size
= read_passphrase_hash (passphrase_file
,
954 MAX_HMAC_KEY_LENGTH
);
955 ASSERT (hash_size
== kt
.hmac_length
);
961 "Control Channel Authentication: using '%s' as a free-form passphrase file",
965 /* handle key direction */
967 key_direction_state_init (&kds
, key_direction
);
968 must_have_n_keys (passphrase_file
, "tls-auth", &key2
, kds
.need_keys
);
970 /* initialize hmac key in both directions */
972 init_key_ctx (&ctx
->encrypt
, &key2
.keys
[kds
.out_key
], &kt
, DO_ENCRYPT
,
973 "Outgoing Control Channel Authentication");
974 init_key_ctx (&ctx
->decrypt
, &key2
.keys
[kds
.in_key
], &kt
, DO_DECRYPT
,
975 "Incoming Control Channel Authentication");
986 /* header and footer for static key file */
987 static const char static_key_head
[] = "-----BEGIN " PACKAGE_NAME
" Static key V1-----";
988 static const char static_key_foot
[] = "-----END " PACKAGE_NAME
" Static key V1-----";
990 static const char printable_char_fmt
[] =
991 "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
993 static const char unprintable_char_fmt
[] =
994 "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
996 /* read key from file */
999 read_key_file (struct key2
*key2
, const char *file
, const unsigned int flags
)
1001 struct gc_arena gc
= gc_new ();
1004 uint8_t hex_byte
[3] = {0, 0, 0};
1005 const char *error_filename
= file
;
1008 const unsigned char *cp
;
1015 uint8_t* out
= (uint8_t*) &key2
->keys
;
1016 const int keylen
= sizeof (key2
->keys
);
1020 # define PARSE_INITIAL 0
1021 # define PARSE_HEAD 1
1022 # define PARSE_DATA 2
1023 # define PARSE_DATA_COMPLETE 3
1024 # define PARSE_FOOT 4
1025 # define PARSE_FINISHED 5
1026 int state
= PARSE_INITIAL
;
1029 const int hlen
= strlen (static_key_head
);
1030 const int flen
= strlen (static_key_foot
);
1031 const int onekeylen
= sizeof (key2
->keys
[0]);
1036 * Key can be provided as a filename in 'file' or if RKF_INLINE
1037 * is set, the actual key data itself in ascii form.
1039 #if ENABLE_INLINE_FILES
1040 if (flags
& RKF_INLINE
) /* 'file' is a string containing ascii representation of key */
1042 size
= strlen (file
) + 1;
1043 buf_set_read (&in
, (const uint8_t *)file
, size
);
1044 error_filename
= INLINE_FILE_TAG
;
1046 else /* 'file' is a filename which refers to a file containing the ascii key */
1049 in
= alloc_buf_gc (2048, &gc
);
1050 fd
= open (file
, O_RDONLY
);
1052 msg (M_ERR
, "Cannot open file key file '%s'", file
);
1053 size
= read (fd
, in
.data
, in
.capacity
);
1055 msg (M_FATAL
, "Read error on key file ('%s')", file
);
1056 if (size
== in
.capacity
)
1057 msg (M_FATAL
, "Key file ('%s') can be a maximum of %d bytes", file
, (int)in
.capacity
);
1061 cp
= (unsigned char *)in
.data
;
1064 const unsigned char c
= *cp
;
1067 msg (M_INFO
, "char='%c' s=%d ln=%d li=%d m=%d c=%d",
1068 c
, state
, line_num
, line_index
, match
, count
);
1073 line_index
= match
= 0;
1078 /* first char of new line */
1081 /* first char of line after header line? */
1082 if (state
== PARSE_HEAD
)
1085 /* first char of footer */
1086 if ((state
== PARSE_DATA
|| state
== PARSE_DATA_COMPLETE
) && c
== '-')
1090 /* compare read chars with header line */
1091 if (state
== PARSE_INITIAL
)
1093 if (line_index
< hlen
&& c
== static_key_head
[line_index
])
1095 if (++match
== hlen
)
1100 /* compare read chars with footer line */
1101 if (state
== PARSE_FOOT
)
1103 if (line_index
< flen
&& c
== static_key_foot
[line_index
])
1105 if (++match
== flen
)
1106 state
= PARSE_FINISHED
;
1111 if (state
== PARSE_DATA
)
1115 ASSERT (hb_index
>= 0 && hb_index
< 2);
1116 hex_byte
[hb_index
++] = c
;
1120 ASSERT(sscanf((const char *)hex_byte
, "%x", &u
) == 1);
1123 if (++count
== keylen
)
1124 state
= PARSE_DATA_COMPLETE
;
1127 else if (isspace(c
))
1132 (isprint (c
) ? printable_char_fmt
: unprintable_char_fmt
),
1133 c
, line_num
, error_filename
, count
, onekeylen
, keylen
);
1143 * Normally we will read either 1 or 2 keys from file.
1145 key2
->n
= count
/ onekeylen
;
1147 ASSERT (key2
->n
>= 0 && key2
->n
<= (int) SIZE (key2
->keys
));
1149 if (flags
& RKF_MUST_SUCCEED
)
1152 msg (M_FATAL
, "Insufficient key material or header text not found found in file '%s' (%d/%d/%d bytes found/min/max)",
1153 error_filename
, count
, onekeylen
, keylen
);
1155 if (state
!= PARSE_FINISHED
)
1156 msg (M_FATAL
, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1157 error_filename
, count
, onekeylen
, keylen
);
1160 /* zero file read buffer if not an inline file */
1161 #if ENABLE_INLINE_FILES
1162 if (!(flags
& RKF_INLINE
))
1167 warn_if_group_others_accessible (error_filename
);
1173 printf ("KEY READ, n=%d\n", key2
->n
);
1174 for (i
= 0; i
< (int) SIZE (key2
->keys
); ++i
)
1176 /* format key as ascii */
1177 const char *fmt
= format_hex_ex ((const uint8_t*)&key2
->keys
[i
],
1178 sizeof (key2
->keys
[i
]),
1183 printf ("[%d]\n%s\n\n", i
, fmt
);
1188 /* pop our garbage collection level */
1193 read_passphrase_hash (const char *passphrase_file
,
1194 const EVP_MD
*digest
,
1198 unsigned int outlen
= 0;
1201 ASSERT (len
>= EVP_MD_size (digest
));
1202 memset (output
, 0, len
);
1204 EVP_DigestInit (&md
, digest
);
1206 /* read passphrase file */
1208 const int min_passphrase_size
= 8;
1211 int fd
= open (passphrase_file
, O_RDONLY
);
1214 msg (M_ERR
, "Cannot open passphrase file: '%s'", passphrase_file
);
1218 int size
= read (fd
, buf
, sizeof (buf
));
1222 msg (M_ERR
, "Read error on passphrase file: '%s'",
1224 EVP_DigestUpdate (&md
, buf
, size
);
1229 warn_if_group_others_accessible (passphrase_file
);
1231 if (total_size
< min_passphrase_size
)
1233 "Passphrase file '%s' is too small (must have at least %d characters)",
1234 passphrase_file
, min_passphrase_size
);
1237 EVP_DigestFinal (&md
, output
, &outlen
);
1238 EVP_MD_CTX_cleanup (&md
);
1243 * Write key to file, return number of random bits
1247 write_key_file (const int nkeys
, const char *filename
)
1249 struct gc_arena gc
= gc_new ();
1254 /* must be large enough to hold full key file */
1255 struct buffer out
= alloc_buf_gc (2048, &gc
);
1256 struct buffer nbits_head_text
= alloc_buf_gc (128, &gc
);
1258 /* how to format the ascii file representation of key */
1259 const int bytes_per_line
= 16;
1262 fd
= open (filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, S_IRUSR
| S_IWUSR
);
1265 msg (M_ERR
, "Cannot open shared secret file '%s' for write", filename
);
1267 buf_printf (&out
, "%s\n", static_key_head
);
1269 for (i
= 0; i
< nkeys
; ++i
)
1274 /* generate random bits */
1275 generate_key_random (&key
, NULL
);
1277 /* format key as ascii */
1278 fmt
= format_hex_ex ((const uint8_t*)&key
,
1285 /* increment random bits counter */
1286 nbits
+= sizeof (key
) * 8;
1288 /* write to holding buffer */
1289 buf_printf (&out
, "%s\n", fmt
);
1291 /* zero memory which held key component (will be freed by GC) */
1292 memset (fmt
, 0, strlen(fmt
));
1296 buf_printf (&out
, "%s\n", static_key_foot
);
1298 /* write number of bits */
1299 buf_printf (&nbits_head_text
, "#\n# %d bit " PACKAGE_NAME
" static key\n#\n", nbits
);
1300 buf_write_string_file (&nbits_head_text
, filename
, fd
);
1302 /* write key file, now formatted in out, to file */
1303 buf_write_string_file (&out
, filename
, fd
);
1306 msg (M_ERR
, "Close error on shared secret file %s", filename
);
1308 /* zero memory which held file content (memory will be freed by GC) */
1311 /* pop our garbage collection level */
1318 must_have_n_keys (const char *filename
, const char *option
, const struct key2
*key2
, int n
)
1323 msg (M_FATAL
, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename
, option
, key2
->n
, n
);
1325 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
);
1331 ascii2keydirection (int msglevel
, const char *str
)
1334 return KEY_DIRECTION_BIDIRECTIONAL
;
1335 else if (!strcmp (str
, "0"))
1336 return KEY_DIRECTION_NORMAL
;
1337 else if (!strcmp (str
, "1"))
1338 return KEY_DIRECTION_INVERSE
;
1341 msg (msglevel
, "Unknown key direction '%s' -- must be '0' or '1'", str
);
1344 return KEY_DIRECTION_BIDIRECTIONAL
; /* NOTREACHED */
1348 keydirection2ascii (int kd
, bool remote
)
1350 if (kd
== KEY_DIRECTION_BIDIRECTIONAL
)
1352 else if (kd
== KEY_DIRECTION_NORMAL
)
1353 return remote
? "1" : "0";
1354 else if (kd
== KEY_DIRECTION_INVERSE
)
1355 return remote
? "0" : "1";
1360 return NULL
; /* NOTREACHED */
1364 key_direction_state_init (struct key_direction_state
*kds
, int key_direction
)
1367 switch (key_direction
)
1369 case KEY_DIRECTION_NORMAL
:
1374 case KEY_DIRECTION_INVERSE
:
1379 case KEY_DIRECTION_BIDIRECTIONAL
:
1390 verify_fix_key2 (struct key2
*key2
, const struct key_type
*kt
, const char *shared_secret_file
)
1394 for (i
= 0; i
< key2
->n
; ++i
)
1396 /* Fix parity for DES keys and make sure not a weak key */
1397 fixup_key (&key2
->keys
[i
], kt
);
1399 /* This should be a very improbable failure */
1400 if (!check_key (&key2
->keys
[i
], kt
))
1401 msg (M_FATAL
, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
1402 i
+1, shared_secret_file
);
1406 /* given a key and key_type, write key to buffer */
1408 write_key (const struct key
*key
, const struct key_type
*kt
,
1411 ASSERT (kt
->cipher_length
<= MAX_CIPHER_KEY_LENGTH
1412 && kt
->hmac_length
<= MAX_HMAC_KEY_LENGTH
);
1414 if (!buf_write (buf
, &kt
->cipher_length
, 1))
1416 if (!buf_write (buf
, &kt
->hmac_length
, 1))
1418 if (!buf_write (buf
, key
->cipher
, kt
->cipher_length
))
1420 if (!buf_write (buf
, key
->hmac
, kt
->hmac_length
))
1427 * Given a key_type and buffer, read key from buffer.
1428 * Return: 1 on success
1430 * 0 on key length mismatch
1433 read_key (struct key
*key
, const struct key_type
*kt
, struct buffer
*buf
)
1435 uint8_t cipher_length
;
1436 uint8_t hmac_length
;
1439 if (!buf_read (buf
, &cipher_length
, 1))
1441 if (!buf_read (buf
, &hmac_length
, 1))
1444 if (!buf_read (buf
, key
->cipher
, cipher_length
))
1446 if (!buf_read (buf
, key
->hmac
, hmac_length
))
1449 if (cipher_length
!= kt
->cipher_length
|| hmac_length
!= kt
->hmac_length
)
1455 msg (D_TLS_ERRORS
, "TLS Error: error reading key from remote");
1460 "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1461 kt
->cipher_length
, kt
->hmac_length
, cipher_length
, hmac_length
);
1466 show_available_ciphers ()
1471 #ifndef ENABLE_SMALL
1472 printf ("The following ciphers and cipher modes are available\n"
1473 "for use with " PACKAGE_NAME
". Each cipher shown below may be\n"
1474 "used as a parameter to the --cipher option. The default\n"
1475 "key size is shown as well as whether or not it can be\n"
1476 "changed with the --keysize directive. Using a CBC mode\n"
1477 "is recommended.\n\n");
1480 for (nid
= 0; nid
< 10000; ++nid
) /* is there a better way to get the size of the nid list? */
1482 const EVP_CIPHER
*cipher
= EVP_get_cipherbynid (nid
);
1483 if (cipher
&& cipher_ok (OBJ_nid2sn (nid
)))
1485 const unsigned int mode
= EVP_CIPHER_mode (cipher
);
1486 if (mode
== EVP_CIPH_CBC_MODE
1487 #ifdef ALLOW_NON_CBC_CIPHERS
1488 || mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
1491 printf ("%s %d bit default key (%s)\n",
1493 EVP_CIPHER_key_length (cipher
) * 8,
1494 ((EVP_CIPHER_flags (cipher
) & EVP_CIPH_VARIABLE_LENGTH
) ?
1495 "variable" : "fixed"));
1502 show_available_digests ()
1506 #ifndef ENABLE_SMALL
1507 printf ("The following message digests are available for use with\n"
1508 PACKAGE_NAME
". A message digest is used in conjunction with\n"
1509 "the HMAC function, to authenticate received packets.\n"
1510 "You can specify a message digest as parameter to\n"
1511 "the --auth option.\n\n");
1514 for (nid
= 0; nid
< 10000; ++nid
)
1516 const EVP_MD
*digest
= EVP_get_digestbynid (nid
);
1519 printf ("%s %d bit digest size\n",
1520 OBJ_nid2sn (nid
), EVP_MD_size (digest
) * 8);
1527 show_available_engines ()
1532 printf ("OpenSSL Crypto Engines\n\n");
1534 ENGINE_load_builtin_engines ();
1536 e
= ENGINE_get_first ();
1539 printf ("%s [%s]\n",
1540 ENGINE_get_name (e
),
1542 e
= ENGINE_get_next (e
);
1546 printf ("Sorry, OpenSSL hardware crypto engine functionality is not available.\n");
1551 * Enable crypto acceleration, if available
1554 static bool engine_initialized
= false; /* GLOBAL */
1558 static ENGINE
*engine_persist
= NULL
; /* GLOBAL */
1560 /* Try to load an engine in a shareable library */
1562 try_load_engine (const char *engine
)
1564 ENGINE
*e
= ENGINE_by_id ("dynamic");
1567 if (!ENGINE_ctrl_cmd_string (e
, "SO_PATH", engine
, 0)
1568 || !ENGINE_ctrl_cmd_string (e
, "LOAD", NULL
, 0))
1578 setup_engine (const char *engine
)
1582 ENGINE_load_builtin_engines ();
1586 if (strcmp (engine
, "auto") == 0)
1588 msg (M_INFO
, "Initializing OpenSSL auto engine support");
1589 ENGINE_register_all_complete ();
1592 if ((e
= ENGINE_by_id (engine
)) == NULL
1593 && (e
= try_load_engine (engine
)) == NULL
)
1595 msg (M_FATAL
, "OpenSSL error: cannot load engine '%s'", engine
);
1598 if (!ENGINE_set_default (e
, ENGINE_METHOD_ALL
))
1600 msg (M_FATAL
, "OpenSSL error: ENGINE_set_default failed on engine '%s'",
1604 msg (M_INFO
, "Initializing OpenSSL support for engine '%s'",
1612 init_crypto_lib_engine (const char *engine_name
)
1614 if (!engine_initialized
)
1617 ASSERT (engine_name
);
1618 ASSERT (!engine_persist
);
1619 engine_persist
= setup_engine (engine_name
);
1621 msg (M_WARN
, "Note: OpenSSL hardware crypto engine functionality is not available");
1623 engine_initialized
= true;
1628 * This routine should have additional OpenSSL crypto library initialisations
1629 * used by both crypto and ssl components of OpenVPN.
1631 void init_crypto_lib ()
1635 void uninit_crypto_lib ()
1638 if (engine_initialized
)
1641 engine_persist
= NULL
;
1642 engine_initialized
= false;
1649 * Random number functions, used in cases where we want
1650 * reasonably strong cryptographic random number generation
1651 * without depleting our entropy pool. Used for random
1652 * IV values and a number of other miscellaneous tasks.
1655 static uint8_t *nonce_data
; /* GLOBAL */
1656 static const EVP_MD
*nonce_md
= NULL
; /* GLOBAL */
1657 static int nonce_secret_len
; /* GLOBAL */
1660 prng_init (const char *md_name
, const int nonce_secret_len_parm
)
1663 nonce_md
= md_name
? get_md (md_name
) : NULL
;
1666 ASSERT (nonce_secret_len_parm
>= NONCE_SECRET_LEN_MIN
&& nonce_secret_len_parm
<= NONCE_SECRET_LEN_MAX
);
1667 nonce_secret_len
= nonce_secret_len_parm
;
1669 const int size
= EVP_MD_size (nonce_md
) + nonce_secret_len
;
1670 dmsg (D_CRYPTO_DEBUG
, "PRNG init md=%s size=%d", EVP_MD_name (nonce_md
), size
);
1671 nonce_data
= (uint8_t*) malloc (size
);
1672 check_malloc_return (nonce_data
);
1673 #if 1 /* Must be 1 for real usage */
1674 if (!RAND_bytes (nonce_data
, size
))
1675 msg (M_FATAL
, "ERROR: Random number generator cannot obtain entropy for PRNG");
1677 /* Only for testing -- will cause a predictable PRNG sequence */
1680 for (i
= 0; i
< size
; ++i
)
1681 nonce_data
[i
] = (uint8_t) i
;
1694 nonce_secret_len
= 0;
1698 prng_bytes (uint8_t *output
, int len
)
1703 const int md_size
= EVP_MD_size (nonce_md
);
1704 mutex_lock_static (L_PRNG
);
1707 unsigned int outlen
= 0;
1708 const int blen
= min_int (len
, md_size
);
1709 EVP_DigestInit (&ctx
, nonce_md
);
1710 EVP_DigestUpdate (&ctx
, nonce_data
, md_size
+ nonce_secret_len
);
1711 EVP_DigestFinal (&ctx
, nonce_data
, &outlen
);
1712 ASSERT (outlen
== md_size
);
1713 EVP_MD_CTX_cleanup (&ctx
);
1714 memcpy (output
, nonce_data
, blen
);
1718 mutex_unlock_static (L_PRNG
);
1721 RAND_bytes (output
, len
);
1724 /* an analogue to the random() function, but use prng_bytes */
1729 prng_bytes ((unsigned char *)&l
, sizeof(l
));
1736 md5sum (uint8_t *buf
, int len
, int n_print_chars
, struct gc_arena
*gc
)
1738 uint8_t digest
[MD5_DIGEST_LENGTH
];
1739 MD5 (buf
, len
, digest
);
1740 return format_hex (digest
, MD5_DIGEST_LENGTH
, n_print_chars
, gc
);
1744 * OpenSSL memory debugging. If dmalloc debugging is enabled, tell
1745 * OpenSSL to use our private malloc/realloc/free functions so that
1746 * we can dispatch them to dmalloc.
1752 crypto_malloc (size_t size
, const char *file
, int line
)
1754 return dmalloc_malloc(file
, line
, size
, DMALLOC_FUNC_MALLOC
, 0, 0);
1758 crypto_realloc (void *ptr
, size_t size
, const char *file
, int line
)
1760 return dmalloc_realloc(file
, line
, ptr
, size
, DMALLOC_FUNC_REALLOC
, 0);
1764 crypto_free (void *ptr
)
1766 dmalloc_free (__FILE__
, __LINE__
, ptr
, DMALLOC_FUNC_FREE
);
1770 openssl_dmalloc_init (void)
1772 CRYPTO_set_mem_ex_functions (crypto_malloc
,
1777 #endif /* DMALLOC */
1784 ERR_load_crypto_strings ();
1785 OpenSSL_add_all_algorithms ();
1792 uninit_crypto_lib ();
1794 ERR_free_strings ();
1797 #endif /* USE_SSL */
1804 md5_state_init (struct md5_state
*s
)
1810 md5_state_update (struct md5_state
*s
, void *data
, size_t len
)
1812 MD5_Update (&s
->ctx
, data
, len
);
1816 md5_state_final (struct md5_state
*s
, struct md5_digest
*out
)
1818 MD5_Final (out
->digest
, &s
->ctx
);
1822 md5_digest_clear (struct md5_digest
*digest
)
1828 md5_digest_defined (const struct md5_digest
*digest
)
1831 for (i
= 0; i
< MD5_DIGEST_LENGTH
; ++i
)
1832 if (digest
->digest
[i
])
1838 md5_digest_equal (const struct md5_digest
*d1
, const struct md5_digest
*d2
)
1840 return memcmp(d1
->digest
, d2
->digest
, MD5_DIGEST_LENGTH
) == 0;
1843 #endif /* USE_CRYPTO */