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-2004 James Yonan <jim@yonan.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 as published by
12
* the Free Software Foundation; either version 2 of the License, or
13
* (at your option) any later version.
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
27
#include "config-win32.h"
44
* Check for key size creepage.
47
#if MAX_CIPHER_KEY_LENGTH < EVP_MAX_KEY_LENGTH
48
#warning Some OpenSSL EVP ciphers now support key lengths greater than MAX_CIPHER_KEY_LENGTH -- consider increasing MAX_CIPHER_KEY_LENGTH
51
#if MAX_HMAC_KEY_LENGTH < EVP_MAX_MD_SIZE
52
#warning Some OpenSSL HMAC message digests now support key lengths greater than MAX_HMAC_KEY_LENGTH -- consider increasing MAX_HMAC_KEY_LENGTH
56
* Encryption and Compression Routines.
58
* On entry, buf contains the input data and length.
59
* On exit, it should be set to the output data and length.
61
* If buf->len is <= 0 we should return
62
* If buf->len is set to 0 on exit it tells the caller to ignore the packet.
64
* work is a workspace buffer we are given of size BUF_SIZE.
65
* work may be used to return output data, or the input buffer
66
* may be modified and returned as output. If output data is
67
* returned in work, the data should start after FRAME_HEADROOM bytes
68
* of padding to leave room for downstream routines to prepend.
70
* Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
71
* by all routines (encryption, decryption, compression, and decompression).
73
* Note that the buf_prepend return will assert if we try to
74
* make a header bigger than FRAME_HEADROOM. This should not
75
* happen unless the frame parameters are wrong.
78
#define CRYPT_ERROR(format) \
79
do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
82
openvpn_encrypt (struct buffer *buf, struct buffer work,
83
const struct crypto_options *opt,
84
const struct frame* frame,
87
if (buf->len > 0 && opt->key_ctx_bi)
89
struct key_ctx *ctx = &opt->key_ctx_bi->encrypt;
91
/* Do Encrypt from buf -> work */
94
uint8_t iv_buf[EVP_MAX_IV_LENGTH];
95
const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
96
const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);
99
if (mode == EVP_CIPH_CBC_MODE)
103
/* generate pseudo-random IV */
105
prng_bytes (iv_buf, iv_size);
107
/* Put packet ID in plaintext buffer or IV, depending on cipher mode */
110
struct packet_id_net pin;
111
packet_id_alloc_outgoing (&opt->packet_id->send, &pin, opt->packet_id_long_form);
112
ASSERT (packet_id_write (&pin, buf, opt->packet_id_long_form, true));
115
else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
117
struct packet_id_net pin;
120
ASSERT (opt->use_iv); /* IV and packet-ID required */
121
ASSERT (opt->packet_id); /* for this mode. */
123
packet_id_alloc_outgoing (&opt->packet_id->send, &pin, true);
124
memset (iv_buf, 0, iv_size);
125
buf_set_write (&b, iv_buf, iv_size);
126
ASSERT (packet_id_write (&pin, &b, true, false));
128
else /* We only support CBC, CFB, or OFB modes right now */
133
/* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
134
ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
136
/* set the IV pseudo-randomly */
138
msg (D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex (iv_buf, iv_size, 0));
140
msg (D_PACKET_CONTENT, "ENCRYPT FROM: %s",
141
format_hex (BPTR (buf), BLEN (buf), 80));
143
/* cipher_ctx was already initialized with key & keylen */
144
ASSERT (EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_ENCRYPT));
146
/* Buffer overflow check (should never happen) */
147
ASSERT (buf_safe (&work, buf->len + EVP_CIPHER_CTX_block_size (ctx->cipher)));
149
/* Encrypt packet ID, payload */
150
ASSERT (EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
153
/* Flush the encryption buffer */
154
ASSERT (EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen));
156
ASSERT (outlen == iv_size);
158
/* prepend the IV to the ciphertext */
161
uint8_t *output = buf_prepend (&work, iv_size);
163
memcpy (output, iv_buf, iv_size);
166
msg (D_PACKET_CONTENT, "ENCRYPT TO: %s",
167
format_hex (BPTR (&work), BLEN (&work), 80));
169
else /* No Encryption */
173
struct packet_id_net pin;
174
packet_id_alloc_outgoing (&opt->packet_id->send, &pin, opt->packet_id_long_form);
175
ASSERT (packet_id_write (&pin, buf, opt->packet_id_long_form, true));
180
/* HMAC the ciphertext (or plaintext if !cipher) */
186
HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
187
HMAC_Update (ctx->hmac, BPTR (&work), BLEN (&work));
188
output = buf_prepend (&work, HMAC_size (ctx->hmac));
190
HMAC_Final (ctx->hmac, output, (unsigned int *)&hmac_len);
191
ASSERT (hmac_len == HMAC_size (ctx->hmac));
200
* If opt->use_iv is not NULL, we will read an IV from the packet.
202
* Set buf->len to 0 and return false on decrypt error.
204
* On success, buf is set to point to plaintext, true
208
openvpn_decrypt (struct buffer *buf, struct buffer work,
209
const struct crypto_options *opt,
210
const struct frame* frame,
211
const time_t current)
213
static const char error_prefix[] = "Authenticate/Decrypt packet error";
215
if (buf->len > 0 && opt->key_ctx_bi)
217
struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
218
struct packet_id_net pin;
219
bool have_pin = false;
221
/* Verify the HMAC */
225
uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
228
HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
230
/* Assume the length of the input HMAC */
231
hmac_len = HMAC_size (ctx->hmac);
233
/* Authentication fails if insufficient data in packet for HMAC */
234
if (buf->len < hmac_len)
235
CRYPT_ERROR ("missing authentication info");
237
HMAC_Update (ctx->hmac, BPTR (buf) + hmac_len,
238
BLEN (buf) - hmac_len);
239
HMAC_Final (ctx->hmac, local_hmac, (unsigned int *)&in_hmac_len);
240
ASSERT (hmac_len == in_hmac_len);
242
/* Compare locally computed HMAC with packet HMAC */
243
if (memcmp (local_hmac, BPTR (buf), hmac_len))
244
CRYPT_ERROR ("packet HMAC authentication failed");
246
ASSERT (buf_advance (buf, hmac_len));
249
/* Decrypt packet ID + payload */
253
const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);
254
const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
255
uint8_t iv_buf[EVP_MAX_IV_LENGTH];
258
/* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
259
ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
261
/* use IV if user requested it */
265
if (buf->len < iv_size)
266
CRYPT_ERROR ("missing IV info");
267
memcpy (iv_buf, BPTR (buf), iv_size);
268
ASSERT (buf_advance (buf, iv_size));
271
/* show the IV's initial state */
273
msg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0));
276
CRYPT_ERROR ("missing payload");
278
/* ctx->cipher was already initialized with key & keylen */
279
if (!EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_DECRYPT))
280
CRYPT_ERROR ("cipher init failed");
282
/* Buffer overflow check (should never happen) */
283
if (!buf_safe (&work, buf->len))
284
CRYPT_ERROR ("buffer overflow");
286
/* Decrypt packet ID, payload */
287
if (!EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)))
288
CRYPT_ERROR ("cipher update failed");
291
/* Flush the decryption buffer */
292
if (!EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen))
293
CRYPT_ERROR ("cipher final failed");
296
msg (D_PACKET_CONTENT, "DECRYPT TO: %s",
297
format_hex (BPTR (&work), BLEN (&work), 80));
299
/* Get packet ID from plaintext buffer or IV, depending on cipher mode */
301
if (mode == EVP_CIPH_CBC_MODE)
305
if (!packet_id_read (&pin, &work, opt->packet_id_long_form))
306
CRYPT_ERROR ("error reading CBC packet-id");
310
else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
314
ASSERT (opt->use_iv); /* IV and packet-ID required */
315
ASSERT (opt->packet_id); /* for this mode. */
317
buf_set_read (&b, iv_buf, iv_size);
318
if (!packet_id_read (&pin, &b, true))
319
CRYPT_ERROR ("error reading CFB/OFB packet-id");
322
else /* We only support CBC, CFB, or OFB modes right now */
333
if (!packet_id_read (&pin, &work, opt->packet_id_long_form))
334
CRYPT_ERROR ("error reading packet-id");
341
packet_id_reap_test (&opt->packet_id->rec, current);
342
if (packet_id_test (&opt->packet_id->rec, &pin))
344
packet_id_add (&opt->packet_id->rec, &pin, current);
345
if (opt->pid_persist && opt->packet_id_long_form)
346
packet_id_persist_save_obj (opt->pid_persist, opt->packet_id);
350
msg (D_CRYPT_ERRORS, "%s: bad packet ID (may be a replay): %s -- see the man page entry for --no-replay and --replay-window for more info",
351
error_prefix, packet_id_net_print (&pin, true));
365
* How many bytes will we add to frame buffer for a given
366
* set of crypto options?
369
crypto_adjust_frame_parameters(struct frame *frame,
370
const struct key_type* kt,
374
bool packet_id_long_form)
376
frame_add_to_extra_frame (frame,
377
(packet_id ? packet_id_size (packet_id_long_form) : 0) +
378
((cipher_defined && use_iv) ? EVP_CIPHER_iv_length (kt->cipher) : 0) +
379
(cipher_defined ? EVP_CIPHER_block_size (kt->cipher) : 0) + /* worst case padding expansion */
383
static const EVP_CIPHER *
384
get_cipher (const char *ciphername)
386
const EVP_CIPHER *cipher = NULL;
388
cipher = EVP_get_cipherbyname (ciphername);
389
if ( !(cipher && cipher_ok (OBJ_nid2sn (EVP_CIPHER_nid (cipher)))))
390
msg (M_SSLERR, "Cipher algorithm '%s' not found", ciphername);
391
if (EVP_CIPHER_key_length (cipher) > MAX_CIPHER_KEY_LENGTH)
392
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)",
394
EVP_CIPHER_key_length (cipher),
395
MAX_CIPHER_KEY_LENGTH);
399
static const EVP_MD *
400
get_md (const char *digest)
402
const EVP_MD *md = NULL;
404
md = EVP_get_digestbyname (digest);
406
msg (M_SSLERR, "Message hash algorithm '%s' not found", digest);
407
if (EVP_MD_size (md) > MAX_HMAC_KEY_LENGTH)
408
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)",
411
MAX_HMAC_KEY_LENGTH);
416
init_cipher (EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
417
struct key *key, const struct key_type *kt, int enc,
420
EVP_CIPHER_CTX_init (ctx);
421
if (!EVP_CipherInit_ov (ctx, cipher, NULL, NULL, enc))
422
msg (M_SSLERR, "EVP cipher init #1");
423
#ifdef HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH
424
if (!EVP_CIPHER_CTX_set_key_length (ctx, kt->cipher_length))
425
msg (M_SSLERR, "EVP set key size");
427
if (!EVP_CipherInit_ov (ctx, NULL, key->cipher, NULL, enc))
428
msg (M_SSLERR, "EVP cipher init #2");
430
msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
432
OBJ_nid2sn (EVP_CIPHER_CTX_nid (ctx)),
433
EVP_CIPHER_CTX_key_length (ctx) * 8);
435
/* make sure we used a big enough key */
436
ASSERT (EVP_CIPHER_CTX_key_length (ctx) <= kt->cipher_length);
438
msg (D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
439
format_hex (key->cipher, kt->cipher_length, 0));
440
msg (D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d",
442
EVP_CIPHER_CTX_block_size (ctx),
443
EVP_CIPHER_CTX_iv_length (ctx));
447
init_hmac (HMAC_CTX *ctx, const EVP_MD *digest,
448
struct key *key, const struct key_type *kt, const char *prefix)
451
HMAC_Init_ex (ctx, key->hmac, kt->hmac_length, digest, NULL);
453
"%s: Using %d bit message hash '%s' for HMAC authentication",
454
prefix, HMAC_size (ctx) * 8, OBJ_nid2sn (EVP_MD_type (digest)));
456
/* make sure we used a big enough key */
457
ASSERT (HMAC_size (ctx) <= kt->hmac_length);
459
msg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
460
format_hex (key->hmac, kt->hmac_length, 0));
461
msg (D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d",
463
EVP_MD_size (digest),
464
EVP_MD_block_size (digest));
467
/* build a key_type */
469
init_key_type (struct key_type *kt, const char *ciphername,
470
bool ciphername_defined, const char *authname,
471
bool authname_defined, int keysize,
472
bool cfb_ofb_allowed, bool warn)
475
if (ciphername && ciphername_defined)
477
kt->cipher = get_cipher (ciphername);
478
kt->cipher_length = EVP_CIPHER_key_length (kt->cipher);
479
if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH)
480
kt->cipher_length = keysize;
482
/* check legal cipher mode */
484
const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
485
if (!(mode == EVP_CIPH_CBC_MODE
486
#ifdef ALLOW_NON_CBC_CIPHERS
487
|| (cfb_ofb_allowed && (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE))
490
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);
496
msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used");
498
if (authname && authname_defined)
500
kt->digest = get_md (authname);
501
kt->hmac_length = EVP_MD_size (kt->digest);
506
msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
511
kt_cipher_name (const struct key_type *kt)
514
return EVP_CIPHER_name (kt->cipher);
516
return "[null-cipher]";
520
kt_digest_name (const struct key_type *kt)
523
return EVP_MD_name (kt->digest);
525
return "[null-digest]";
529
kt_key_size (const struct key_type *kt)
531
if (kt->cipher_length)
532
return kt->cipher_length * 8;
534
return EVP_CIPHER_key_length (kt->cipher) * 8;
539
/* given a key and key_type, build a key_ctx */
541
init_key_ctx (struct key_ctx *ctx, struct key *key,
542
const struct key_type *kt, int enc,
546
if (kt->cipher && kt->cipher_length > 0)
548
ASSERT (ctx->cipher = (EVP_CIPHER_CTX *) malloc (sizeof (EVP_CIPHER_CTX)));
549
init_cipher (ctx->cipher, kt->cipher, key, kt, enc, prefix);
551
if (kt->digest && kt->hmac_length > 0)
553
ASSERT (ctx->hmac = (HMAC_CTX *) malloc (sizeof (HMAC_CTX)));
554
init_hmac (ctx->hmac, kt->digest, key, kt, prefix);
558
void free_key_ctx (struct key_ctx *ctx)
562
EVP_CIPHER_CTX_cleanup (ctx->cipher);
568
HMAC_CTX_cleanup (ctx->hmac);
574
void free_key_ctx_bi (struct key_ctx_bi *ctx)
576
free_key_ctx(&ctx->encrypt);
577
free_key_ctx(&ctx->decrypt);
581
* Return number of DES cblocks for the current
582
* key type or 0 if not a DES cipher.
585
n_DES_cblocks (const struct key_type *kt)
588
const char *name = OBJ_nid2sn (EVP_CIPHER_nid (kt->cipher));
591
if (!strncmp (name, "DES-", 4))
593
ret = EVP_CIPHER_key_length (kt->cipher) / sizeof (DES_cblock);
595
else if (!strncmp (name, "DESX-", 5))
600
msg (D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret);
605
check_key_DES (struct key *key, const struct key_type *kt, int ndc)
610
buf_set_read (&b, key->cipher, kt->cipher_length);
611
for (i = 0; i < ndc; ++i)
613
DES_cblock *dc = (DES_cblock*) buf_read_alloc (&b, sizeof (DES_cblock));
616
msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: insufficient key material");
619
if (DES_is_weak_key(dc))
621
msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: weak key detected");
624
if (!DES_check_key_parity (dc))
626
msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: bad parity detected");
634
fixup_key_DES (struct key *key, const struct key_type *kt, int ndc)
639
buf_set_read (&b, key->cipher, kt->cipher_length);
640
for (i = 0; i < ndc; ++i)
642
DES_cblock *dc = (DES_cblock*) buf_read_alloc(&b, sizeof(DES_cblock));
645
msg (D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material");
648
DES_set_odd_parity (dc);
653
key_is_zero(struct key *key, const struct key_type *kt)
656
for (i = 0; i < kt->cipher_length; ++i)
659
msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
664
* Make sure that cipher key is a valid key for current key_type.
667
check_key (struct key *key, const struct key_type *kt)
674
if (key_is_zero(key, kt))
678
* Check for weak or semi-weak DES keys.
681
const int ndc = n_DES_cblocks (kt);
683
return check_key_DES (key, kt, ndc);
692
* Make safe mutations to key to ensure it is valid,
693
* such as ensuring correct parity on DES keys.
695
* This routine cannot guarantee it will generate a good
696
* key. You must always call check_key after this routine
700
fixup_key (struct key *key, const struct key_type *kt)
704
const struct key orig = *key;
705
const int ndc = n_DES_cblocks (kt);
708
fixup_key_DES (key, kt, ndc);
710
if (check_debug_level (D_CRYPTO_DEBUG))
712
if (memcmp (orig.cipher, key->cipher, kt->cipher_length))
713
msg (D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s",
714
format_hex (orig.cipher, kt->cipher_length, 0),
715
format_hex (key->cipher, kt->cipher_length, 0));
721
check_replay_iv_consistency(const struct key_type *kt, bool packet_id, bool use_iv)
723
if (cfb_ofb_mode (kt) && !(packet_id && use_iv))
724
msg (M_FATAL, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
728
cfb_ofb_mode(const struct key_type* kt)
731
const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
732
return mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE;
738
* Generate a random key. If key_type is provided, make
739
* sure generated key is valid for key_type.
742
generate_key_random (struct key *key, const struct key_type *kt)
744
int cipher_len = MAX_CIPHER_KEY_LENGTH;
745
int hmac_len = MAX_HMAC_KEY_LENGTH;
751
if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
752
cipher_len = kt->cipher_length;
754
if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
755
hmac_len = kt->hmac_length;
757
ASSERT (RAND_bytes (key->cipher, cipher_len));
758
ASSERT (RAND_bytes (key->hmac, hmac_len));
760
msg (D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex (key->cipher, cipher_len, 0));
761
msg (D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex (key->hmac, hmac_len, 0));
765
} while (kt && !check_key (key, kt));
772
key2_print (const struct key2* k,
773
const struct key_type *kt,
778
msg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
780
format_hex (k->keys[0].cipher, kt->cipher_length, 0));
781
msg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
783
format_hex (k->keys[0].hmac, kt->hmac_length, 0));
784
msg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
786
format_hex (k->keys[1].cipher, kt->cipher_length, 0));
787
msg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
789
format_hex (k->keys[1].hmac, kt->hmac_length, 0));
793
test_crypto (const struct crypto_options *co, struct frame* frame)
796
struct buffer src = alloc_buf_gc (TUN_MTU_SIZE (frame));
797
struct buffer work = alloc_buf_gc (BUF_SIZE (frame));
798
struct buffer encrypt_workspace = alloc_buf_gc (BUF_SIZE (frame));
799
struct buffer decrypt_workspace = alloc_buf_gc (BUF_SIZE (frame));
800
struct buffer buf = clear_buf();
803
ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
805
msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
806
for (i = 1; i <= TUN_MTU_SIZE (frame); ++i)
808
const time_t current = time (NULL);
810
msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
813
* Load src with random data.
815
ASSERT (buf_init (&src, 0));
816
ASSERT (i <= src.capacity);
818
ASSERT (RAND_pseudo_bytes (BPTR (&src), BLEN (&src)));
820
/* copy source to input buf */
822
memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
825
openvpn_encrypt (&buf, encrypt_workspace, co, frame, current);
828
openvpn_decrypt (&buf, decrypt_workspace, co, frame, current);
831
if (buf.len != src.len)
832
msg (M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
833
for (j = 0; j < i; ++j)
835
const uint8_t in = *(BPTR (&src) + j);
836
const uint8_t out = *(BPTR (&buf) + j);
838
msg (M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
841
msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
846
get_tls_handshake_key (const struct key_type *key_type,
847
struct key_ctx_bi *ctx,
848
const char *passphrase_file,
851
if (passphrase_file && key_type->hmac_length)
854
struct key_type kt = *key_type;
855
struct key_direction_state kds;
857
/* for control channel we are only authenticating, not encrypting */
858
kt.cipher_length = 0;
861
/* first try to parse as an OpenVPN static key file */
862
read_key_file (&key2, passphrase_file, false);
868
"Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
877
/* failed, now try to get hash from a freeform file */
878
hash_size = read_passphrase_hash (passphrase_file,
881
MAX_HMAC_KEY_LENGTH);
882
ASSERT (hash_size == kt.hmac_length);
888
"Control Channel Authentication: using '%s' as a free-form passphrase file",
892
/* handle key direction */
894
key_direction_state_init (&kds, key_direction);
895
must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
897
/* initialize hmac key in both directions */
899
init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, DO_ENCRYPT,
900
"Outgoing Control Channel Authentication");
901
init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, DO_DECRYPT,
902
"Incoming Control Channel Authentication");
913
/* header and footer for static key file */
914
static const char static_key_head[] = "-----BEGIN " PACKAGE_NAME " Static key V1-----";
915
static const char static_key_foot[] = "-----END " PACKAGE_NAME " Static key V1-----";
917
static const char printable_char_fmt[] =
918
"Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
920
static const char unprintable_char_fmt[] =
921
"Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
923
/* read key from file */
925
read_key_file (struct key2 *key2, const char *filename, bool must_succeed)
927
const int gc_level = gc_new_level ();
928
struct buffer in = alloc_buf_gc (64);
930
uint8_t hex_byte[3] = {0, 0, 0};
939
uint8_t* out = (uint8_t*) &key2->keys;
940
const int keylen = sizeof (key2->keys);
944
# define PARSE_INITIAL 0
945
# define PARSE_HEAD 1
946
# define PARSE_DATA 2
947
# define PARSE_DATA_COMPLETE 3
948
# define PARSE_FOOT 4
949
# define PARSE_FINISHED 5
950
int state = PARSE_INITIAL;
953
const int hlen = strlen (static_key_head);
954
const int flen = strlen (static_key_foot);
955
const int onekeylen = sizeof (key2->keys[0]);
959
fd = open (filename, O_RDONLY);
961
msg (M_ERR, "Cannot open file key file '%s'", filename);
963
while ((size = read (fd, in.data, in.capacity)))
965
const char *cp = (char *)in.data;
971
msg (M_INFO, "char='%c' s=%d ln=%d li=%d m=%d c=%d",
972
c, state, line_num, line_index, match, count);
977
line_index = match = 0;
982
/* first char of new line */
985
/* first char of line after header line? */
986
if (state == PARSE_HEAD)
989
/* first char of footer */
990
if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
994
/* compare read chars with header line */
995
if (state == PARSE_INITIAL)
997
if (line_index < hlen && c == static_key_head[line_index])
1004
/* compare read chars with footer line */
1005
if (state == PARSE_FOOT)
1007
if (line_index < flen && c == static_key_foot[line_index])
1009
if (++match == flen)
1010
state = PARSE_FINISHED;
1015
if (state == PARSE_DATA)
1019
ASSERT (hb_index >= 0 && hb_index < 2);
1020
hex_byte[hb_index++] = c;
1024
ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
1027
if (++count == keylen)
1028
state = PARSE_DATA_COMPLETE;
1031
else if (isspace(c))
1036
(isprint (c) ? printable_char_fmt : unprintable_char_fmt),
1037
c, line_num, filename, count, onekeylen, keylen);
1050
* Normally we will read either 1 or 2 keys from file.
1052
key2->n = count / onekeylen;
1054
ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys));
1059
msg (M_FATAL, "Insufficient key material or header text not found found in file '%s' (%d/%d/%d bytes found/min/max)",
1060
filename, count, onekeylen, keylen);
1062
if (state != PARSE_FINISHED)
1063
msg (M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1064
filename, count, onekeylen, keylen);
1067
/* zero file read buffer */
1071
warn_if_group_others_accessible (filename);
1077
printf ("KEY READ, n=%d\n", key2->n);
1078
for (i = 0; i < (int) SIZE (key2->keys); ++i)
1080
/* format key as ascii */
1081
const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i],
1082
sizeof (key2->keys[i]),
1086
printf ("[%d]\n%s\n\n", i, fmt);
1091
/* pop our garbage collection level */
1092
gc_free_level (gc_level);
1096
read_passphrase_hash (const char *passphrase_file,
1097
const EVP_MD *digest,
1101
unsigned int outlen = 0;
1104
ASSERT (len >= EVP_MD_size (digest));
1105
memset (output, 0, len);
1107
EVP_DigestInit (&md, digest);
1109
/* read passphrase file */
1111
const int min_passphrase_size = 8;
1114
int fd = open (passphrase_file, O_RDONLY);
1117
msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
1121
int size = read (fd, buf, sizeof (buf));
1125
msg (M_ERR, "Read error on passphrase file: '%s'",
1127
EVP_DigestUpdate (&md, buf, size);
1132
warn_if_group_others_accessible (passphrase_file);
1134
if (total_size < min_passphrase_size)
1136
"Passphrase file '%s' is too small (must have at least %d characters)",
1137
passphrase_file, min_passphrase_size);
1140
EVP_DigestFinal (&md, output, &outlen);
1141
EVP_MD_CTX_cleanup (&md);
1146
* Write key to file, return number of random bits
1150
write_key_file (const int nkeys, const char *filename)
1152
const int gc_level = gc_new_level ();
1157
/* must be large enough to hold full key file */
1158
struct buffer out = alloc_buf_gc (2048);
1159
struct buffer nbits_head_text = alloc_buf_gc (128);
1161
/* how to format the ascii file representation of key */
1162
const int bytes_per_line = 16;
1165
fd = open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
1168
msg (M_ERR, "Cannot open shared secret file '%s' for write", filename);
1170
buf_printf (&out, "%s\n", static_key_head);
1172
for (i = 0; i < nkeys; ++i)
1177
/* generate random bits */
1178
generate_key_random (&key, NULL);
1180
/* format key as ascii */
1181
fmt = format_hex_ex ((const uint8_t*)&key,
1187
/* increment random bits counter */
1188
nbits += sizeof (key) * 8;
1190
/* write to holding buffer */
1191
buf_printf (&out, "%s\n", fmt);
1193
/* zero memory which held key component (will be freed by GC) */
1194
memset (fmt, 0, strlen(fmt));
1198
buf_printf (&out, "%s\n", static_key_foot);
1200
/* write number of bits */
1201
buf_printf (&nbits_head_text, "#\n# %d bit " PACKAGE_NAME " static key\n#\n", nbits);
1202
buf_write_string_file (&nbits_head_text, filename, fd);
1204
/* write key file, now formatted in out, to file */
1205
buf_write_string_file (&out, filename, fd);
1208
msg (M_ERR, "Close error on shared secret file %s", filename);
1210
/* zero memory which held file content (memory will be freed by GC) */
1213
/* pop our garbage collection level */
1214
gc_free_level (gc_level);
1220
must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
1223
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);
1227
ascii2keydirection (const char *str)
1230
return KEY_DIRECTION_BIDIRECTIONAL;
1231
else if (!strcmp (str, "0"))
1232
return KEY_DIRECTION_NORMAL;
1233
else if (!strcmp (str, "1"))
1234
return KEY_DIRECTION_INVERSE;
1236
msg (M_USAGE, "Unknown key direction '%s' -- must be '0' or '1'",
1238
return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1242
keydirection2ascii (int kd, bool remote)
1244
if (kd == KEY_DIRECTION_BIDIRECTIONAL)
1246
else if (kd == KEY_DIRECTION_NORMAL)
1247
return remote ? "1" : "0";
1248
else if (kd == KEY_DIRECTION_INVERSE)
1249
return remote ? "0" : "1";
1254
return NULL; /* NOTREACHED */
1258
key_direction_state_init (struct key_direction_state *kds, int key_direction)
1261
switch (key_direction)
1263
case KEY_DIRECTION_NORMAL:
1268
case KEY_DIRECTION_INVERSE:
1273
case KEY_DIRECTION_BIDIRECTIONAL:
1284
verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1288
for (i = 0; i < key2->n; ++i)
1290
/* Fix parity for DES keys and make sure not a weak key */
1291
fixup_key (&key2->keys[i], kt);
1293
/* This should be a very improbable failure */
1294
if (!check_key (&key2->keys[i], kt))
1295
msg (M_FATAL, "Key #%d in '%s' is bad. Try making a new key with --genkey.",
1296
i+1, shared_secret_file);
1300
/* given a key and key_type, write key to buffer */
1302
write_key (const struct key *key, const struct key_type *kt,
1305
ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH
1306
&& kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
1307
ASSERT (buf_write (buf, &kt->cipher_length, 1));
1308
ASSERT (buf_write (buf, &kt->hmac_length, 1));
1309
ASSERT (buf_write (buf, key->cipher, kt->cipher_length));
1310
ASSERT (buf_write (buf, key->hmac, kt->hmac_length));
1314
* Given a key_type and buffer, read key from buffer.
1315
* Return: 1 on success
1317
* 0 on key length mismatch
1320
read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
1322
uint8_t cipher_length;
1323
uint8_t hmac_length;
1326
if (!buf_read (buf, &cipher_length, 1))
1328
if (!buf_read (buf, &hmac_length, 1))
1331
if (!buf_read (buf, key->cipher, cipher_length))
1333
if (!buf_read (buf, key->hmac, hmac_length))
1336
if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1342
msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
1347
"TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1348
kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
1353
show_available_ciphers ()
1357
printf ("The following ciphers and cipher modes are available\n"
1358
"for use with " PACKAGE_NAME ". Each cipher shown below may be\n"
1359
"used as a parameter to the --cipher option. The default\n"
1360
"key size is shown as well as whether or not it can be\n"
1361
"changed with the --keysize directive. Using a CBC mode\n"
1362
"is recommended.\n\n");
1364
for (nid = 0; nid < 10000; ++nid) /* is there a better way to get the size of the nid list? */
1366
const EVP_CIPHER *cipher = EVP_get_cipherbynid (nid);
1367
if (cipher && cipher_ok (OBJ_nid2sn (nid)))
1369
const unsigned int mode = EVP_CIPHER_mode (cipher);
1370
if (mode == EVP_CIPH_CBC_MODE
1371
#ifdef ALLOW_NON_CBC_CIPHERS
1372
|| mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE
1375
printf ("%s %d bit default key (%s)\n",
1377
EVP_CIPHER_key_length (cipher) * 8,
1378
((EVP_CIPHER_flags (cipher) & EVP_CIPH_VARIABLE_LENGTH) ?
1379
"variable" : "fixed"));
1386
show_available_digests ()
1390
printf ("The following message digests are available for use with\n"
1391
PACKAGE_NAME ". A message digest is used in conjunction with\n"
1392
"the HMAC function, to authenticate received packets.\n"
1393
"You can specify a message digest as parameter to\n"
1394
"the --auth option.\n\n");
1396
for (nid = 0; nid < 10000; ++nid)
1398
const EVP_MD *digest = EVP_get_digestbynid (nid);
1401
printf ("%s %d bit digest size\n",
1402
OBJ_nid2sn (nid), EVP_MD_size (digest) * 8);
1409
* This routine should have additional OpenSSL crypto library initialisations
1410
* used by both crypto and ssl components of OpenVPN.
1412
void init_crypto_lib ()
1417
* Random number functions, used in cases where we want
1418
* reasonably strong cryptographic random number generation
1419
* without depleting our entropy pool. Used for random
1420
* IV values and a number of other miscellaneous tasks.
1423
#define NONCE_SECRET_LEN 16
1425
static uint8_t nonce_data [SHA_DIGEST_LENGTH + NONCE_SECRET_LEN];
1430
ASSERT (RAND_bytes (nonce_data, sizeof(nonce_data)));
1434
prng_bytes (uint8_t *output, int len)
1437
mutex_lock (L_PRNG);
1440
const int blen = min_int (len, SHA_DIGEST_LENGTH);
1442
SHA1_Update (&ctx, nonce_data, sizeof (nonce_data));
1443
SHA1_Final (nonce_data, &ctx);
1444
memcpy (output, nonce_data, blen);
1448
mutex_unlock (L_PRNG);
1451
/* an analogue to the random() function, but use prng_bytes */
1456
prng_bytes ((unsigned char *)&l, sizeof(l));
1463
md5sum(uint8_t *buf, int len, int n_print_chars)
1465
uint8_t digest[MD5_DIGEST_LENGTH];
1466
MD5 (buf, len, digest);
1467
return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars);
1475
ERR_load_crypto_strings ();
1476
OpenSSL_add_all_algorithms ();
1484
ERR_free_strings ();
1487
#endif /* USE_SSL */
1488
#endif /* USE_CRYPTO */