• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/router/openvpn/src/openvpn/
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.
7 *
8 *  Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9 *  Copyright (C) 2010 Fox Crypto B.V. <openvpn@fox-it.com>
10 *
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.
14 *
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.
19 *
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
24 */
25
26#ifdef HAVE_CONFIG_H
27#include "config.h"
28#elif defined(_MSC_VER)
29#include "config-msvc.h"
30#endif
31
32#include "syshead.h"
33
34#ifdef ENABLE_CRYPTO
35
36#include "crypto.h"
37#include "error.h"
38#include "misc.h"
39
40#include "memdbg.h"
41
42/*
43 * Encryption and Compression Routines.
44 *
45 * On entry, buf contains the input data and length.
46 * On exit, it should be set to the output data and length.
47 *
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.
50 *
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.
56 *
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).
59 *
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.
63 */
64
65#define CRYPT_ERROR(format) \
66  do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
67
68/**
69 * As memcmp(), but constant-time.
70 * Returns 0 when data is equal, non-zero otherwise.
71 */
72static int
73memcmp_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;
78
79  for (i = 0; i < size; i++) {
80      ret |= *a1++ ^ *b1++;
81  }
82
83  return ret;
84}
85
86void
87openvpn_encrypt (struct buffer *buf, struct buffer work,
88		 const struct crypto_options *opt,
89		 const struct frame* frame)
90{
91  struct gc_arena gc;
92  gc_init (&gc);
93
94  if (buf->len > 0 && opt->key_ctx_bi)
95    {
96      struct key_ctx *ctx = &opt->key_ctx_bi->encrypt;
97
98      /* Do Encrypt from buf -> work */
99      if (ctx->cipher)
100	{
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;
105
106	  if (mode == OPENVPN_MODE_CBC)
107	    {
108	      CLEAR (iv_buf);
109
110	      /* generate pseudo-random IV */
111	      if (opt->flags & CO_USE_IV)
112		prng_bytes (iv_buf, iv_size);
113
114	      /* Put packet ID in plaintext buffer or IV, depending on cipher mode */
115	      if (opt->packet_id)
116		{
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));
120		}
121	    }
122	  else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)
123	    {
124	      struct packet_id_net pin;
125	      struct buffer b;
126
127	      ASSERT (opt->flags & CO_USE_IV);    /* IV and packet-ID required */
128	      ASSERT (opt->packet_id); /*  for this mode. */
129
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));
134	    }
135	  else /* We only support CBC, CFB, or OFB modes right now */
136	    {
137	      ASSERT (0);
138	    }
139
140	  /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
141	  ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
142
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));
146
147	  dmsg (D_PACKET_CONTENT, "ENCRYPT FROM: %s",
148	       format_hex (BPTR (buf), BLEN (buf), 80, &gc));
149
150	  /* cipher_ctx was already initialized with key & keylen */
151	  ASSERT (cipher_ctx_reset(ctx->cipher, iv_buf));
152
153	  /* Buffer overflow check */
154	  if (!buf_safe (&work, buf->len + cipher_ctx_block_size(ctx->cipher)))
155	    {
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;
165	    }
166
167	  /* Encrypt packet ID, payload */
168	  ASSERT (cipher_ctx_update (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
169	  work.len += outlen;
170
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);
175
176	  /* prepend the IV to the ciphertext */
177	  if (opt->flags & CO_USE_IV)
178	    {
179	      uint8_t *output = buf_prepend (&work, iv_size);
180	      ASSERT (output);
181	      memcpy (output, iv_buf, iv_size);
182	    }
183
184	  dmsg (D_PACKET_CONTENT, "ENCRYPT TO: %s",
185	       format_hex (BPTR (&work), BLEN (&work), 80, &gc));
186	}
187      else				/* No Encryption */
188	{
189	  if (opt->packet_id)
190	    {
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));
194	    }
195	  work = *buf;
196	}
197
198      /* HMAC the ciphertext (or plaintext if !cipher) */
199      if (ctx->hmac)
200	{
201	  uint8_t *output = NULL;
202
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);
208	}
209
210      *buf = work;
211    }
212
213  gc_free (&gc);
214  return;
215
216err:
217  crypto_clear_error();
218  buf->len = 0;
219  gc_free (&gc);
220  return;
221}
222
223/*
224 * If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet.
225 *
226 * Set buf->len to 0 and return false on decrypt error.
227 *
228 * On success, buf is set to point to plaintext, true
229 * is returned.
230 */
231bool
232openvpn_decrypt (struct buffer *buf, struct buffer work,
233		 const struct crypto_options *opt,
234		 const struct frame* frame)
235{
236  static const char error_prefix[] = "Authenticate/Decrypt packet error";
237  struct gc_arena gc;
238  gc_init (&gc);
239
240  if (buf->len > 0 && opt->key_ctx_bi)
241    {
242      struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
243      struct packet_id_net pin;
244      bool have_pin = false;
245
246      /* Verify the HMAC */
247      if (ctx->hmac)
248	{
249	  int hmac_len;
250	  uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
251
252	  hmac_ctx_reset(ctx->hmac);
253
254	  /* Assume the length of the input HMAC */
255	  hmac_len = hmac_ctx_size (ctx->hmac);
256
257	  /* Authentication fails if insufficient data in packet for HMAC */
258	  if (buf->len < hmac_len)
259	    CRYPT_ERROR ("missing authentication info");
260
261	  hmac_ctx_update (ctx->hmac, BPTR (buf) + hmac_len, BLEN (buf) - hmac_len);
262	  hmac_ctx_final (ctx->hmac, local_hmac);
263
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");
267
268	  ASSERT (buf_advance (buf, hmac_len));
269	}
270
271      /* Decrypt packet ID + payload */
272
273      if (ctx->cipher)
274	{
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;
279
280	  /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
281	  ASSERT (buf_init (&work, FRAME_HEADROOM_ADJ (frame, FRAME_HEADROOM_MARKER_DECRYPT)));
282
283	  /* use IV if user requested it */
284	  CLEAR (iv_buf);
285	  if (opt->flags & CO_USE_IV)
286	    {
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));
291	    }
292
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));
296
297	  if (buf->len < 1)
298	    CRYPT_ERROR ("missing payload");
299
300	  /* ctx->cipher was already initialized with key & keylen */
301	  if (!cipher_ctx_reset (ctx->cipher, iv_buf))
302	    CRYPT_ERROR ("cipher init failed");
303
304	  /* Buffer overflow check (should never happen) */
305	  if (!buf_safe (&work, buf->len))
306	    CRYPT_ERROR ("buffer overflow");
307
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;
312
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;
317
318	  dmsg (D_PACKET_CONTENT, "DECRYPT TO: %s",
319	       format_hex (BPTR (&work), BLEN (&work), 80, &gc));
320
321	  /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
322	  {
323	    if (mode == OPENVPN_MODE_CBC)
324	      {
325		if (opt->packet_id)
326		  {
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;
330		  }
331	      }
332	    else if (mode == OPENVPN_MODE_CFB || mode == OPENVPN_MODE_OFB)
333	      {
334		struct buffer b;
335
336		ASSERT (opt->flags & CO_USE_IV);    /* IV and packet-ID required */
337		ASSERT (opt->packet_id); /*  for this mode. */
338
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;
343	      }
344	    else /* We only support CBC, CFB, or OFB modes right now */
345	      {
346		ASSERT (0);
347	      }
348	  }
349	}
350      else
351	{
352	  work = *buf;
353	  if (opt->packet_id)
354	    {
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);
358	    }
359	}
360
361      if (have_pin)
362	{
363	  packet_id_reap_test (&opt->packet_id->rec);
364	  if (packet_id_test (&opt->packet_id->rec, &pin))
365	    {
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);
369	    }
370	  else
371	    {
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;
376	    }
377	}
378      *buf = work;
379    }
380
381  gc_free (&gc);
382  return true;
383
384 error_exit:
385  crypto_clear_error();
386  buf->len = 0;
387  gc_free (&gc);
388  return false;
389}
390
391/*
392 * How many bytes will we add to frame buffer for a given
393 * set of crypto options?
394 */
395void
396crypto_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)
402{
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);
408}
409
410/*
411 * Build a struct key_type.
412 */
413void
414init_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)
418{
419  CLEAR (*kt);
420  if (ciphername && ciphername_defined)
421    {
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;
426
427      /* check legal cipher mode */
428      {
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
434	      ))
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
440      }
441    }
442  else
443    {
444      if (warn)
445	msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used");
446    }
447  if (authname && authname_defined)
448    {
449      kt->digest = md_kt_get (authname);
450      kt->hmac_length = md_kt_size (kt->digest);
451    }
452  else
453    {
454      if (warn)
455	msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
456    }
457}
458
459/* given a key and key_type, build a key_ctx */
460void
461init_key_ctx (struct key_ctx *ctx, struct key *key,
462	      const struct key_type *kt, int enc,
463	      const char *prefix)
464{
465  struct gc_arena gc = gc_new ();
466  CLEAR (*ctx);
467  if (kt->cipher && kt->cipher_length > 0)
468    {
469
470      ALLOC_OBJ(ctx->cipher, cipher_ctx_t);
471      cipher_ctx_init (ctx->cipher, key->cipher, kt->cipher_length,
472	  kt->cipher, enc);
473
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);
478
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));
485    }
486  if (kt->digest && kt->hmac_length > 0)
487    {
488      ALLOC_OBJ(ctx->hmac, hmac_ctx_t);
489      hmac_ctx_init (ctx->hmac, key->hmac, kt->hmac_length, kt->digest);
490
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));
494
495      dmsg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
496	  format_hex (key->hmac, kt->hmac_length, 0, &gc));
497
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));
502
503    }
504  gc_free (&gc);
505}
506
507void
508free_key_ctx (struct key_ctx *ctx)
509{
510  if (ctx->cipher)
511    {
512      cipher_ctx_cleanup(ctx->cipher);
513      free(ctx->cipher);
514      ctx->cipher = NULL;
515    }
516  if (ctx->hmac)
517    {
518      hmac_ctx_cleanup(ctx->hmac);
519      free(ctx->hmac);
520      ctx->hmac = NULL;
521    }
522}
523
524void
525free_key_ctx_bi (struct key_ctx_bi *ctx)
526{
527  free_key_ctx(&ctx->encrypt);
528  free_key_ctx(&ctx->decrypt);
529}
530
531
532static bool
533key_is_zero (struct key *key, const struct key_type *kt)
534{
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;
541}
542
543/*
544 * Make sure that cipher key is a valid key for current key_type.
545 */
546bool
547check_key (struct key *key, const struct key_type *kt)
548{
549  if (kt->cipher)
550    {
551      /*
552       * Check for zero key
553       */
554      if (key_is_zero(key, kt))
555	return false;
556
557      /*
558       * Check for weak or semi-weak DES keys.
559       */
560      {
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;
566      }
567    }
568  return true;
569}
570
571/*
572 * Make safe mutations to key to ensure it is valid,
573 * such as ensuring correct parity on DES keys.
574 *
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.
578 */
579void
580fixup_key (struct key *key, const struct key_type *kt)
581{
582  struct gc_arena gc = gc_new ();
583  if (kt->cipher)
584    {
585#ifdef ENABLE_DEBUG
586      const struct key orig = *key;
587#endif
588      const int ndc = key_des_num_cblocks (kt->cipher);
589
590      if (ndc)
591	key_des_fixup (key->cipher, kt->cipher_length, ndc);
592
593#ifdef ENABLE_DEBUG
594      if (check_debug_level (D_CRYPTO_DEBUG))
595	{
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));
600	}
601#endif
602    }
603  gc_free (&gc);
604}
605
606void
607check_replay_iv_consistency (const struct key_type *kt, bool packet_id, bool use_iv)
608{
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");
611}
612
613bool
614cfb_ofb_mode (const struct key_type* kt)
615{
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;
619  }
620  return false;
621}
622
623/*
624 * Generate a random key.  If key_type is provided, make
625 * sure generated key is valid for key_type.
626 */
627void
628generate_key_random (struct key *key, const struct key_type *kt)
629{
630  int cipher_len = MAX_CIPHER_KEY_LENGTH;
631  int hmac_len = MAX_HMAC_KEY_LENGTH;
632
633  struct gc_arena gc = gc_new ();
634
635  do {
636    CLEAR (*key);
637    if (kt)
638      {
639	if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
640	  cipher_len = kt->cipher_length;
641
642	if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
643	  hmac_len = kt->hmac_length;
644      }
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");
648
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));
651
652    if (kt)
653      fixup_key (key, kt);
654  } while (kt && !check_key (key, kt));
655
656  gc_free (&gc);
657}
658
659/*
660 * Print key material
661 */
662void
663key2_print (const struct key2* k,
664	    const struct key_type *kt,
665	    const char* prefix0,
666	    const char* prefix1)
667{
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);
683}
684
685void
686test_crypto (const struct crypto_options *co, struct frame* frame)
687{
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();
695
696  /* init work */
697  ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
698
699  msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
700  for (i = 1; i <= TUN_MTU_SIZE (frame); ++i)
701    {
702      update_time ();
703
704      msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
705
706      /*
707       * Load src with random data.
708       */
709      ASSERT (buf_init (&src, 0));
710      ASSERT (i <= src.capacity);
711      src.len = i;
712      ASSERT (rand_bytes (BPTR (&src), BLEN (&src)));
713
714      /* copy source to input buf */
715      buf = work;
716      memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
717
718      /* encrypt */
719      openvpn_encrypt (&buf, encrypt_workspace, co, frame);
720
721      /* decrypt */
722      openvpn_decrypt (&buf, decrypt_workspace, co, frame);
723
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)
728	{
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);
733	}
734    }
735  msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
736  gc_free (&gc);
737}
738
739#ifdef ENABLE_SSL
740
741void
742get_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)
747{
748  if (passphrase_file && key_type->hmac_length)
749    {
750      struct key2 key2;
751      struct key_type kt = *key_type;
752      struct key_direction_state kds;
753
754      /* for control channel we are only authenticating, not encrypting */
755      kt.cipher_length = 0;
756      kt.cipher = NULL;
757
758      if (flags & GHK_INLINE)
759	{
760	  /* key was specified inline, key text is in passphrase_file */
761	  read_key_file (&key2, passphrase_file, RKF_INLINE|RKF_MUST_SUCCEED);
762
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");
768	}
769      else
770      {
771	/* first try to parse as an OpenVPN static key file */
772	read_key_file (&key2, passphrase_file, 0);
773
774	/* succeeded? */
775	if (key2.n == 2)
776	  {
777	    msg (M_INFO,
778		 "Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
779		 passphrase_file);
780	  }
781	else
782	  {
783	    int hash_size;
784
785	    CLEAR (key2);
786
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);
793
794	    /* suceeded */
795	    key2.n = 1;
796
797	    msg (M_INFO,
798		 "Control Channel Authentication: using '%s' as a free-form passphrase file",
799		 passphrase_file);
800	  }
801      }
802      /* handle key direction */
803
804      key_direction_state_init (&kds, key_direction);
805      must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
806
807      /* initialize hmac key in both directions */
808
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");
813
814      CLEAR (key2);
815    }
816  else
817    {
818      CLEAR (*ctx);
819    }
820}
821#endif
822
823/* header and footer for static key file */
824static const char static_key_head[] = "-----BEGIN OpenVPN Static key V1-----";
825static const char static_key_foot[] = "-----END OpenVPN Static key V1-----";
826
827static 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)";
829
830static 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)";
832
833/* read key from file */
834
835void
836read_key_file (struct key2 *key2, const char *file, const unsigned int flags)
837{
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;
843
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;
850
851  /* output */
852  uint8_t* out = (uint8_t*) &key2->keys;
853  const int keylen = sizeof (key2->keys);
854  int count = 0;
855
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;
864
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]);
869
870  CLEAR (*key2);
871
872  /*
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.
875   */
876  if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */
877    {
878      size = strlen (file) + 1;
879      buf_set_read (&in, (const uint8_t *)file, size);
880      error_filename = INLINE_FILE_TAG;
881    }
882  else /* 'file' is a filename which refers to a file containing the ascii key */
883    {
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);
894    }
895
896  cp = (unsigned char *)in.data;
897  while (size > 0)
898    {
899      const unsigned char c = *cp;
900
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
905
906      if (c == '\n')
907	{
908	  line_index = match = 0;
909	  ++line_num;
910	}
911      else
912	{
913	  /* first char of new line */
914	  if (!line_index)
915	    {
916	      /* first char of line after header line? */
917	      if (state == PARSE_HEAD)
918		state = PARSE_DATA;
919
920	      /* first char of footer */
921	      if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
922		state = PARSE_FOOT;
923	    }
924
925	  /* compare read chars with header line */
926	  if (state == PARSE_INITIAL)
927	    {
928	      if (line_index < hlen && c == static_key_head[line_index])
929		{
930		  if (++match == hlen)
931		    state = PARSE_HEAD;
932		}
933	    }
934
935	  /* compare read chars with footer line */
936	  if (state == PARSE_FOOT)
937	    {
938	      if (line_index < flen && c == static_key_foot[line_index])
939		{
940		  if (++match == flen)
941		    state = PARSE_FINISHED;
942		}
943	    }
944
945	  /* reading key */
946	  if (state == PARSE_DATA)
947	    {
948	      if (isxdigit(c))
949		{
950		  ASSERT (hb_index >= 0 && hb_index < 2);
951		  hex_byte[hb_index++] = c;
952		  if (hb_index == 2)
953		    {
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;
960		    }
961		}
962	      else if (isspace(c))
963		;
964	      else
965		{
966		  msg (M_FATAL,
967		       (isprint (c) ? printable_char_fmt : unprintable_char_fmt),
968		       c, line_num, error_filename, count, onekeylen, keylen);
969		}
970	    }
971	  ++line_index;
972	}
973      ++cp;
974      --size;
975    }
976
977  /*
978   * Normally we will read either 1 or 2 keys from file.
979   */
980  key2->n = count / onekeylen;
981
982  ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys));
983
984  if (flags & RKF_MUST_SUCCEED)
985    {
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);
989
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);
993    }
994
995  /* zero file read buffer if not an inline file */
996  if (!(flags & RKF_INLINE))
997    buf_clear (&in);
998
999  if (key2->n)
1000    warn_if_group_others_accessible (error_filename);
1001
1002#if 0
1003  /* DEBUGGING */
1004  {
1005    int i;
1006    printf ("KEY READ, n=%d\n", key2->n);
1007    for (i = 0; i < (int) SIZE (key2->keys); ++i)
1008      {
1009	/* format key as ascii */
1010	const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i],
1011					 sizeof (key2->keys[i]),
1012					 0,
1013					 16,
1014					 "\n",
1015					 &gc);
1016	printf ("[%d]\n%s\n\n", i, fmt);
1017      }
1018  }
1019#endif
1020
1021  /* pop our garbage collection level */
1022  gc_free (&gc);
1023}
1024
1025int
1026read_passphrase_hash (const char *passphrase_file,
1027		      const md_kt_t *digest,
1028		      uint8_t *output,
1029		      int len)
1030{
1031  unsigned int outlen = 0;
1032  md_ctx_t md;
1033
1034  ASSERT (len >= md_kt_size(digest));
1035  memset (output, 0, len);
1036
1037  md_ctx_init(&md, digest);
1038
1039  /* read passphrase file */
1040  {
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);
1045
1046    if (fd == -1)
1047      msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
1048
1049    for (;;)
1050      {
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;
1059      }
1060    close (fd);
1061
1062    warn_if_group_others_accessible (passphrase_file);
1063
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);
1068  }
1069  md_ctx_final(&md, output);
1070  md_ctx_cleanup(&md);
1071  return md_kt_size(digest);
1072}
1073
1074/*
1075 * Write key to file, return number of random bits
1076 * written.
1077 */
1078int
1079write_key_file (const int nkeys, const char *filename)
1080{
1081  struct gc_arena gc = gc_new ();
1082
1083  int fd, i;
1084  int nbits = 0;
1085
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);
1089
1090  /* how to format the ascii file representation of key */
1091  const int bytes_per_line = 16;
1092
1093  /* open key file */
1094  fd = platform_open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
1095
1096  if (fd == -1)
1097    msg (M_ERR, "Cannot open shared secret file '%s' for write", filename);
1098
1099  buf_printf (&out, "%s\n", static_key_head);
1100
1101  for (i = 0; i < nkeys; ++i)
1102    {
1103      struct key key;
1104      char* fmt;
1105
1106      /* generate random bits */
1107      generate_key_random (&key, NULL);
1108
1109      /* format key as ascii */
1110      fmt = format_hex_ex ((const uint8_t*)&key,
1111			   sizeof (key),
1112			   0,
1113			   bytes_per_line,
1114			   "\n",
1115			   &gc);
1116
1117      /* increment random bits counter */
1118      nbits += sizeof (key) * 8;
1119
1120      /* write to holding buffer */
1121      buf_printf (&out, "%s\n", fmt);
1122
1123      /* zero memory which held key component (will be freed by GC) */
1124      memset (fmt, 0, strlen(fmt));
1125      CLEAR (key);
1126    }
1127
1128  buf_printf (&out, "%s\n", static_key_foot);
1129
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);
1133
1134  /* write key file, now formatted in out, to file */
1135  buf_write_string_file (&out, filename, fd);
1136
1137  if (close (fd))
1138    msg (M_ERR, "Close error on shared secret file %s", filename);
1139
1140  /* zero memory which held file content (memory will be freed by GC) */
1141  buf_clear (&out);
1142
1143  /* pop our garbage collection level */
1144  gc_free (&gc);
1145
1146  return nbits;
1147}
1148
1149void
1150must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
1151{
1152  if (key2->n < n)
1153    {
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
1159    }
1160}
1161
1162int
1163ascii2keydirection (int msglevel, const char *str)
1164{
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
1172    {
1173      msg (msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1174      return -1;
1175    }
1176  return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1177}
1178
1179const char *
1180keydirection2ascii (int kd, bool remote)
1181{
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
1189    {
1190      ASSERT (0);
1191    }
1192  return NULL; /* NOTREACHED */
1193}
1194
1195void
1196key_direction_state_init (struct key_direction_state *kds, int key_direction)
1197{
1198  CLEAR (*kds);
1199  switch (key_direction)
1200    {
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);
1218    }
1219}
1220
1221void
1222verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1223{
1224  int i;
1225
1226  for (i = 0; i < key2->n; ++i)
1227    {
1228      /* Fix parity for DES keys and make sure not a weak key */
1229      fixup_key (&key2->keys[i], kt);
1230
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);
1235    }
1236}
1237
1238/* given a key and key_type, write key to buffer */
1239bool
1240write_key (const struct key *key, const struct key_type *kt,
1241	   struct buffer *buf)
1242{
1243  ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH
1244	  && kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
1245
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;
1254
1255  return true;
1256}
1257
1258/*
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
1263 */
1264int
1265read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
1266{
1267  uint8_t cipher_length;
1268  uint8_t hmac_length;
1269
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;
1275
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;
1280
1281  if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1282    goto key_len_err;
1283
1284  return 1;
1285
1286read_err:
1287  msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
1288  return -1;
1289
1290key_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;
1295}
1296
1297/*
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.
1302 */
1303
1304static uint8_t *nonce_data = NULL; /* GLOBAL */
1305static const md_kt_t *nonce_md = NULL; /* GLOBAL */
1306static int nonce_secret_len = 0; /* GLOBAL */
1307
1308/* Reset the nonce value, also done periodically to refresh entropy */
1309static void
1310prng_reset_nonce ()
1311{
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 */
1318    {
1319      int i;
1320      for (i = 0; i < size; ++i)
1321	nonce_data[i] = (uint8_t) i;
1322    }
1323#endif
1324}
1325
1326void
1327prng_init (const char *md_name, const int nonce_secret_len_parm)
1328{
1329  prng_uninit ();
1330  nonce_md = md_name ? md_kt_get (md_name) : NULL;
1331  if (nonce_md)
1332    {
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;
1335      {
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();
1341      }
1342    }
1343}
1344
1345void
1346prng_uninit (void)
1347{
1348  free (nonce_data);
1349  nonce_data = NULL;
1350  nonce_md = NULL;
1351  nonce_secret_len = 0;
1352}
1353
1354void
1355prng_bytes (uint8_t *output, int len)
1356{
1357  static size_t processed = 0;
1358
1359  if (nonce_md)
1360    {
1361      const int md_size = md_kt_size (nonce_md);
1362      while (len > 0)
1363	{
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;
1370
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;
1376	  }
1377	}
1378    }
1379  else
1380    rand_bytes (output, len);
1381}
1382
1383/* an analogue to the random() function, but use prng_bytes */
1384long int
1385get_random()
1386{
1387  long int l;
1388  prng_bytes ((unsigned char *)&l, sizeof(l));
1389  if (l < 0)
1390    l = -l;
1391  return l;
1392}
1393
1394#ifndef ENABLE_SSL
1395
1396void
1397init_ssl_lib (void)
1398{
1399  crypto_init_lib ();
1400}
1401
1402void
1403free_ssl_lib (void)
1404{
1405  crypto_uninit_lib ();
1406  prng_uninit();
1407}
1408
1409#endif /* ENABLE_SSL */
1410
1411/*
1412 * md5 functions
1413 */
1414
1415const char *
1416md5sum (uint8_t *buf, int len, int n_print_chars, struct gc_arena *gc)
1417{
1418  uint8_t digest[MD5_DIGEST_LENGTH];
1419  const md_kt_t *md5_kt = md_kt_get("MD5");
1420
1421  md_full(md5_kt, buf, len, digest);
1422
1423  return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars, gc);
1424}
1425
1426void
1427md5_state_init (struct md5_state *s)
1428{
1429  const md_kt_t *md5_kt = md_kt_get("MD5");
1430
1431  md_ctx_init(&s->ctx, md5_kt);
1432}
1433
1434void
1435md5_state_update (struct md5_state *s, void *data, size_t len)
1436{
1437  md_ctx_update(&s->ctx, data, len);
1438}
1439
1440void
1441md5_state_final (struct md5_state *s, struct md5_digest *out)
1442{
1443  md_ctx_final(&s->ctx, out->digest);
1444  md_ctx_cleanup(&s->ctx);
1445}
1446
1447void
1448md5_digest_clear (struct md5_digest *digest)
1449{
1450  CLEAR (*digest);
1451}
1452
1453bool
1454md5_digest_defined (const struct md5_digest *digest)
1455{
1456  int i;
1457  for (i = 0; i < MD5_DIGEST_LENGTH; ++i)
1458    if (digest->digest[i])
1459      return true;
1460  return false;
1461}
1462
1463bool
1464md5_digest_equal (const struct md5_digest *d1, const struct md5_digest *d2)
1465{
1466  return memcmp(d1->digest, d2->digest, MD5_DIGEST_LENGTH) == 0;
1467}
1468
1469#endif /* ENABLE_CRYPTO */
1470