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-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9 * Copyright (C) 2010 Fox Crypto B.V. <openvpn@fox-it.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2
13 * as published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program (see the file COPYING included with this
22 * distribution); if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #elif defined(_MSC_VER)
29 #include "config-msvc.h"
43 * Encryption and Compression Routines.
45 * On entry, buf contains the input data and length.
46 * On exit, it should be set to the output data and length.
48 * If buf->len is <= 0 we should return
49 * If buf->len is set to 0 on exit it tells the caller to ignore the packet.
51 * work is a workspace buffer we are given of size BUF_SIZE.
52 * work may be used to return output data, or the input buffer
53 * may be modified and returned as output. If output data is
54 * returned in work, the data should start after FRAME_HEADROOM bytes
55 * of padding to leave room for downstream routines to prepend.
57 * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
58 * by all routines (encryption, decryption, compression, and decompression).
60 * Note that the buf_prepend return will assert if we try to
61 * make a header bigger than FRAME_HEADROOM. This should not
62 * happen unless the frame parameters are wrong.
65 #define CRYPT_ERROR(format) \
66 do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
69 * As memcmp(), but constant-time.
70 * Returns 0 when data is equal, non-zero otherwise.
73 memcmp_constant_time (const void *a
, const void *b
, size_t size
) {
74 const uint8_t * a1
= a
;
75 const uint8_t * b1
= b
;
79 for (i
= 0; i
< size
; i
++) {
87 openvpn_encrypt (struct buffer
*buf
, struct buffer work
,
88 const struct crypto_options
*opt
,
89 const struct frame
* frame
)
94 if (buf
->len
> 0 && opt
->key_ctx_bi
)
96 struct key_ctx
*ctx
= &opt
->key_ctx_bi
->encrypt
;
98 /* Do Encrypt from buf -> work */
101 uint8_t iv_buf
[OPENVPN_MAX_IV_LENGTH
];
102 const int iv_size
= cipher_ctx_iv_length (ctx
->cipher
);
103 const unsigned int mode
= cipher_ctx_mode (ctx
->cipher
);
106 if (mode
== OPENVPN_MODE_CBC
)
110 /* generate pseudo-random IV */
111 if (opt
->flags
& CO_USE_IV
)
112 prng_bytes (iv_buf
, iv_size
);
114 /* Put packet ID in plaintext buffer or IV, depending on cipher mode */
117 struct packet_id_net pin
;
118 packet_id_alloc_outgoing (&opt
->packet_id
->send
, &pin
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
));
119 ASSERT (packet_id_write (&pin
, buf
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
), true));
122 else if (mode
== OPENVPN_MODE_CFB
|| mode
== OPENVPN_MODE_OFB
)
124 struct packet_id_net pin
;
127 ASSERT (opt
->flags
& CO_USE_IV
); /* IV and packet-ID required */
128 ASSERT (opt
->packet_id
); /* for this mode. */
130 packet_id_alloc_outgoing (&opt
->packet_id
->send
, &pin
, true);
131 memset (iv_buf
, 0, iv_size
);
132 buf_set_write (&b
, iv_buf
, iv_size
);
133 ASSERT (packet_id_write (&pin
, &b
, true, false));
135 else /* We only support CBC, CFB, or OFB modes right now */
140 /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
141 ASSERT (buf_init (&work
, FRAME_HEADROOM (frame
)));
143 /* set the IV pseudo-randomly */
144 if (opt
->flags
& CO_USE_IV
)
145 dmsg (D_PACKET_CONTENT
, "ENCRYPT IV: %s", format_hex (iv_buf
, iv_size
, 0, &gc
));
147 dmsg (D_PACKET_CONTENT
, "ENCRYPT FROM: %s",
148 format_hex (BPTR (buf
), BLEN (buf
), 80, &gc
));
150 /* cipher_ctx was already initialized with key & keylen */
151 ASSERT (cipher_ctx_reset(ctx
->cipher
, iv_buf
));
153 /* Buffer overflow check */
154 if (!buf_safe (&work
, buf
->len
+ cipher_ctx_block_size(ctx
->cipher
)))
156 msg (D_CRYPT_ERRORS
, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d",
163 cipher_ctx_block_size (ctx
->cipher
));
167 /* Encrypt packet ID, payload */
168 ASSERT (cipher_ctx_update (ctx
->cipher
, BPTR (&work
), &outlen
, BPTR (buf
), BLEN (buf
)));
171 /* Flush the encryption buffer */
172 ASSERT(cipher_ctx_final(ctx
->cipher
, BPTR (&work
) + outlen
, &outlen
));
174 ASSERT (outlen
== iv_size
);
176 /* prepend the IV to the ciphertext */
177 if (opt
->flags
& CO_USE_IV
)
179 uint8_t *output
= buf_prepend (&work
, iv_size
);
181 memcpy (output
, iv_buf
, iv_size
);
184 dmsg (D_PACKET_CONTENT
, "ENCRYPT TO: %s",
185 format_hex (BPTR (&work
), BLEN (&work
), 80, &gc
));
187 else /* No Encryption */
191 struct packet_id_net pin
;
192 packet_id_alloc_outgoing (&opt
->packet_id
->send
, &pin
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
));
193 ASSERT (packet_id_write (&pin
, buf
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
), true));
198 /* HMAC the ciphertext (or plaintext if !cipher) */
201 uint8_t *output
= NULL
;
203 hmac_ctx_reset (ctx
->hmac
);
204 hmac_ctx_update (ctx
->hmac
, BPTR(&work
), BLEN(&work
));
205 output
= buf_prepend (&work
, hmac_ctx_size(ctx
->hmac
));
207 hmac_ctx_final (ctx
->hmac
, output
);
217 crypto_clear_error();
224 * If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet.
226 * Set buf->len to 0 and return false on decrypt error.
228 * On success, buf is set to point to plaintext, true
232 openvpn_decrypt (struct buffer
*buf
, struct buffer work
,
233 const struct crypto_options
*opt
,
234 const struct frame
* frame
)
236 static const char error_prefix
[] = "Authenticate/Decrypt packet error";
240 if (buf
->len
> 0 && opt
->key_ctx_bi
)
242 struct key_ctx
*ctx
= &opt
->key_ctx_bi
->decrypt
;
243 struct packet_id_net pin
;
244 bool have_pin
= false;
246 /* Verify the HMAC */
250 uint8_t local_hmac
[MAX_HMAC_KEY_LENGTH
]; /* HMAC of ciphertext computed locally */
252 hmac_ctx_reset(ctx
->hmac
);
254 /* Assume the length of the input HMAC */
255 hmac_len
= hmac_ctx_size (ctx
->hmac
);
257 /* Authentication fails if insufficient data in packet for HMAC */
258 if (buf
->len
< hmac_len
)
259 CRYPT_ERROR ("missing authentication info");
261 hmac_ctx_update (ctx
->hmac
, BPTR (buf
) + hmac_len
, BLEN (buf
) - hmac_len
);
262 hmac_ctx_final (ctx
->hmac
, local_hmac
);
264 /* Compare locally computed HMAC with packet HMAC */
265 if (memcmp_constant_time (local_hmac
, BPTR (buf
), hmac_len
))
266 CRYPT_ERROR ("packet HMAC authentication failed");
268 ASSERT (buf_advance (buf
, hmac_len
));
271 /* Decrypt packet ID + payload */
275 const unsigned int mode
= cipher_ctx_mode (ctx
->cipher
);
276 const int iv_size
= cipher_ctx_iv_length (ctx
->cipher
);
277 uint8_t iv_buf
[OPENVPN_MAX_IV_LENGTH
];
280 /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
281 ASSERT (buf_init (&work
, FRAME_HEADROOM_ADJ (frame
, FRAME_HEADROOM_MARKER_DECRYPT
)));
283 /* use IV if user requested it */
285 if (opt
->flags
& CO_USE_IV
)
287 if (buf
->len
< iv_size
)
288 CRYPT_ERROR ("missing IV info");
289 memcpy (iv_buf
, BPTR (buf
), iv_size
);
290 ASSERT (buf_advance (buf
, iv_size
));
293 /* show the IV's initial state */
294 if (opt
->flags
& CO_USE_IV
)
295 dmsg (D_PACKET_CONTENT
, "DECRYPT IV: %s", format_hex (iv_buf
, iv_size
, 0, &gc
));
298 CRYPT_ERROR ("missing payload");
300 /* ctx->cipher was already initialized with key & keylen */
301 if (!cipher_ctx_reset (ctx
->cipher
, iv_buf
))
302 CRYPT_ERROR ("cipher init failed");
304 /* Buffer overflow check (should never happen) */
305 if (!buf_safe (&work
, buf
->len
))
306 CRYPT_ERROR ("buffer overflow");
308 /* Decrypt packet ID, payload */
309 if (!cipher_ctx_update (ctx
->cipher
, BPTR (&work
), &outlen
, BPTR (buf
), BLEN (buf
)))
310 CRYPT_ERROR ("cipher update failed");
313 /* Flush the decryption buffer */
314 if (!cipher_ctx_final (ctx
->cipher
, BPTR (&work
) + outlen
, &outlen
))
315 CRYPT_ERROR ("cipher final failed");
318 dmsg (D_PACKET_CONTENT
, "DECRYPT TO: %s",
319 format_hex (BPTR (&work
), BLEN (&work
), 80, &gc
));
321 /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
323 if (mode
== OPENVPN_MODE_CBC
)
327 if (!packet_id_read (&pin
, &work
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
)))
328 CRYPT_ERROR ("error reading CBC packet-id");
332 else if (mode
== OPENVPN_MODE_CFB
|| mode
== OPENVPN_MODE_OFB
)
336 ASSERT (opt
->flags
& CO_USE_IV
); /* IV and packet-ID required */
337 ASSERT (opt
->packet_id
); /* for this mode. */
339 buf_set_read (&b
, iv_buf
, iv_size
);
340 if (!packet_id_read (&pin
, &b
, true))
341 CRYPT_ERROR ("error reading CFB/OFB packet-id");
344 else /* We only support CBC, CFB, or OFB modes right now */
355 if (!packet_id_read (&pin
, &work
, BOOL_CAST (opt
->flags
& CO_PACKET_ID_LONG_FORM
)))
356 CRYPT_ERROR ("error reading packet-id");
357 have_pin
= !BOOL_CAST (opt
->flags
& CO_IGNORE_PACKET_ID
);
363 packet_id_reap_test (&opt
->packet_id
->rec
);
364 if (packet_id_test (&opt
->packet_id
->rec
, &pin
))
366 packet_id_add (&opt
->packet_id
->rec
, &pin
);
367 if (opt
->pid_persist
&& (opt
->flags
& CO_PACKET_ID_LONG_FORM
))
368 packet_id_persist_save_obj (opt
->pid_persist
, opt
->packet_id
);
372 if (!(opt
->flags
& CO_MUTE_REPLAY_WARNINGS
))
373 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",
374 error_prefix
, packet_id_net_print (&pin
, true, &gc
));
385 crypto_clear_error();
392 * How many bytes will we add to frame buffer for a given
393 * set of crypto options?
396 crypto_adjust_frame_parameters(struct frame
*frame
,
397 const struct key_type
* kt
,
401 bool packet_id_long_form
)
403 frame_add_to_extra_frame (frame
,
404 (packet_id
? packet_id_size (packet_id_long_form
) : 0) +
405 ((cipher_defined
&& use_iv
) ? cipher_kt_iv_size (kt
->cipher
) : 0) +
406 (cipher_defined
? cipher_kt_block_size (kt
->cipher
) : 0) + /* worst case padding expansion */
411 * Build a struct key_type.
414 init_key_type (struct key_type
*kt
, const char *ciphername
,
415 bool ciphername_defined
, const char *authname
,
416 bool authname_defined
, int keysize
,
417 bool cfb_ofb_allowed
, bool warn
)
420 if (ciphername
&& ciphername_defined
)
422 kt
->cipher
= cipher_kt_get (translate_cipher_name_from_openvpn(ciphername
));
423 kt
->cipher_length
= cipher_kt_key_size (kt
->cipher
);
424 if (keysize
> 0 && keysize
<= MAX_CIPHER_KEY_LENGTH
)
425 kt
->cipher_length
= keysize
;
427 /* check legal cipher mode */
429 const unsigned int mode
= cipher_kt_mode (kt
->cipher
);
430 if (!(mode
== OPENVPN_MODE_CBC
431 #ifdef ALLOW_NON_CBC_CIPHERS
432 || (cfb_ofb_allowed
&& (mode
== OPENVPN_MODE_CFB
|| mode
== OPENVPN_MODE_OFB
))
436 msg (M_FATAL
, "Cipher '%s' mode not supported", ciphername
);
438 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
);
445 msg (M_WARN
, "******* WARNING *******: null cipher specified, no encryption will be used");
447 if (authname
&& authname_defined
)
449 kt
->digest
= md_kt_get (authname
);
450 kt
->hmac_length
= md_kt_size (kt
->digest
);
455 msg (M_WARN
, "******* WARNING *******: null MAC specified, no authentication will be used");
459 /* given a key and key_type, build a key_ctx */
461 init_key_ctx (struct key_ctx
*ctx
, struct key
*key
,
462 const struct key_type
*kt
, int enc
,
465 struct gc_arena gc
= gc_new ();
467 if (kt
->cipher
&& kt
->cipher_length
> 0)
470 ALLOC_OBJ(ctx
->cipher
, cipher_ctx_t
);
471 cipher_ctx_init (ctx
->cipher
, key
->cipher
, kt
->cipher_length
,
474 msg (D_HANDSHAKE
, "%s: Cipher '%s' initialized with %d bit key",
476 cipher_kt_name(kt
->cipher
),
477 kt
->cipher_length
*8);
479 dmsg (D_SHOW_KEYS
, "%s: CIPHER KEY: %s", prefix
,
480 format_hex (key
->cipher
, kt
->cipher_length
, 0, &gc
));
481 dmsg (D_CRYPTO_DEBUG
, "%s: CIPHER block_size=%d iv_size=%d",
483 cipher_kt_block_size(kt
->cipher
),
484 cipher_kt_iv_size(kt
->cipher
));
486 if (kt
->digest
&& kt
->hmac_length
> 0)
488 ALLOC_OBJ(ctx
->hmac
, hmac_ctx_t
);
489 hmac_ctx_init (ctx
->hmac
, key
->hmac
, kt
->hmac_length
, kt
->digest
);
492 "%s: Using %d bit message hash '%s' for HMAC authentication",
493 prefix
, md_kt_size(kt
->digest
) * 8, md_kt_name(kt
->digest
));
495 dmsg (D_SHOW_KEYS
, "%s: HMAC KEY: %s", prefix
,
496 format_hex (key
->hmac
, kt
->hmac_length
, 0, &gc
));
498 dmsg (D_CRYPTO_DEBUG
, "%s: HMAC size=%d block_size=%d",
500 md_kt_size(kt
->digest
),
501 hmac_ctx_size(ctx
->hmac
));
508 free_key_ctx (struct key_ctx
*ctx
)
512 cipher_ctx_cleanup(ctx
->cipher
);
518 hmac_ctx_cleanup(ctx
->hmac
);
525 free_key_ctx_bi (struct key_ctx_bi
*ctx
)
527 free_key_ctx(&ctx
->encrypt
);
528 free_key_ctx(&ctx
->decrypt
);
533 key_is_zero (struct key
*key
, const struct key_type
*kt
)
536 for (i
= 0; i
< kt
->cipher_length
; ++i
)
539 msg (D_CRYPT_ERRORS
, "CRYPTO INFO: WARNING: zero key detected");
544 * Make sure that cipher key is a valid key for current key_type.
547 check_key (struct key
*key
, const struct key_type
*kt
)
554 if (key_is_zero(key
, kt
))
558 * Check for weak or semi-weak DES keys.
561 const int ndc
= key_des_num_cblocks (kt
->cipher
);
563 return key_des_check (key
->cipher
, kt
->cipher_length
, ndc
);
572 * Make safe mutations to key to ensure it is valid,
573 * such as ensuring correct parity on DES keys.
575 * This routine cannot guarantee it will generate a good
576 * key. You must always call check_key after this routine
580 fixup_key (struct key
*key
, const struct key_type
*kt
)
582 struct gc_arena gc
= gc_new ();
586 const struct key orig
= *key
;
588 const int ndc
= key_des_num_cblocks (kt
->cipher
);
591 key_des_fixup (key
->cipher
, kt
->cipher_length
, ndc
);
594 if (check_debug_level (D_CRYPTO_DEBUG
))
596 if (memcmp (orig
.cipher
, key
->cipher
, kt
->cipher_length
))
597 dmsg (D_CRYPTO_DEBUG
, "CRYPTO INFO: fixup_key: before=%s after=%s",
598 format_hex (orig
.cipher
, kt
->cipher_length
, 0, &gc
),
599 format_hex (key
->cipher
, kt
->cipher_length
, 0, &gc
));
607 check_replay_iv_consistency (const struct key_type
*kt
, bool packet_id
, bool use_iv
)
609 if (cfb_ofb_mode (kt
) && !(packet_id
&& use_iv
))
610 msg (M_FATAL
, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
614 cfb_ofb_mode (const struct key_type
* kt
)
616 if (kt
&& kt
->cipher
) {
617 const unsigned int mode
= cipher_kt_mode (kt
->cipher
);
618 return mode
== OPENVPN_MODE_CFB
|| mode
== OPENVPN_MODE_OFB
;
624 * Generate a random key. If key_type is provided, make
625 * sure generated key is valid for key_type.
628 generate_key_random (struct key
*key
, const struct key_type
*kt
)
630 int cipher_len
= MAX_CIPHER_KEY_LENGTH
;
631 int hmac_len
= MAX_HMAC_KEY_LENGTH
;
633 struct gc_arena gc
= gc_new ();
639 if (kt
->cipher
&& kt
->cipher_length
> 0 && kt
->cipher_length
<= cipher_len
)
640 cipher_len
= kt
->cipher_length
;
642 if (kt
->digest
&& kt
->hmac_length
> 0 && kt
->hmac_length
<= hmac_len
)
643 hmac_len
= kt
->hmac_length
;
645 if (!rand_bytes (key
->cipher
, cipher_len
)
646 || !rand_bytes (key
->hmac
, hmac_len
))
647 msg (M_FATAL
, "ERROR: Random number generator cannot obtain entropy for key generation");
649 dmsg (D_SHOW_KEY_SOURCE
, "Cipher source entropy: %s", format_hex (key
->cipher
, cipher_len
, 0, &gc
));
650 dmsg (D_SHOW_KEY_SOURCE
, "HMAC source entropy: %s", format_hex (key
->hmac
, hmac_len
, 0, &gc
));
654 } while (kt
&& !check_key (key
, kt
));
663 key2_print (const struct key2
* k
,
664 const struct key_type
*kt
,
668 struct gc_arena gc
= gc_new ();
670 dmsg (D_SHOW_KEY_SOURCE
, "%s (cipher): %s",
672 format_hex (k
->keys
[0].cipher
, kt
->cipher_length
, 0, &gc
));
673 dmsg (D_SHOW_KEY_SOURCE
, "%s (hmac): %s",
675 format_hex (k
->keys
[0].hmac
, kt
->hmac_length
, 0, &gc
));
676 dmsg (D_SHOW_KEY_SOURCE
, "%s (cipher): %s",
678 format_hex (k
->keys
[1].cipher
, kt
->cipher_length
, 0, &gc
));
679 dmsg (D_SHOW_KEY_SOURCE
, "%s (hmac): %s",
681 format_hex (k
->keys
[1].hmac
, kt
->hmac_length
, 0, &gc
));
686 test_crypto (const struct crypto_options
*co
, struct frame
* frame
)
689 struct gc_arena gc
= gc_new ();
690 struct buffer src
= alloc_buf_gc (TUN_MTU_SIZE (frame
), &gc
);
691 struct buffer work
= alloc_buf_gc (BUF_SIZE (frame
), &gc
);
692 struct buffer encrypt_workspace
= alloc_buf_gc (BUF_SIZE (frame
), &gc
);
693 struct buffer decrypt_workspace
= alloc_buf_gc (BUF_SIZE (frame
), &gc
);
694 struct buffer buf
= clear_buf();
697 ASSERT (buf_init (&work
, FRAME_HEADROOM (frame
)));
699 msg (M_INFO
, "Entering " PACKAGE_NAME
" crypto self-test mode.");
700 for (i
= 1; i
<= TUN_MTU_SIZE (frame
); ++i
)
704 msg (M_INFO
, "TESTING ENCRYPT/DECRYPT of packet length=%d", i
);
707 * Load src with random data.
709 ASSERT (buf_init (&src
, 0));
710 ASSERT (i
<= src
.capacity
);
712 ASSERT (rand_bytes (BPTR (&src
), BLEN (&src
)));
714 /* copy source to input buf */
716 memcpy (buf_write_alloc (&buf
, BLEN (&src
)), BPTR (&src
), BLEN (&src
));
719 openvpn_encrypt (&buf
, encrypt_workspace
, co
, frame
);
722 openvpn_decrypt (&buf
, decrypt_workspace
, co
, frame
);
725 if (buf
.len
!= src
.len
)
726 msg (M_FATAL
, "SELF TEST FAILED, src.len=%d buf.len=%d", src
.len
, buf
.len
);
727 for (j
= 0; j
< i
; ++j
)
729 const uint8_t in
= *(BPTR (&src
) + j
);
730 const uint8_t out
= *(BPTR (&buf
) + j
);
732 msg (M_FATAL
, "SELF TEST FAILED, pos=%d in=%d out=%d", j
, in
, out
);
735 msg (M_INFO
, PACKAGE_NAME
" crypto self-test mode SUCCEEDED.");
742 get_tls_handshake_key (const struct key_type
*key_type
,
743 struct key_ctx_bi
*ctx
,
744 const char *passphrase_file
,
745 const int key_direction
,
746 const unsigned int flags
)
748 if (passphrase_file
&& key_type
->hmac_length
)
751 struct key_type kt
= *key_type
;
752 struct key_direction_state kds
;
754 /* for control channel we are only authenticating, not encrypting */
755 kt
.cipher_length
= 0;
758 if (flags
& GHK_INLINE
)
760 /* key was specified inline, key text is in passphrase_file */
761 read_key_file (&key2
, passphrase_file
, RKF_INLINE
|RKF_MUST_SUCCEED
);
765 msg (M_INFO
, "Control Channel Authentication: tls-auth using INLINE static key file");
767 msg (M_FATAL
, "INLINE tls-auth file lacks the requisite 2 keys");
771 /* first try to parse as an OpenVPN static key file */
772 read_key_file (&key2
, passphrase_file
, 0);
778 "Control Channel Authentication: using '%s' as a " PACKAGE_NAME
" static key file",
787 /* failed, now try to get hash from a freeform file */
788 hash_size
= read_passphrase_hash (passphrase_file
,
791 MAX_HMAC_KEY_LENGTH
);
792 ASSERT (hash_size
== kt
.hmac_length
);
798 "Control Channel Authentication: using '%s' as a free-form passphrase file",
802 /* handle key direction */
804 key_direction_state_init (&kds
, key_direction
);
805 must_have_n_keys (passphrase_file
, "tls-auth", &key2
, kds
.need_keys
);
807 /* initialize hmac key in both directions */
809 init_key_ctx (&ctx
->encrypt
, &key2
.keys
[kds
.out_key
], &kt
, OPENVPN_OP_ENCRYPT
,
810 "Outgoing Control Channel Authentication");
811 init_key_ctx (&ctx
->decrypt
, &key2
.keys
[kds
.in_key
], &kt
, OPENVPN_OP_DECRYPT
,
812 "Incoming Control Channel Authentication");
823 /* header and footer for static key file */
824 static const char static_key_head
[] = "-----BEGIN OpenVPN Static key V1-----";
825 static const char static_key_foot
[] = "-----END OpenVPN Static key V1-----";
827 static const char printable_char_fmt
[] =
828 "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
830 static const char unprintable_char_fmt
[] =
831 "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
833 /* read key from file */
836 read_key_file (struct key2
*key2
, const char *file
, const unsigned int flags
)
838 struct gc_arena gc
= gc_new ();
841 uint8_t hex_byte
[3] = {0, 0, 0};
842 const char *error_filename
= file
;
845 const unsigned char *cp
;
852 uint8_t* out
= (uint8_t*) &key2
->keys
;
853 const int keylen
= sizeof (key2
->keys
);
857 # define PARSE_INITIAL 0
858 # define PARSE_HEAD 1
859 # define PARSE_DATA 2
860 # define PARSE_DATA_COMPLETE 3
861 # define PARSE_FOOT 4
862 # define PARSE_FINISHED 5
863 int state
= PARSE_INITIAL
;
866 const int hlen
= strlen (static_key_head
);
867 const int flen
= strlen (static_key_foot
);
868 const int onekeylen
= sizeof (key2
->keys
[0]);
873 * Key can be provided as a filename in 'file' or if RKF_INLINE
874 * is set, the actual key data itself in ascii form.
876 if (flags
& RKF_INLINE
) /* 'file' is a string containing ascii representation of key */
878 size
= strlen (file
) + 1;
879 buf_set_read (&in
, (const uint8_t *)file
, size
);
880 error_filename
= INLINE_FILE_TAG
;
882 else /* 'file' is a filename which refers to a file containing the ascii key */
884 in
= alloc_buf_gc (2048, &gc
);
885 fd
= platform_open (file
, O_RDONLY
, 0);
887 msg (M_ERR
, "Cannot open file key file '%s'", file
);
888 size
= read (fd
, in
.data
, in
.capacity
);
890 msg (M_FATAL
, "Read error on key file ('%s')", file
);
891 if (size
== in
.capacity
)
892 msg (M_FATAL
, "Key file ('%s') can be a maximum of %d bytes", file
, (int)in
.capacity
);
896 cp
= (unsigned char *)in
.data
;
899 const unsigned char c
= *cp
;
902 msg (M_INFO
, "char='%c'[%d] s=%d ln=%d li=%d m=%d c=%d",
903 c
, (int)c
, state
, line_num
, line_index
, match
, count
);
908 line_index
= match
= 0;
913 /* first char of new line */
916 /* first char of line after header line? */
917 if (state
== PARSE_HEAD
)
920 /* first char of footer */
921 if ((state
== PARSE_DATA
|| state
== PARSE_DATA_COMPLETE
) && c
== '-')
925 /* compare read chars with header line */
926 if (state
== PARSE_INITIAL
)
928 if (line_index
< hlen
&& c
== static_key_head
[line_index
])
935 /* compare read chars with footer line */
936 if (state
== PARSE_FOOT
)
938 if (line_index
< flen
&& c
== static_key_foot
[line_index
])
941 state
= PARSE_FINISHED
;
946 if (state
== PARSE_DATA
)
950 ASSERT (hb_index
>= 0 && hb_index
< 2);
951 hex_byte
[hb_index
++] = c
;
955 ASSERT(sscanf((const char *)hex_byte
, "%x", &u
) == 1);
958 if (++count
== keylen
)
959 state
= PARSE_DATA_COMPLETE
;
967 (isprint (c
) ? printable_char_fmt
: unprintable_char_fmt
),
968 c
, line_num
, error_filename
, count
, onekeylen
, keylen
);
978 * Normally we will read either 1 or 2 keys from file.
980 key2
->n
= count
/ onekeylen
;
982 ASSERT (key2
->n
>= 0 && key2
->n
<= (int) SIZE (key2
->keys
));
984 if (flags
& RKF_MUST_SUCCEED
)
987 msg (M_FATAL
, "Insufficient key material or header text not found in file '%s' (%d/%d/%d bytes found/min/max)",
988 error_filename
, count
, onekeylen
, keylen
);
990 if (state
!= PARSE_FINISHED
)
991 msg (M_FATAL
, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
992 error_filename
, count
, onekeylen
, keylen
);
995 /* zero file read buffer if not an inline file */
996 if (!(flags
& RKF_INLINE
))
1000 warn_if_group_others_accessible (error_filename
);
1006 printf ("KEY READ, n=%d\n", key2
->n
);
1007 for (i
= 0; i
< (int) SIZE (key2
->keys
); ++i
)
1009 /* format key as ascii */
1010 const char *fmt
= format_hex_ex ((const uint8_t*)&key2
->keys
[i
],
1011 sizeof (key2
->keys
[i
]),
1016 printf ("[%d]\n%s\n\n", i
, fmt
);
1021 /* pop our garbage collection level */
1026 read_passphrase_hash (const char *passphrase_file
,
1027 const md_kt_t
*digest
,
1031 unsigned int outlen
= 0;
1034 ASSERT (len
>= md_kt_size(digest
));
1035 memset (output
, 0, len
);
1037 md_ctx_init(&md
, digest
);
1039 /* read passphrase file */
1041 const int min_passphrase_size
= 8;
1044 int fd
= platform_open (passphrase_file
, O_RDONLY
, 0);
1047 msg (M_ERR
, "Cannot open passphrase file: '%s'", passphrase_file
);
1051 int size
= read (fd
, buf
, sizeof (buf
));
1055 msg (M_ERR
, "Read error on passphrase file: '%s'",
1057 md_ctx_update(&md
, buf
, size
);
1062 warn_if_group_others_accessible (passphrase_file
);
1064 if (total_size
< min_passphrase_size
)
1066 "Passphrase file '%s' is too small (must have at least %d characters)",
1067 passphrase_file
, min_passphrase_size
);
1069 md_ctx_final(&md
, output
);
1070 md_ctx_cleanup(&md
);
1071 return md_kt_size(digest
);
1075 * Write key to file, return number of random bits
1079 write_key_file (const int nkeys
, const char *filename
)
1081 struct gc_arena gc
= gc_new ();
1086 /* must be large enough to hold full key file */
1087 struct buffer out
= alloc_buf_gc (2048, &gc
);
1088 struct buffer nbits_head_text
= alloc_buf_gc (128, &gc
);
1090 /* how to format the ascii file representation of key */
1091 const int bytes_per_line
= 16;
1094 fd
= platform_open (filename
, O_CREAT
| O_TRUNC
| O_WRONLY
, S_IRUSR
| S_IWUSR
);
1097 msg (M_ERR
, "Cannot open shared secret file '%s' for write", filename
);
1099 buf_printf (&out
, "%s\n", static_key_head
);
1101 for (i
= 0; i
< nkeys
; ++i
)
1106 /* generate random bits */
1107 generate_key_random (&key
, NULL
);
1109 /* format key as ascii */
1110 fmt
= format_hex_ex ((const uint8_t*)&key
,
1117 /* increment random bits counter */
1118 nbits
+= sizeof (key
) * 8;
1120 /* write to holding buffer */
1121 buf_printf (&out
, "%s\n", fmt
);
1123 /* zero memory which held key component (will be freed by GC) */
1124 memset (fmt
, 0, strlen(fmt
));
1128 buf_printf (&out
, "%s\n", static_key_foot
);
1130 /* write number of bits */
1131 buf_printf (&nbits_head_text
, "#\n# %d bit OpenVPN static key\n#\n", nbits
);
1132 buf_write_string_file (&nbits_head_text
, filename
, fd
);
1134 /* write key file, now formatted in out, to file */
1135 buf_write_string_file (&out
, filename
, fd
);
1138 msg (M_ERR
, "Close error on shared secret file %s", filename
);
1140 /* zero memory which held file content (memory will be freed by GC) */
1143 /* pop our garbage collection level */
1150 must_have_n_keys (const char *filename
, const char *option
, const struct key2
*key2
, int n
)
1155 msg (M_FATAL
, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename
, option
, key2
->n
, n
);
1157 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
);
1163 ascii2keydirection (int msglevel
, const char *str
)
1166 return KEY_DIRECTION_BIDIRECTIONAL
;
1167 else if (!strcmp (str
, "0"))
1168 return KEY_DIRECTION_NORMAL
;
1169 else if (!strcmp (str
, "1"))
1170 return KEY_DIRECTION_INVERSE
;
1173 msg (msglevel
, "Unknown key direction '%s' -- must be '0' or '1'", str
);
1176 return KEY_DIRECTION_BIDIRECTIONAL
; /* NOTREACHED */
1180 keydirection2ascii (int kd
, bool remote
)
1182 if (kd
== KEY_DIRECTION_BIDIRECTIONAL
)
1184 else if (kd
== KEY_DIRECTION_NORMAL
)
1185 return remote
? "1" : "0";
1186 else if (kd
== KEY_DIRECTION_INVERSE
)
1187 return remote
? "0" : "1";
1192 return NULL
; /* NOTREACHED */
1196 key_direction_state_init (struct key_direction_state
*kds
, int key_direction
)
1199 switch (key_direction
)
1201 case KEY_DIRECTION_NORMAL
:
1206 case KEY_DIRECTION_INVERSE
:
1211 case KEY_DIRECTION_BIDIRECTIONAL
:
1222 verify_fix_key2 (struct key2
*key2
, const struct key_type
*kt
, const char *shared_secret_file
)
1226 for (i
= 0; i
< key2
->n
; ++i
)
1228 /* Fix parity for DES keys and make sure not a weak key */
1229 fixup_key (&key2
->keys
[i
], kt
);
1231 /* This should be a very improbable failure */
1232 if (!check_key (&key2
->keys
[i
], kt
))
1233 msg (M_FATAL
, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
1234 i
+1, shared_secret_file
);
1238 /* given a key and key_type, write key to buffer */
1240 write_key (const struct key
*key
, const struct key_type
*kt
,
1243 ASSERT (kt
->cipher_length
<= MAX_CIPHER_KEY_LENGTH
1244 && kt
->hmac_length
<= MAX_HMAC_KEY_LENGTH
);
1246 if (!buf_write (buf
, &kt
->cipher_length
, 1))
1248 if (!buf_write (buf
, &kt
->hmac_length
, 1))
1250 if (!buf_write (buf
, key
->cipher
, kt
->cipher_length
))
1252 if (!buf_write (buf
, key
->hmac
, kt
->hmac_length
))
1259 * Given a key_type and buffer, read key from buffer.
1260 * Return: 1 on success
1262 * 0 on key length mismatch
1265 read_key (struct key
*key
, const struct key_type
*kt
, struct buffer
*buf
)
1267 uint8_t cipher_length
;
1268 uint8_t hmac_length
;
1271 if (!buf_read (buf
, &cipher_length
, 1))
1273 if (!buf_read (buf
, &hmac_length
, 1))
1276 if (!buf_read (buf
, key
->cipher
, cipher_length
))
1278 if (!buf_read (buf
, key
->hmac
, hmac_length
))
1281 if (cipher_length
!= kt
->cipher_length
|| hmac_length
!= kt
->hmac_length
)
1287 msg (D_TLS_ERRORS
, "TLS Error: error reading key from remote");
1292 "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1293 kt
->cipher_length
, kt
->hmac_length
, cipher_length
, hmac_length
);
1298 * Random number functions, used in cases where we want
1299 * reasonably strong cryptographic random number generation
1300 * without depleting our entropy pool. Used for random
1301 * IV values and a number of other miscellaneous tasks.
1304 static uint8_t *nonce_data
= NULL
; /* GLOBAL */
1305 static const md_kt_t
*nonce_md
= NULL
; /* GLOBAL */
1306 static int nonce_secret_len
= 0; /* GLOBAL */
1308 /* Reset the nonce value, also done periodically to refresh entropy */
1312 const int size
= md_kt_size (nonce_md
) + nonce_secret_len
;
1313 #if 1 /* Must be 1 for real usage */
1314 if (!rand_bytes (nonce_data
, size
))
1315 msg (M_FATAL
, "ERROR: Random number generator cannot obtain entropy for PRNG");
1317 /* Only for testing -- will cause a predictable PRNG sequence */
1320 for (i
= 0; i
< size
; ++i
)
1321 nonce_data
[i
] = (uint8_t) i
;
1327 prng_init (const char *md_name
, const int nonce_secret_len_parm
)
1330 nonce_md
= md_name
? md_kt_get (md_name
) : NULL
;
1333 ASSERT (nonce_secret_len_parm
>= NONCE_SECRET_LEN_MIN
&& nonce_secret_len_parm
<= NONCE_SECRET_LEN_MAX
);
1334 nonce_secret_len
= nonce_secret_len_parm
;
1336 const int size
= md_kt_size(nonce_md
) + nonce_secret_len
;
1337 dmsg (D_CRYPTO_DEBUG
, "PRNG init md=%s size=%d", md_kt_name(nonce_md
), size
);
1338 nonce_data
= (uint8_t*) malloc (size
);
1339 check_malloc_return (nonce_data
);
1351 nonce_secret_len
= 0;
1355 prng_bytes (uint8_t *output
, int len
)
1357 static size_t processed
= 0;
1361 const int md_size
= md_kt_size (nonce_md
);
1364 unsigned int outlen
= 0;
1365 const int blen
= min_int (len
, md_size
);
1366 md_full(nonce_md
, nonce_data
, md_size
+ nonce_secret_len
, nonce_data
);
1367 memcpy (output
, nonce_data
, blen
);
1371 /* Ensure that random data is reset regularly */
1373 if(processed
> PRNG_NONCE_RESET_BYTES
) {
1380 rand_bytes (output
, len
);
1383 /* an analogue to the random() function, but use prng_bytes */
1388 prng_bytes ((unsigned char *)&l
, sizeof(l
));
1405 crypto_uninit_lib ();
1409 #endif /* ENABLE_SSL */
1416 md5sum (uint8_t *buf
, int len
, int n_print_chars
, struct gc_arena
*gc
)
1418 uint8_t digest
[MD5_DIGEST_LENGTH
];
1419 const md_kt_t
*md5_kt
= md_kt_get("MD5");
1421 md_full(md5_kt
, buf
, len
, digest
);
1423 return format_hex (digest
, MD5_DIGEST_LENGTH
, n_print_chars
, gc
);
1427 md5_state_init (struct md5_state
*s
)
1429 const md_kt_t
*md5_kt
= md_kt_get("MD5");
1431 md_ctx_init(&s
->ctx
, md5_kt
);
1435 md5_state_update (struct md5_state
*s
, void *data
, size_t len
)
1437 md_ctx_update(&s
->ctx
, data
, len
);
1441 md5_state_final (struct md5_state
*s
, struct md5_digest
*out
)
1443 md_ctx_final(&s
->ctx
, out
->digest
);
1444 md_ctx_cleanup(&s
->ctx
);
1448 md5_digest_clear (struct md5_digest
*digest
)
1454 md5_digest_defined (const struct md5_digest
*digest
)
1457 for (i
= 0; i
< MD5_DIGEST_LENGTH
; ++i
)
1458 if (digest
->digest
[i
])
1464 md5_digest_equal (const struct md5_digest
*d1
, const struct md5_digest
*d2
)
1466 return memcmp(d1
->digest
, d2
->digest
, MD5_DIGEST_LENGTH
) == 0;
1469 #endif /* ENABLE_CRYPTO */