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-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
26 #include "config-win32.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
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
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)
81 openvpn_encrypt (struct buffer
*buf
, struct buffer work
,
82 const struct crypto_options
*opt
,
83 const struct frame
* frame
)
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 */
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
);
100 if (mode
== EVP_CIPH_CBC_MODE
)
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 */
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
;
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 */
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",
157 EVP_CIPHER_CTX_block_size (ctx
->cipher
));
161 /* Encrypt packet ID, payload */
162 ASSERT (EVP_CipherUpdate_ov (ctx
->cipher
, BPTR (&work
), &outlen
, BPTR (buf
), BLEN (buf
)));
165 /* Flush the encryption buffer */
166 ASSERT (EVP_CipherFinal (ctx
->cipher
, BPTR (&work
) + outlen
, &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
);
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 */
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));
192 /* HMAC the ciphertext (or plaintext if !cipher) */
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
));
202 HMAC_Final (ctx
->hmac
, output
, (unsigned int *)&hmac_len
);
203 ASSERT (hmac_len
== HMAC_size (ctx
->hmac
));
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
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";
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 */
246 uint8_t local_hmac
[MAX_HMAC_KEY_LENGTH
]; /* HMAC of ciphertext computed locally */
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 */
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
];
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 */
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
));
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");
312 /* Flush the decryption buffer */
313 if (!EVP_CipherFinal (ctx
->cipher
, BPTR (&work
) + outlen
, &outlen
))
314 CRYPT_ERROR ("cipher final failed");
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
)
326 if (!packet_id_read (&pin
, &work
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
)))
327 CRYPT_ERROR ("error reading CBC packet-id");
331 else if (mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
)
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");
343 else /* We only support CBC, CFB, or OFB modes right now */
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
);
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
);
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
));
391 * How many bytes will we add to frame buffer for a given
392 * set of crypto options?
395 crypto_adjust_frame_parameters(struct frame
*frame
,
396 const struct key_type
* kt
,
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 */
409 static const EVP_CIPHER
*
410 get_cipher (const char *ciphername
)
412 const EVP_CIPHER
*cipher
= NULL
;
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)",
420 EVP_CIPHER_key_length (cipher
),
421 MAX_CIPHER_KEY_LENGTH
);
425 static const EVP_MD
*
426 get_md (const char *digest
)
428 const EVP_MD
*md
= NULL
;
430 md
= EVP_get_digestbyname (digest
);
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)",
437 MAX_HMAC_KEY_LENGTH
);
442 init_cipher (EVP_CIPHER_CTX
*ctx
, const EVP_CIPHER
*cipher
,
443 struct key
*key
, const struct key_type
*kt
, int enc
,
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");
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",
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",
470 EVP_CIPHER_CTX_block_size (ctx
),
471 EVP_CIPHER_CTX_iv_length (ctx
));
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 ();
483 HMAC_Init_ex (ctx
, key
->hmac
, kt
->hmac_length
, digest
, NULL
);
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",
495 EVP_MD_size (digest
),
496 EVP_MD_block_size (digest
));
502 * Build a struct key_type.
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
)
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
))
527 msg (M_FATAL
, "Cipher '%s' mode not supported", ciphername
);
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
);
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
);
546 msg (M_WARN
, "******* WARNING *******: null MAC specified, no authentication will be used");
551 kt_cipher_name (const struct key_type
*kt
)
554 return EVP_CIPHER_name (kt
->cipher
);
556 return "[null-cipher]";
560 kt_digest_name (const struct key_type
*kt
)
563 return EVP_MD_name (kt
->digest
);
565 return "[null-digest]";
569 kt_key_size (const struct key_type
*kt
)
571 if (kt
->cipher_length
)
572 return kt
->cipher_length
* 8;
574 return EVP_CIPHER_key_length (kt
->cipher
) * 8;
579 /* given a key and key_type, build a key_ctx */
581 init_key_ctx (struct key_ctx
*ctx
, struct key
*key
,
582 const struct key_type
*kt
, int enc
,
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
);
599 free_key_ctx (struct key_ctx
*ctx
)
603 EVP_CIPHER_CTX_cleanup (ctx
->cipher
);
609 HMAC_CTX_cleanup (ctx
->hmac
);
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.
627 n_DES_cblocks (const struct key_type
*kt
)
630 const char *name
= OBJ_nid2sn (EVP_CIPHER_nid (kt
->cipher
));
633 if (!strncmp (name
, "DES-", 4))
635 ret
= EVP_CIPHER_key_length (kt
->cipher
) / sizeof (DES_cblock
);
637 else if (!strncmp (name
, "DESX-", 5))
642 dmsg (D_CRYPTO_DEBUG
, "CRYPTO INFO: n_DES_cblocks=%d", ret
);
647 check_key_DES (struct key
*key
, const struct key_type
*kt
, int ndc
)
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
));
659 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: check_key_DES: insufficient key material");
662 if (DES_is_weak_key(dc
))
664 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: check_key_DES: weak key detected");
667 if (!DES_check_key_parity (dc
))
669 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: check_key_DES: bad parity detected");
681 fixup_key_DES (struct key
*key
, const struct key_type
*kt
, int ndc
)
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
));
692 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: fixup_key_DES: insufficient key material");
696 DES_set_odd_parity (dc
);
701 key_is_zero (struct key
*key
, const struct key_type
*kt
)
704 for (i
= 0; i
< kt
->cipher_length
; ++i
)
707 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: WARNING: zero key detected");
712 * Make sure that cipher key is a valid key for current key_type.
715 check_key (struct key
*key
, const struct key_type
*kt
)
722 if (key_is_zero(key
, kt
))
726 * Check for weak or semi-weak DES keys.
729 const int ndc
= n_DES_cblocks (kt
);
731 return check_key_DES (key
, kt
, ndc
);
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
748 fixup_key (struct key
*key
, const struct key_type
*kt
)
750 struct gc_arena gc
= gc_new ();
754 const struct key orig
= *key
;
756 const int ndc
= n_DES_cblocks (kt
);
759 fixup_key_DES (key
, kt
, ndc
);
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
));
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");
782 cfb_ofb_mode (const struct key_type
* kt
)
785 const unsigned int mode
= EVP_CIPHER_mode (kt
->cipher
);
786 return mode
== EVP_CIPH_CFB_MODE
|| mode
== EVP_CIPH_OFB_MODE
;
792 * Generate a random key. If key_type is provided, make
793 * sure generated key is valid for key_type.
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 ();
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
));
822 } while (kt
&& !check_key (key
, kt
));
831 key2_print (const struct key2
* k
,
832 const struct key_type
*kt
,
836 struct gc_arena gc
= gc_new ();
838 dmsg (D_SHOW_KEY_SOURCE
, "%s (cipher): %s",
840 format_hex (k
->keys
[0].cipher
, kt
->cipher_length
, 0, &gc
));
841 dmsg (D_SHOW_KEY_SOURCE
, "%s (hmac): %s",
843 format_hex (k
->keys
[0].hmac
, kt
->hmac_length
, 0, &gc
));
844 dmsg (D_SHOW_KEY_SOURCE
, "%s (cipher): %s",
846 format_hex (k
->keys
[1].cipher
, kt
->cipher_length
, 0, &gc
));
847 dmsg (D_SHOW_KEY_SOURCE
, "%s (hmac): %s",
849 format_hex (k
->keys
[1].hmac
, kt
->hmac_length
, 0, &gc
));
854 test_crypto (const struct crypto_options
*co
, struct frame
* frame
)
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();
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
)
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
);
880 ASSERT (RAND_pseudo_bytes (BPTR (&src
), BLEN (&src
)));
882 /* copy source to input buf */
884 memcpy (buf_write_alloc (&buf
, BLEN (&src
)), BPTR (&src
), BLEN (&src
));
887 openvpn_encrypt (&buf
, encrypt_workspace
, co
, frame
);
890 openvpn_decrypt (&buf
, decrypt_workspace
, co
, frame
);
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
);
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.");
909 get_tls_handshake_key (const struct key_type
*key_type
,
910 struct key_ctx_bi
*ctx
,
911 const char *passphrase_file
,
914 if (passphrase_file
&& key_type
->hmac_length
)
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;
924 /* first try to parse as an OpenVPN static key file */
925 read_key_file (&key2
, passphrase_file
, false);
931 "Control Channel Authentication: using '%s' as a " PACKAGE_NAME
" static key file",
940 /* failed, now try to get hash from a freeform file */
941 hash_size
= read_passphrase_hash (passphrase_file
,
944 MAX_HMAC_KEY_LENGTH
);
945 ASSERT (hash_size
== kt
.hmac_length
);
951 "Control Channel Authentication: using '%s' as a free-form 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");
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 */
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
);
993 uint8_t hex_byte
[3] = {0, 0, 0};
1002 uint8_t* out
= (uint8_t*) &key2
->keys
;
1003 const int keylen
= sizeof (key2
->keys
);
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
;
1016 const int hlen
= strlen (static_key_head
);
1017 const int flen
= strlen (static_key_foot
);
1018 const int onekeylen
= sizeof (key2
->keys
[0]);
1022 fd
= open (filename
, O_RDONLY
);
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
;
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
);
1040 line_index
= match
= 0;
1045 /* first char of new line */
1048 /* first char of line after header line? */
1049 if (state
== PARSE_HEAD
)
1052 /* first char of footer */
1053 if ((state
== PARSE_DATA
|| state
== PARSE_DATA_COMPLETE
) && c
== '-')
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
)
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
;
1078 if (state
== PARSE_DATA
)
1082 ASSERT (hb_index
>= 0 && hb_index
< 2);
1083 hex_byte
[hb_index
++] = c
;
1087 ASSERT(sscanf((const char *)hex_byte
, "%x", &u
) == 1);
1090 if (++count
== keylen
)
1091 state
= PARSE_DATA_COMPLETE
;
1094 else if (isspace(c
))
1099 (isprint (c
) ? printable_char_fmt
: unprintable_char_fmt
),
1100 c
, line_num
, filename
, count
, onekeylen
, keylen
);
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
));
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 */
1134 warn_if_group_others_accessible (filename
);
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
]),
1150 printf ("[%d]\n%s\n\n", i
, fmt
);
1155 /* pop our garbage collection level */
1160 read_passphrase_hash (const char *passphrase_file
,
1161 const EVP_MD
*digest
,
1165 unsigned int outlen
= 0;
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;
1178 int fd
= open (passphrase_file
, O_RDONLY
);
1181 msg (M_ERR
, "Cannot open passphrase file: '%s'", passphrase_file
);
1185 int size
= read (fd
, buf
, sizeof (buf
));
1189 msg (M_ERR
, "Read error on passphrase file: '%s'",
1191 EVP_DigestUpdate (&md
, buf
, size
);
1196 warn_if_group_others_accessible (passphrase_file
);
1198 if (total_size
< min_passphrase_size
)
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
);
1210 * Write key to file, return number of random bits
1214 write_key_file (const int nkeys
, const char *filename
)
1216 struct gc_arena gc
= gc_new ();
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;
1229 fd
= open (filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, S_IRUSR
| S_IWUSR
);
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
)
1241 /* generate random bits */
1242 generate_key_random (&key
, NULL
);
1244 /* format key as ascii */
1245 fmt
= format_hex_ex ((const uint8_t*)&key
,
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
));
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
);
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) */
1278 /* pop our garbage collection level */
1285 must_have_n_keys (const char *filename
, const char *option
, const struct key2
*key2
, int n
)
1290 msg (M_FATAL
, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename
, option
, key2
->n
, n
);
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
);
1298 ascii2keydirection (int msglevel
, const char *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
;
1308 msg (msglevel
, "Unknown key direction '%s' -- must be '0' or '1'", str
);
1311 return KEY_DIRECTION_BIDIRECTIONAL
; /* NOTREACHED */
1315 keydirection2ascii (int kd
, bool remote
)
1317 if (kd
== KEY_DIRECTION_BIDIRECTIONAL
)
1319 else if (kd
== KEY_DIRECTION_NORMAL
)
1320 return remote
? "1" : "0";
1321 else if (kd
== KEY_DIRECTION_INVERSE
)
1322 return remote
? "0" : "1";
1327 return NULL
; /* NOTREACHED */
1331 key_direction_state_init (struct key_direction_state
*kds
, int key_direction
)
1334 switch (key_direction
)
1336 case KEY_DIRECTION_NORMAL
:
1341 case KEY_DIRECTION_INVERSE
:
1346 case KEY_DIRECTION_BIDIRECTIONAL
:
1357 verify_fix_key2 (struct key2
*key2
, const struct key_type
*kt
, const char *shared_secret_file
)
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 */
1375 write_key (const struct key
*key
, const struct key_type
*kt
,
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))
1383 if (!buf_write (buf
, &kt
->hmac_length
, 1))
1385 if (!buf_write (buf
, key
->cipher
, kt
->cipher_length
))
1387 if (!buf_write (buf
, key
->hmac
, kt
->hmac_length
))
1394 * Given a key_type and buffer, read key from buffer.
1395 * Return: 1 on success
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
;
1406 if (!buf_read (buf
, &cipher_length
, 1))
1408 if (!buf_read (buf
, &hmac_length
, 1))
1411 if (!buf_read (buf
, key
->cipher
, cipher_length
))
1413 if (!buf_read (buf
, key
->hmac
, hmac_length
))
1416 if (cipher_length
!= kt
->cipher_length
|| hmac_length
!= kt
->hmac_length
)
1422 msg (D_TLS_ERRORS
, "TLS Error: error reading key from remote");
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
);
1433 show_available_ciphers ()
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");
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
1458 printf ("%s %d bit default key (%s)\n",
1460 EVP_CIPHER_key_length (cipher
) * 8,
1461 ((EVP_CIPHER_flags (cipher
) & EVP_CIPH_VARIABLE_LENGTH
) ?
1462 "variable" : "fixed"));
1469 show_available_digests ()
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");
1481 for (nid
= 0; nid
< 10000; ++nid
)
1483 const EVP_MD
*digest
= EVP_get_digestbynid (nid
);
1486 printf ("%s %d bit digest size\n",
1487 OBJ_nid2sn (nid
), EVP_MD_size (digest
) * 8);
1494 show_available_engines ()
1499 printf ("OpenSSL Crypto Engines\n\n");
1501 ENGINE_load_builtin_engines ();
1503 e
= ENGINE_get_first ();
1506 printf ("%s [%s]\n",
1507 ENGINE_get_name (e
),
1509 e
= ENGINE_get_next (e
);
1513 printf ("Sorry, OpenSSL hardware crypto engine functionality is not available.\n");
1518 * Enable crypto acceleration, if available
1521 static bool engine_initialized
= false; /* GLOBAL */
1525 static ENGINE
*engine_persist
= NULL
; /* GLOBAL */
1527 /* Try to load an engine in a shareable library */
1529 try_load_engine (const char *engine
)
1531 ENGINE
*e
= ENGINE_by_id ("dynamic");
1534 if (!ENGINE_ctrl_cmd_string (e
, "SO_PATH", engine
, 0)
1535 || !ENGINE_ctrl_cmd_string (e
, "LOAD", NULL
, 0))
1545 setup_engine (const char *engine
)
1549 ENGINE_load_builtin_engines ();
1553 if (strcmp (engine
, "auto") == 0)
1555 msg (M_INFO
, "Initializing OpenSSL auto engine support");
1556 ENGINE_register_all_complete ();
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'",
1571 msg (M_INFO
, "Initializing OpenSSL support for engine '%s'",
1579 init_crypto_lib_engine (const char *engine_name
)
1581 if (!engine_initialized
)
1584 ASSERT (engine_name
);
1585 ASSERT (!engine_persist
);
1586 engine_persist
= setup_engine (engine_name
);
1588 msg (M_WARN
, "Note: OpenSSL hardware crypto engine functionality is not available");
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 ()
1605 if (engine_initialized
)
1608 engine_persist
= NULL
;
1609 engine_initialized
= false;
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 */
1628 if (!RAND_bytes (nonce_data
, sizeof(nonce_data
)))
1629 msg (M_FATAL
, "ERROR: Random number generator cannot obtain entropy for PRNG");
1633 prng_bytes (uint8_t *output
, int len
)
1636 mutex_lock_static (L_PRNG
);
1639 const int blen
= min_int (len
, SHA_DIGEST_LENGTH
);
1641 SHA1_Update (&ctx
, nonce_data
, sizeof (nonce_data
));
1642 SHA1_Final (nonce_data
, &ctx
);
1643 memcpy (output
, nonce_data
, blen
);
1647 mutex_unlock_static (L_PRNG
);
1650 /* an analogue to the random() function, but use prng_bytes */
1655 prng_bytes ((unsigned char *)&l
, sizeof(l
));
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.
1678 crypto_malloc (size_t size
, const char *file
, int line
)
1680 return dmalloc_malloc(file
, line
, size
, DMALLOC_FUNC_MALLOC
, 0, 0);
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);
1690 crypto_free (void *ptr
)
1692 dmalloc_free (__FILE__
, __LINE__
, ptr
, DMALLOC_FUNC_FREE
);
1696 openssl_dmalloc_init (void)
1698 CRYPTO_set_mem_ex_functions (crypto_malloc
,
1703 #endif /* DMALLOC */
1710 ERR_load_crypto_strings ();
1711 OpenSSL_add_all_algorithms ();
1718 uninit_crypto_lib ();
1720 ERR_free_strings ();
1723 #endif /* USE_SSL */
1724 #endif /* USE_CRYPTO */