OpenVPN: Update to version 2.3.2. Solves TLS security bug.
[tomato.git] / release / src / router / openvpn / src / openvpn / crypto.c
blobd9adf5b51304cd7611c7bfc8d69d6f6447555476
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-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
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #elif defined(_MSC_VER)
29 #include "config-msvc.h"
30 #endif
32 #include "syshead.h"
34 #ifdef ENABLE_CRYPTO
36 #include "crypto.h"
37 #include "error.h"
38 #include "misc.h"
40 #include "memdbg.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)
68 /**
69 * As memcmp(), but constant-time.
70 * Returns 0 when data is equal, non-zero otherwise.
72 static int
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;
76 int ret = 0;
77 size_t i;
79 for (i = 0; i < size; i++) {
80 ret |= *a1++ ^ *b1++;
83 return ret;
86 void
87 openvpn_encrypt (struct buffer *buf, struct buffer work,
88 const struct crypto_options *opt,
89 const struct frame* frame)
91 struct gc_arena gc;
92 gc_init (&gc);
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 */
99 if (ctx->cipher)
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);
104 int outlen;
106 if (mode == OPENVPN_MODE_CBC)
108 CLEAR (iv_buf);
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 */
115 if (opt->packet_id)
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;
125 struct buffer b;
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 */
137 ASSERT (0);
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",
157 buf->capacity,
158 buf->offset,
159 buf->len,
160 work.capacity,
161 work.offset,
162 work.len,
163 cipher_ctx_block_size (ctx->cipher));
164 goto err;
167 /* Encrypt packet ID, payload */
168 ASSERT (cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
169 work.len += outlen;
171 /* Flush the encryption buffer */
172 ASSERT(cipher_ctx_final(ctx->cipher, BPTR (&work) + outlen, &outlen));
173 work.len += 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);
180 ASSERT (output);
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 */
189 if (opt->packet_id)
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));
195 work = *buf;
198 /* HMAC the ciphertext (or plaintext if !cipher) */
199 if (ctx->hmac)
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));
206 ASSERT (output);
207 hmac_ctx_final (ctx->hmac, output);
210 *buf = work;
213 gc_free (&gc);
214 return;
216 err:
217 crypto_clear_error();
218 buf->len = 0;
219 gc_free (&gc);
220 return;
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
229 * is returned.
231 bool
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";
237 struct gc_arena gc;
238 gc_init (&gc);
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 */
247 if (ctx->hmac)
249 int hmac_len;
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 */
273 if (ctx->cipher)
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];
278 int outlen;
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 */
284 CLEAR (iv_buf);
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));
297 if (buf->len < 1)
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");
311 work.len += outlen;
313 /* Flush the decryption buffer */
314 if (!cipher_ctx_final (ctx->cipher, BPTR (&work) + outlen, &outlen))
315 CRYPT_ERROR ("cipher final failed");
316 work.len += outlen;
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)
325 if (opt->packet_id)
327 if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
328 CRYPT_ERROR ("error reading CBC packet-id");
329 have_pin = true;
332 else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)
334 struct buffer b;
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");
342 have_pin = true;
344 else /* We only support CBC, CFB, or OFB modes right now */
346 ASSERT (0);
350 else
352 work = *buf;
353 if (opt->packet_id)
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);
361 if (have_pin)
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);
370 else
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));
375 goto error_exit;
378 *buf = work;
381 gc_free (&gc);
382 return true;
384 error_exit:
385 crypto_clear_error();
386 buf->len = 0;
387 gc_free (&gc);
388 return false;
392 * How many bytes will we add to frame buffer for a given
393 * set of crypto options?
395 void
396 crypto_adjust_frame_parameters(struct frame *frame,
397 const struct key_type* kt,
398 bool cipher_defined,
399 bool use_iv,
400 bool packet_id,
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 */
407 kt->hmac_length);
411 * Build a struct key_type.
413 void
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)
419 CLEAR (*kt);
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))
433 #endif
435 #ifdef ENABLE_SMALL
436 msg (M_FATAL, "Cipher '%s' mode not supported", ciphername);
437 #else
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);
439 #endif
442 else
444 if (warn)
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);
452 else
454 if (warn)
455 msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
459 /* given a key and key_type, build a key_ctx */
460 void
461 init_key_ctx (struct key_ctx *ctx, struct key *key,
462 const struct key_type *kt, int enc,
463 const char *prefix)
465 struct gc_arena gc = gc_new ();
466 CLEAR (*ctx);
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,
472 kt->cipher, enc);
474 msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
475 prefix,
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",
482 prefix,
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);
491 msg (D_HANDSHAKE,
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",
499 prefix,
500 md_kt_size(kt->digest),
501 hmac_ctx_size(ctx->hmac));
504 gc_free (&gc);
507 void
508 free_key_ctx (struct key_ctx *ctx)
510 if (ctx->cipher)
512 cipher_ctx_cleanup(ctx->cipher);
513 free(ctx->cipher);
514 ctx->cipher = NULL;
516 if (ctx->hmac)
518 hmac_ctx_cleanup(ctx->hmac);
519 free(ctx->hmac);
520 ctx->hmac = NULL;
524 void
525 free_key_ctx_bi (struct key_ctx_bi *ctx)
527 free_key_ctx(&ctx->encrypt);
528 free_key_ctx(&ctx->decrypt);
532 static bool
533 key_is_zero (struct key *key, const struct key_type *kt)
535 int i;
536 for (i = 0; i < kt->cipher_length; ++i)
537 if (key->cipher[i])
538 return false;
539 msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
540 return true;
544 * Make sure that cipher key is a valid key for current key_type.
546 bool
547 check_key (struct key *key, const struct key_type *kt)
549 if (kt->cipher)
552 * Check for zero key
554 if (key_is_zero(key, kt))
555 return false;
558 * Check for weak or semi-weak DES keys.
561 const int ndc = key_des_num_cblocks (kt->cipher);
562 if (ndc)
563 return key_des_check (key->cipher, kt->cipher_length, ndc);
564 else
565 return true;
568 return true;
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
577 * to make sure.
579 void
580 fixup_key (struct key *key, const struct key_type *kt)
582 struct gc_arena gc = gc_new ();
583 if (kt->cipher)
585 #ifdef ENABLE_DEBUG
586 const struct key orig = *key;
587 #endif
588 const int ndc = key_des_num_cblocks (kt->cipher);
590 if (ndc)
591 key_des_fixup (key->cipher, kt->cipher_length, ndc);
593 #ifdef ENABLE_DEBUG
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));
601 #endif
603 gc_free (&gc);
606 void
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");
613 bool
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;
620 return false;
624 * Generate a random key. If key_type is provided, make
625 * sure generated key is valid for key_type.
627 void
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 ();
635 do {
636 CLEAR (*key);
637 if (kt)
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));
652 if (kt)
653 fixup_key (key, kt);
654 } while (kt && !check_key (key, kt));
656 gc_free (&gc);
660 * Print key material
662 void
663 key2_print (const struct key2* k,
664 const struct key_type *kt,
665 const char* prefix0,
666 const char* prefix1)
668 struct gc_arena gc = gc_new ();
669 ASSERT (k->n == 2);
670 dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
671 prefix0,
672 format_hex (k->keys[0].cipher, kt->cipher_length, 0, &gc));
673 dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
674 prefix0,
675 format_hex (k->keys[0].hmac, kt->hmac_length, 0, &gc));
676 dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
677 prefix1,
678 format_hex (k->keys[1].cipher, kt->cipher_length, 0, &gc));
679 dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
680 prefix1,
681 format_hex (k->keys[1].hmac, kt->hmac_length, 0, &gc));
682 gc_free (&gc);
685 void
686 test_crypto (const struct crypto_options *co, struct frame* frame)
688 int i, j;
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();
696 /* init work */
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)
702 update_time ();
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);
711 src.len = i;
712 ASSERT (rand_bytes (BPTR (&src), BLEN (&src)));
714 /* copy source to input buf */
715 buf = work;
716 memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
718 /* encrypt */
719 openvpn_encrypt (&buf, encrypt_workspace, co, frame);
721 /* decrypt */
722 openvpn_decrypt (&buf, decrypt_workspace, co, frame);
724 /* compare */
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);
731 if (in != out)
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.");
736 gc_free (&gc);
739 #ifdef ENABLE_SSL
741 void
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)
750 struct key2 key2;
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;
756 kt.cipher = NULL;
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);
763 /* succeeded? */
764 if (key2.n == 2)
765 msg (M_INFO, "Control Channel Authentication: tls-auth using INLINE static key file");
766 else
767 msg (M_FATAL, "INLINE tls-auth file lacks the requisite 2 keys");
769 else
771 /* first try to parse as an OpenVPN static key file */
772 read_key_file (&key2, passphrase_file, 0);
774 /* succeeded? */
775 if (key2.n == 2)
777 msg (M_INFO,
778 "Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
779 passphrase_file);
781 else
783 int hash_size;
785 CLEAR (key2);
787 /* failed, now try to get hash from a freeform file */
788 hash_size = read_passphrase_hash (passphrase_file,
789 kt.digest,
790 key2.keys[0].hmac,
791 MAX_HMAC_KEY_LENGTH);
792 ASSERT (hash_size == kt.hmac_length);
794 /* suceeded */
795 key2.n = 1;
797 msg (M_INFO,
798 "Control Channel Authentication: using '%s' as a free-form passphrase file",
799 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");
814 CLEAR (key2);
816 else
818 CLEAR (*ctx);
821 #endif
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 */
835 void
836 read_key_file (struct key2 *key2, const char *file, const unsigned int flags)
838 struct gc_arena gc = gc_new ();
839 struct buffer in;
840 int fd, size;
841 uint8_t hex_byte[3] = {0, 0, 0};
842 const char *error_filename = file;
844 /* parse info */
845 const unsigned char *cp;
846 int hb_index = 0;
847 int line_num = 1;
848 int line_index = 0;
849 int match = 0;
851 /* output */
852 uint8_t* out = (uint8_t*) &key2->keys;
853 const int keylen = sizeof (key2->keys);
854 int count = 0;
856 /* parse states */
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;
865 /* constants */
866 const int hlen = strlen (static_key_head);
867 const int flen = strlen (static_key_foot);
868 const int onekeylen = sizeof (key2->keys[0]);
870 CLEAR (*key2);
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);
886 if (fd == -1)
887 msg (M_ERR, "Cannot open file key file '%s'", file);
888 size = read (fd, in.data, in.capacity);
889 if (size < 0)
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);
893 close (fd);
896 cp = (unsigned char *)in.data;
897 while (size > 0)
899 const unsigned char c = *cp;
901 #if 0
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);
904 #endif
906 if (c == '\n')
908 line_index = match = 0;
909 ++line_num;
911 else
913 /* first char of new line */
914 if (!line_index)
916 /* first char of line after header line? */
917 if (state == PARSE_HEAD)
918 state = PARSE_DATA;
920 /* first char of footer */
921 if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
922 state = PARSE_FOOT;
925 /* compare read chars with header line */
926 if (state == PARSE_INITIAL)
928 if (line_index < hlen && c == static_key_head[line_index])
930 if (++match == hlen)
931 state = PARSE_HEAD;
935 /* compare read chars with footer line */
936 if (state == PARSE_FOOT)
938 if (line_index < flen && c == static_key_foot[line_index])
940 if (++match == flen)
941 state = PARSE_FINISHED;
945 /* reading key */
946 if (state == PARSE_DATA)
948 if (isxdigit(c))
950 ASSERT (hb_index >= 0 && hb_index < 2);
951 hex_byte[hb_index++] = c;
952 if (hb_index == 2)
954 unsigned int u;
955 ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
956 *out++ = u;
957 hb_index = 0;
958 if (++count == keylen)
959 state = PARSE_DATA_COMPLETE;
962 else if (isspace(c))
964 else
966 msg (M_FATAL,
967 (isprint (c) ? printable_char_fmt : unprintable_char_fmt),
968 c, line_num, error_filename, count, onekeylen, keylen);
971 ++line_index;
973 ++cp;
974 --size;
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)
986 if (!key2->n)
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))
997 buf_clear (&in);
999 if (key2->n)
1000 warn_if_group_others_accessible (error_filename);
1002 #if 0
1003 /* DEBUGGING */
1005 int i;
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]),
1014 "\n",
1015 &gc);
1016 printf ("[%d]\n%s\n\n", i, fmt);
1019 #endif
1021 /* pop our garbage collection level */
1022 gc_free (&gc);
1026 read_passphrase_hash (const char *passphrase_file,
1027 const md_kt_t *digest,
1028 uint8_t *output,
1029 int len)
1031 unsigned int outlen = 0;
1032 md_ctx_t md;
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;
1042 uint8_t buf[64];
1043 int total_size = 0;
1044 int fd = platform_open (passphrase_file, O_RDONLY, 0);
1046 if (fd == -1)
1047 msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
1049 for (;;)
1051 int size = read (fd, buf, sizeof (buf));
1052 if (size == 0)
1053 break;
1054 if (size == -1)
1055 msg (M_ERR, "Read error on passphrase file: '%s'",
1056 passphrase_file);
1057 md_ctx_update(&md, buf, size);
1058 total_size += size;
1060 close (fd);
1062 warn_if_group_others_accessible (passphrase_file);
1064 if (total_size < min_passphrase_size)
1065 msg (M_FATAL,
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
1076 * written.
1079 write_key_file (const int nkeys, const char *filename)
1081 struct gc_arena gc = gc_new ();
1083 int fd, i;
1084 int nbits = 0;
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;
1093 /* open key file */
1094 fd = platform_open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
1096 if (fd == -1)
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)
1103 struct key key;
1104 char* fmt;
1106 /* generate random bits */
1107 generate_key_random (&key, NULL);
1109 /* format key as ascii */
1110 fmt = format_hex_ex ((const uint8_t*)&key,
1111 sizeof (key),
1113 bytes_per_line,
1114 "\n",
1115 &gc);
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));
1125 CLEAR (key);
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);
1137 if (close (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) */
1141 buf_clear (&out);
1143 /* pop our garbage collection level */
1144 gc_free (&gc);
1146 return nbits;
1149 void
1150 must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
1152 if (key2->n < n)
1154 #ifdef ENABLE_SMALL
1155 msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n);
1156 #else
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);
1158 #endif
1163 ascii2keydirection (int msglevel, const char *str)
1165 if (!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;
1171 else
1173 msg (msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1174 return -1;
1176 return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1179 const char *
1180 keydirection2ascii (int kd, bool remote)
1182 if (kd == KEY_DIRECTION_BIDIRECTIONAL)
1183 return NULL;
1184 else if (kd == KEY_DIRECTION_NORMAL)
1185 return remote ? "1" : "0";
1186 else if (kd == KEY_DIRECTION_INVERSE)
1187 return remote ? "0" : "1";
1188 else
1190 ASSERT (0);
1192 return NULL; /* NOTREACHED */
1195 void
1196 key_direction_state_init (struct key_direction_state *kds, int key_direction)
1198 CLEAR (*kds);
1199 switch (key_direction)
1201 case KEY_DIRECTION_NORMAL:
1202 kds->out_key = 0;
1203 kds->in_key = 1;
1204 kds->need_keys = 2;
1205 break;
1206 case KEY_DIRECTION_INVERSE:
1207 kds->out_key = 1;
1208 kds->in_key = 0;
1209 kds->need_keys = 2;
1210 break;
1211 case KEY_DIRECTION_BIDIRECTIONAL:
1212 kds->out_key = 0;
1213 kds->in_key = 0;
1214 kds->need_keys = 1;
1215 break;
1216 default:
1217 ASSERT (0);
1221 void
1222 verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1224 int i;
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 */
1239 bool
1240 write_key (const struct key *key, const struct key_type *kt,
1241 struct buffer *buf)
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))
1247 return false;
1248 if (!buf_write (buf, &kt->hmac_length, 1))
1249 return false;
1250 if (!buf_write (buf, key->cipher, kt->cipher_length))
1251 return false;
1252 if (!buf_write (buf, key->hmac, kt->hmac_length))
1253 return false;
1255 return true;
1259 * Given a key_type and buffer, read key from buffer.
1260 * Return: 1 on success
1261 * -1 read failure
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;
1270 CLEAR (*key);
1271 if (!buf_read (buf, &cipher_length, 1))
1272 goto read_err;
1273 if (!buf_read (buf, &hmac_length, 1))
1274 goto read_err;
1276 if (!buf_read (buf, key->cipher, cipher_length))
1277 goto read_err;
1278 if (!buf_read (buf, key->hmac, hmac_length))
1279 goto read_err;
1281 if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1282 goto key_len_err;
1284 return 1;
1286 read_err:
1287 msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
1288 return -1;
1290 key_len_err:
1291 msg (D_TLS_ERRORS,
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);
1294 return 0;
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 */
1309 static void
1310 prng_reset_nonce ()
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");
1316 #else
1317 /* Only for testing -- will cause a predictable PRNG sequence */
1319 int i;
1320 for (i = 0; i < size; ++i)
1321 nonce_data[i] = (uint8_t) i;
1323 #endif
1326 void
1327 prng_init (const char *md_name, const int nonce_secret_len_parm)
1329 prng_uninit ();
1330 nonce_md = md_name ? md_kt_get (md_name) : NULL;
1331 if (nonce_md)
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);
1340 prng_reset_nonce();
1345 void
1346 prng_uninit (void)
1348 free (nonce_data);
1349 nonce_data = NULL;
1350 nonce_md = NULL;
1351 nonce_secret_len = 0;
1354 void
1355 prng_bytes (uint8_t *output, int len)
1357 static size_t processed = 0;
1359 if (nonce_md)
1361 const int md_size = md_kt_size (nonce_md);
1362 while (len > 0)
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);
1368 output += blen;
1369 len -= blen;
1371 /* Ensure that random data is reset regularly */
1372 processed += blen;
1373 if(processed > PRNG_NONCE_RESET_BYTES) {
1374 prng_reset_nonce();
1375 processed = 0;
1379 else
1380 rand_bytes (output, len);
1383 /* an analogue to the random() function, but use prng_bytes */
1384 long int
1385 get_random()
1387 long int l;
1388 prng_bytes ((unsigned char *)&l, sizeof(l));
1389 if (l < 0)
1390 l = -l;
1391 return l;
1394 #ifndef ENABLE_SSL
1396 void
1397 init_ssl_lib (void)
1399 crypto_init_lib ();
1402 void
1403 free_ssl_lib (void)
1405 crypto_uninit_lib ();
1406 prng_uninit();
1409 #endif /* ENABLE_SSL */
1412 * md5 functions
1415 const char *
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);
1426 void
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);
1434 void
1435 md5_state_update (struct md5_state *s, void *data, size_t len)
1437 md_ctx_update(&s->ctx, data, len);
1440 void
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);
1447 void
1448 md5_digest_clear (struct md5_digest *digest)
1450 CLEAR (*digest);
1453 bool
1454 md5_digest_defined (const struct md5_digest *digest)
1456 int i;
1457 for (i = 0; i < MD5_DIGEST_LENGTH; ++i)
1458 if (digest->digest[i])
1459 return true;
1460 return false;
1463 bool
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 */