cosmetics
[tomato.git] / release / src / router / openvpn / crypto.c.orig
blobb56038aac2feca44daf7cd20428877a239dfe3be
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-2009 OpenVPN Technologies, Inc. <sales@openvpn.net>
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2
12  *  as published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program (see the file COPYING included with this
21  *  distribution); if not, write to the Free Software Foundation, Inc.,
22  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
25 #include "syshead.h"
27 #ifdef USE_CRYPTO
29 #include "crypto.h"
30 #include "error.h"
31 #include "misc.h"
32 #include "thread.h"
34 #include "memdbg.h"
37  * Check for key size creepage.
38  */
40 #if MAX_CIPHER_KEY_LENGTH < EVP_MAX_KEY_LENGTH
41 #warning Some OpenSSL EVP ciphers now support key lengths greater than MAX_CIPHER_KEY_LENGTH -- consider increasing MAX_CIPHER_KEY_LENGTH
42 #endif
44 #if MAX_HMAC_KEY_LENGTH < EVP_MAX_MD_SIZE
45 #warning Some OpenSSL HMAC message digests now support key lengths greater than MAX_HMAC_KEY_LENGTH -- consider increasing MAX_HMAC_KEY_LENGTH
46 #endif
49  * Encryption and Compression Routines.
50  *
51  * On entry, buf contains the input data and length.
52  * On exit, it should be set to the output data and length.
53  *
54  * If buf->len is <= 0 we should return
55  * If buf->len is set to 0 on exit it tells the caller to ignore the packet.
56  *
57  * work is a workspace buffer we are given of size BUF_SIZE.
58  * work may be used to return output data, or the input buffer
59  * may be modified and returned as output.  If output data is
60  * returned in work, the data should start after FRAME_HEADROOM bytes
61  * of padding to leave room for downstream routines to prepend.
62  *
63  * Up to a total of FRAME_HEADROOM bytes may be prepended to the input buf
64  * by all routines (encryption, decryption, compression, and decompression).
65  *
66  * Note that the buf_prepend return will assert if we try to
67  * make a header bigger than FRAME_HEADROOM.  This should not
68  * happen unless the frame parameters are wrong.
69  */
71 #define CRYPT_ERROR(format) \
72   do { msg (D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
74 void
75 openvpn_encrypt (struct buffer *buf, struct buffer work,
76                  const struct crypto_options *opt,
77                  const struct frame* frame)
79   struct gc_arena gc;
80   gc_init (&gc);
82   if (buf->len > 0 && opt->key_ctx_bi)
83     {
84       struct key_ctx *ctx = &opt->key_ctx_bi->encrypt;
86       /* Do Encrypt from buf -> work */
87       if (ctx->cipher)
88         {
89           uint8_t iv_buf[EVP_MAX_IV_LENGTH];
90           const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
91           const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);  
92           int outlen;
94           if (mode == EVP_CIPH_CBC_MODE)
95             {
96               CLEAR (iv_buf);
98               /* generate pseudo-random IV */
99               if (opt->flags & CO_USE_IV)
100                 prng_bytes (iv_buf, iv_size);
102               /* Put packet ID in plaintext buffer or IV, depending on cipher mode */
103               if (opt->packet_id)
104                 {
105                   struct packet_id_net pin;
106                   packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM));
107                   ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true));
108                 }
109             }
110           else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
111             {
112               struct packet_id_net pin;
113               struct buffer b;
115               ASSERT (opt->flags & CO_USE_IV);    /* IV and packet-ID required */
116               ASSERT (opt->packet_id); /*  for this mode. */
118               packet_id_alloc_outgoing (&opt->packet_id->send, &pin, true);
119               memset (iv_buf, 0, iv_size);
120               buf_set_write (&b, iv_buf, iv_size);
121               ASSERT (packet_id_write (&pin, &b, true, false));
122             }
123           else /* We only support CBC, CFB, or OFB modes right now */
124             {
125               ASSERT (0);
126             }
128           /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
129           ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
131           /* set the IV pseudo-randomly */
132           if (opt->flags & CO_USE_IV)
133             dmsg (D_PACKET_CONTENT, "ENCRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
135           dmsg (D_PACKET_CONTENT, "ENCRYPT FROM: %s",
136                format_hex (BPTR (buf), BLEN (buf), 80, &gc));
138           /* cipher_ctx was already initialized with key & keylen */
139           ASSERT (EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_ENCRYPT));
141           /* Buffer overflow check */
142           if (!buf_safe (&work, buf->len + EVP_CIPHER_CTX_block_size (ctx->cipher)))
143             {
144               msg (D_CRYPT_ERRORS, "ENCRYPT: buffer size error, bc=%d bo=%d bl=%d wc=%d wo=%d wl=%d cbs=%d",
145                    buf->capacity,
146                    buf->offset,
147                    buf->len,
148                    work.capacity,
149                    work.offset,
150                    work.len,
151                    EVP_CIPHER_CTX_block_size (ctx->cipher));
152               goto err;
153             }
155           /* Encrypt packet ID, payload */
156           ASSERT (EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)));
157           work.len += outlen;
159           /* Flush the encryption buffer */
160           ASSERT (EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen));
161           work.len += outlen;
163           /* prepend the IV to the ciphertext */
164           if (opt->flags & CO_USE_IV)
165             {
166               uint8_t *output = buf_prepend (&work, iv_size);
167               ASSERT (output);
168               memcpy (output, iv_buf, iv_size);
169             }
171           dmsg (D_PACKET_CONTENT, "ENCRYPT TO: %s",
172                format_hex (BPTR (&work), BLEN (&work), 80, &gc));
173         }
174       else                              /* No Encryption */
175         {
176           if (opt->packet_id)
177             {
178               struct packet_id_net pin;
179               packet_id_alloc_outgoing (&opt->packet_id->send, &pin, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM));
180               ASSERT (packet_id_write (&pin, buf, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM), true));
181             }
182           work = *buf;
183         }
185       /* HMAC the ciphertext (or plaintext if !cipher) */
186       if (ctx->hmac)
187         {
188           int hmac_len;
189           uint8_t *output;
191           HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
192           HMAC_Update (ctx->hmac, BPTR (&work), BLEN (&work));
193           output = buf_prepend (&work, HMAC_size (ctx->hmac));
194           ASSERT (output);
195           HMAC_Final (ctx->hmac, output, (unsigned int *)&hmac_len);
196           ASSERT (hmac_len == HMAC_size (ctx->hmac));
197         }
199       *buf = work;
200     }
202   gc_free (&gc);
203   return;
205  err:
206   ERR_clear_error ();
207   buf->len = 0;
208   gc_free (&gc);
209   return;
213  * If (opt->flags & CO_USE_IV) is not NULL, we will read an IV from the packet.
215  * Set buf->len to 0 and return false on decrypt error.
217  * On success, buf is set to point to plaintext, true
218  * is returned.
219  */
220 bool
221 openvpn_decrypt (struct buffer *buf, struct buffer work,
222                  const struct crypto_options *opt,
223                  const struct frame* frame)
225   static const char error_prefix[] = "Authenticate/Decrypt packet error";
226   struct gc_arena gc;
227   gc_init (&gc);
229   if (buf->len > 0 && opt->key_ctx_bi)
230     {
231       struct key_ctx *ctx = &opt->key_ctx_bi->decrypt;
232       struct packet_id_net pin;
233       bool have_pin = false;
235       /* Verify the HMAC */
236       if (ctx->hmac)
237         {
238           int hmac_len;
239           uint8_t local_hmac[MAX_HMAC_KEY_LENGTH]; /* HMAC of ciphertext computed locally */
240           int in_hmac_len;
242           HMAC_Init_ex (ctx->hmac, NULL, 0, NULL, NULL);
244           /* Assume the length of the input HMAC */
245           hmac_len = HMAC_size (ctx->hmac);
247           /* Authentication fails if insufficient data in packet for HMAC */
248           if (buf->len < hmac_len)
249             CRYPT_ERROR ("missing authentication info");
251           HMAC_Update (ctx->hmac, BPTR (buf) + hmac_len,
252                        BLEN (buf) - hmac_len);
253           HMAC_Final (ctx->hmac, local_hmac, (unsigned int *)&in_hmac_len);
254           ASSERT (hmac_len == in_hmac_len);
256           /* Compare locally computed HMAC with packet HMAC */
257           if (memcmp (local_hmac, BPTR (buf), hmac_len))
258             CRYPT_ERROR ("packet HMAC authentication failed");
260           ASSERT (buf_advance (buf, hmac_len));
261         }
263       /* Decrypt packet ID + payload */
265       if (ctx->cipher)
266         {
267           const unsigned int mode = EVP_CIPHER_CTX_mode (ctx->cipher);
268           const int iv_size = EVP_CIPHER_CTX_iv_length (ctx->cipher);
269           uint8_t iv_buf[EVP_MAX_IV_LENGTH];
270           int outlen;
272           /* initialize work buffer with FRAME_HEADROOM bytes of prepend capacity */
273           ASSERT (buf_init (&work, FRAME_HEADROOM_ADJ (frame, FRAME_HEADROOM_MARKER_DECRYPT)));
275           /* use IV if user requested it */
276           CLEAR (iv_buf);
277           if (opt->flags & CO_USE_IV)
278             {
279               if (buf->len < iv_size)
280                 CRYPT_ERROR ("missing IV info");
281               memcpy (iv_buf, BPTR (buf), iv_size);
282               ASSERT (buf_advance (buf, iv_size));
283             }
285           /* show the IV's initial state */
286           if (opt->flags & CO_USE_IV)
287             dmsg (D_PACKET_CONTENT, "DECRYPT IV: %s", format_hex (iv_buf, iv_size, 0, &gc));
289           if (buf->len < 1)
290             CRYPT_ERROR ("missing payload");
292           /* ctx->cipher was already initialized with key & keylen */
293           if (!EVP_CipherInit_ov (ctx->cipher, NULL, NULL, iv_buf, DO_DECRYPT))
294             CRYPT_ERROR ("cipher init failed");
296           /* Buffer overflow check (should never happen) */
297           if (!buf_safe (&work, buf->len))
298             CRYPT_ERROR ("buffer overflow");
300           /* Decrypt packet ID, payload */
301           if (!EVP_CipherUpdate_ov (ctx->cipher, BPTR (&work), &outlen, BPTR (buf), BLEN (buf)))
302             CRYPT_ERROR ("cipher update failed");
303           work.len += outlen;
305           /* Flush the decryption buffer */
306           if (!EVP_CipherFinal (ctx->cipher, BPTR (&work) + outlen, &outlen))
307             CRYPT_ERROR ("cipher final failed");
308           work.len += outlen;
310           dmsg (D_PACKET_CONTENT, "DECRYPT TO: %s",
311                format_hex (BPTR (&work), BLEN (&work), 80, &gc));
313           /* Get packet ID from plaintext buffer or IV, depending on cipher mode */
314           {
315             if (mode == EVP_CIPH_CBC_MODE)
316               {
317                 if (opt->packet_id)
318                   {
319                     if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
320                       CRYPT_ERROR ("error reading CBC packet-id");
321                     have_pin = true;
322                   }
323               }
324             else if (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE)
325               {
326                 struct buffer b;
328                 ASSERT (opt->flags & CO_USE_IV);    /* IV and packet-ID required */
329                 ASSERT (opt->packet_id); /*  for this mode. */
331                 buf_set_read (&b, iv_buf, iv_size);
332                 if (!packet_id_read (&pin, &b, true))
333                   CRYPT_ERROR ("error reading CFB/OFB packet-id");
334                 have_pin = true;
335               }
336             else /* We only support CBC, CFB, or OFB modes right now */
337               {
338                 ASSERT (0);
339               }
340           }
341         }
342       else
343         {
344           work = *buf;
345           if (opt->packet_id)
346             {
347               if (!packet_id_read (&pin, &work, BOOL_CAST (opt->flags & CO_PACKET_ID_LONG_FORM)))
348                 CRYPT_ERROR ("error reading packet-id");
349               have_pin = !BOOL_CAST (opt->flags & CO_IGNORE_PACKET_ID);
350             }
351         }
352       
353       if (have_pin)
354         {
355           packet_id_reap_test (&opt->packet_id->rec);
356           if (packet_id_test (&opt->packet_id->rec, &pin))
357             {
358               packet_id_add (&opt->packet_id->rec, &pin);
359               if (opt->pid_persist && (opt->flags & CO_PACKET_ID_LONG_FORM))
360                 packet_id_persist_save_obj (opt->pid_persist, opt->packet_id);
361             }
362           else
363             {
364               if (!(opt->flags & CO_MUTE_REPLAY_WARNINGS))
365               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",
366                    error_prefix, packet_id_net_print (&pin, true, &gc));
367               goto error_exit;
368             }
369         }
370       *buf = work;
371     }
373   gc_free (&gc);
374   return true;
376  error_exit:
377   ERR_clear_error ();
378   buf->len = 0;
379   gc_free (&gc);
380   return false;
384  * How many bytes will we add to frame buffer for a given
385  * set of crypto options?
386  */
387 void
388 crypto_adjust_frame_parameters(struct frame *frame,
389                                const struct key_type* kt,
390                                bool cipher_defined,
391                                bool use_iv,
392                                bool packet_id,
393                                bool packet_id_long_form)
395   frame_add_to_extra_frame (frame,
396                             (packet_id ? packet_id_size (packet_id_long_form) : 0) +
397                             ((cipher_defined && use_iv) ? EVP_CIPHER_iv_length (kt->cipher) : 0) +
398                             (cipher_defined ? EVP_CIPHER_block_size (kt->cipher) : 0) + /* worst case padding expansion */
399                             kt->hmac_length);
402 static const EVP_CIPHER *
403 get_cipher (const char *ciphername)
405   const EVP_CIPHER *cipher = NULL;
406   ASSERT (ciphername);
407   cipher = EVP_get_cipherbyname (ciphername);
408   if ( !(cipher && cipher_ok (OBJ_nid2sn (EVP_CIPHER_nid (cipher)))))
409     msg (M_SSLERR, "Cipher algorithm '%s' not found", ciphername);
410   if (EVP_CIPHER_key_length (cipher) > MAX_CIPHER_KEY_LENGTH)
411     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)",
412          ciphername,
413          EVP_CIPHER_key_length (cipher),
414          MAX_CIPHER_KEY_LENGTH);
415   return cipher;
418 static const EVP_MD *
419 get_md (const char *digest)
421   const EVP_MD *md = NULL;
422   ASSERT (digest);
423   md = EVP_get_digestbyname (digest);
424   if (!md)
425     msg (M_SSLERR, "Message hash algorithm '%s' not found", digest);
426   if (EVP_MD_size (md) > MAX_HMAC_KEY_LENGTH)
427     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)",
428          digest,
429          EVP_MD_size (md),
430          MAX_HMAC_KEY_LENGTH);
431   return md;
434 static void
435 init_cipher (EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
436              struct key *key, const struct key_type *kt, int enc,
437              const char *prefix)
439   struct gc_arena gc = gc_new ();
441   EVP_CIPHER_CTX_init (ctx);
442   if (!EVP_CipherInit_ov (ctx, cipher, NULL, NULL, enc))
443     msg (M_SSLERR, "EVP cipher init #1");
444 #ifdef HAVE_EVP_CIPHER_CTX_SET_KEY_LENGTH
445   if (!EVP_CIPHER_CTX_set_key_length (ctx, kt->cipher_length))
446     msg (M_SSLERR, "EVP set key size");
447 #endif
448   if (!EVP_CipherInit_ov (ctx, NULL, key->cipher, NULL, enc))
449     msg (M_SSLERR, "EVP cipher init #2");
451   msg (D_HANDSHAKE, "%s: Cipher '%s' initialized with %d bit key",
452        prefix,
453        OBJ_nid2sn (EVP_CIPHER_CTX_nid (ctx)),
454        EVP_CIPHER_CTX_key_length (ctx) * 8);
456   /* make sure we used a big enough key */
457   ASSERT (EVP_CIPHER_CTX_key_length (ctx) <= kt->cipher_length);
459   dmsg (D_SHOW_KEYS, "%s: CIPHER KEY: %s", prefix,
460        format_hex (key->cipher, kt->cipher_length, 0, &gc));
461   dmsg (D_CRYPTO_DEBUG, "%s: CIPHER block_size=%d iv_size=%d",
462        prefix,
463        EVP_CIPHER_CTX_block_size (ctx),
464        EVP_CIPHER_CTX_iv_length (ctx));
466   gc_free (&gc);
469 static void
470 init_hmac (HMAC_CTX *ctx, const EVP_MD *digest,
471            struct key *key, const struct key_type *kt, const char *prefix)
473   struct gc_arena gc = gc_new ();
475   HMAC_CTX_init (ctx);
476   HMAC_Init_ex (ctx, key->hmac, kt->hmac_length, digest, NULL);
477   msg (D_HANDSHAKE,
478        "%s: Using %d bit message hash '%s' for HMAC authentication",
479        prefix, HMAC_size (ctx) * 8, OBJ_nid2sn (EVP_MD_type (digest)));
481   /* make sure we used a big enough key */
482   ASSERT (HMAC_size (ctx) <= kt->hmac_length);
484   dmsg (D_SHOW_KEYS, "%s: HMAC KEY: %s", prefix,
485        format_hex (key->hmac, kt->hmac_length, 0, &gc));
486   dmsg (D_CRYPTO_DEBUG, "%s: HMAC size=%d block_size=%d",
487        prefix,
488        EVP_MD_size (digest),
489        EVP_MD_block_size (digest));
491   gc_free (&gc);
495  * Build a struct key_type.
496  */
497 void
498 init_key_type (struct key_type *kt, const char *ciphername,
499                bool ciphername_defined, const char *authname,
500                bool authname_defined, int keysize,
501                bool cfb_ofb_allowed, bool warn)
503   CLEAR (*kt);
504   if (ciphername && ciphername_defined)
505     {
506       kt->cipher = get_cipher (ciphername);
507       kt->cipher_length = EVP_CIPHER_key_length (kt->cipher);
508       if (keysize > 0 && keysize <= MAX_CIPHER_KEY_LENGTH)
509         kt->cipher_length = keysize;
511       /* check legal cipher mode */
512       {
513         const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
514         if (!(mode == EVP_CIPH_CBC_MODE
515 #ifdef ALLOW_NON_CBC_CIPHERS
516               || (cfb_ofb_allowed && (mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE))
517 #endif
518               ))
519 #ifdef ENABLE_SMALL
520           msg (M_FATAL, "Cipher '%s' mode not supported", ciphername);
521 #else
522           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);
523 #endif
524       }
525     }
526   else
527     {
528       if (warn)
529         msg (M_WARN, "******* WARNING *******: null cipher specified, no encryption will be used");
530     }
531   if (authname && authname_defined)
532     {
533       kt->digest = get_md (authname);
534       kt->hmac_length = EVP_MD_size (kt->digest);
535     }
536   else
537     {
538       if (warn)
539         msg (M_WARN, "******* WARNING *******: null MAC specified, no authentication will be used");
540     }
543 const char *
544 kt_cipher_name (const struct key_type *kt)
546   if (kt->cipher)
547     return EVP_CIPHER_name (kt->cipher);
548   else
549     return "[null-cipher]";
552 const char *
553 kt_digest_name (const struct key_type *kt)
555   if (kt->digest)
556     return EVP_MD_name (kt->digest);
557   else
558     return "[null-digest]";
562 kt_key_size (const struct key_type *kt)
564   if (kt->cipher_length)
565     return kt->cipher_length * 8;
566   else if (kt->cipher)
567     return EVP_CIPHER_key_length (kt->cipher) * 8;
568   else
569     return 0;
572 /* given a key and key_type, build a key_ctx */
573 void
574 init_key_ctx (struct key_ctx *ctx, struct key *key,
575               const struct key_type *kt, int enc,
576               const char *prefix)
578   CLEAR (*ctx);
579   if (kt->cipher && kt->cipher_length > 0)
580     {
581       ALLOC_OBJ (ctx->cipher, EVP_CIPHER_CTX);
582       init_cipher (ctx->cipher, kt->cipher, key, kt, enc, prefix);
583     }
584   if (kt->digest && kt->hmac_length > 0)
585     {
586       ALLOC_OBJ (ctx->hmac, HMAC_CTX);
587       init_hmac (ctx->hmac, kt->digest, key, kt, prefix);
588     }
591 void
592 free_key_ctx (struct key_ctx *ctx)
594   if (ctx->cipher)
595     {
596       EVP_CIPHER_CTX_cleanup (ctx->cipher);
597       free (ctx->cipher);
598       ctx->cipher = NULL;
599     }
600   if (ctx->hmac)
601     {
602       HMAC_CTX_cleanup (ctx->hmac);
603       free (ctx->hmac);
604       ctx->hmac = NULL;
605     }
608 void
609 free_key_ctx_bi (struct key_ctx_bi *ctx)
611   free_key_ctx(&ctx->encrypt);
612   free_key_ctx(&ctx->decrypt);
616  * Return number of DES cblocks for the current
617  * key type or 0 if not a DES cipher.
618  */
619 static int
620 n_DES_cblocks (const struct key_type *kt)
622   int ret = 0;
623   const char *name = OBJ_nid2sn (EVP_CIPHER_nid (kt->cipher));
624   if (name)
625     {
626       if (!strncmp (name, "DES-", 4))
627         {
628           ret = EVP_CIPHER_key_length (kt->cipher) / sizeof (DES_cblock);
629         }
630       else if (!strncmp (name, "DESX-", 5))
631         {
632           ret = 1;
633         }
634     }
635   dmsg (D_CRYPTO_DEBUG, "CRYPTO INFO: n_DES_cblocks=%d", ret);
636   return ret;
639 static bool
640 check_key_DES (struct key *key, const struct key_type *kt, int ndc)
642   int i;
643   struct buffer b;
645   buf_set_read (&b, key->cipher, kt->cipher_length);
647   for (i = 0; i < ndc; ++i)
648     {
649       DES_cblock *dc = (DES_cblock*) buf_read_alloc (&b, sizeof (DES_cblock));
650       if (!dc)
651         {
652           msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: insufficient key material");
653           goto err;
654         }
655       if (DES_is_weak_key(dc))
656         {
657           msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: weak key detected");
658           goto err;
659         }
660       if (!DES_check_key_parity (dc))
661         {
662           msg (D_CRYPT_ERRORS, "CRYPTO INFO: check_key_DES: bad parity detected");
663           goto err;
664         }
665     }
666   return true;
668  err:
669   ERR_clear_error ();
670   return false;
673 static void
674 fixup_key_DES (struct key *key, const struct key_type *kt, int ndc)
676   int i;
677   struct buffer b;
679   buf_set_read (&b, key->cipher, kt->cipher_length);
680   for (i = 0; i < ndc; ++i)
681     {
682       DES_cblock *dc = (DES_cblock*) buf_read_alloc(&b, sizeof(DES_cblock));
683       if (!dc)
684         {
685           msg (D_CRYPT_ERRORS, "CRYPTO INFO: fixup_key_DES: insufficient key material");
686           ERR_clear_error ();
687           return;
688         }
689       DES_set_odd_parity (dc);
690     }
693 static bool
694 key_is_zero (struct key *key, const struct key_type *kt)
696   int i;
697   for (i = 0; i < kt->cipher_length; ++i)
698     if (key->cipher[i])
699       return false;
700   msg (D_CRYPT_ERRORS, "CRYPTO INFO: WARNING: zero key detected");
701   return true;
705  * Make sure that cipher key is a valid key for current key_type.
706  */
707 bool
708 check_key (struct key *key, const struct key_type *kt)
710   if (kt->cipher)
711     {
712       /*
713        * Check for zero key
714        */
715       if (key_is_zero(key, kt))
716         return false;
718       /*
719        * Check for weak or semi-weak DES keys.
720        */
721       {
722         const int ndc = n_DES_cblocks (kt);
723         if (ndc)
724           return check_key_DES (key, kt, ndc);
725         else
726           return true;
727       }
728     }
729   return true;
733  * Make safe mutations to key to ensure it is valid,
734  * such as ensuring correct parity on DES keys.
736  * This routine cannot guarantee it will generate a good
737  * key.  You must always call check_key after this routine
738  * to make sure.
739  */ 
740 void
741 fixup_key (struct key *key, const struct key_type *kt)
743   struct gc_arena gc = gc_new ();
744   if (kt->cipher)
745     {
746 #ifdef ENABLE_DEBUG
747       const struct key orig = *key;
748 #endif
749       const int ndc = n_DES_cblocks (kt);
751       if (ndc)
752         fixup_key_DES (key, kt, ndc);
754 #ifdef ENABLE_DEBUG
755       if (check_debug_level (D_CRYPTO_DEBUG))
756         {
757           if (memcmp (orig.cipher, key->cipher, kt->cipher_length))
758             dmsg (D_CRYPTO_DEBUG, "CRYPTO INFO: fixup_key: before=%s after=%s",
759                  format_hex (orig.cipher, kt->cipher_length, 0, &gc),
760                  format_hex (key->cipher, kt->cipher_length, 0, &gc));
761         }
762 #endif
763     }
764   gc_free (&gc);
767 void
768 check_replay_iv_consistency (const struct key_type *kt, bool packet_id, bool use_iv)
770   if (cfb_ofb_mode (kt) && !(packet_id && use_iv))
771     msg (M_FATAL, "--no-replay or --no-iv cannot be used with a CFB or OFB mode cipher");
774 bool
775 cfb_ofb_mode (const struct key_type* kt)
777   if (kt->cipher) {
778     const unsigned int mode = EVP_CIPHER_mode (kt->cipher);
779     return mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE;
780   } else
781     return false;
785  * Generate a random key.  If key_type is provided, make
786  * sure generated key is valid for key_type.
787  */
788 void
789 generate_key_random (struct key *key, const struct key_type *kt)
791   int cipher_len = MAX_CIPHER_KEY_LENGTH;
792   int hmac_len = MAX_HMAC_KEY_LENGTH;
794   struct gc_arena gc = gc_new ();
796   do {
797     CLEAR (*key);
798     if (kt)
799       {
800         if (kt->cipher && kt->cipher_length > 0 && kt->cipher_length <= cipher_len)
801           cipher_len = kt->cipher_length;
803         if (kt->digest && kt->hmac_length > 0 && kt->hmac_length <= hmac_len)
804           hmac_len = kt->hmac_length;
805       }
806     if (!RAND_bytes (key->cipher, cipher_len)
807         || !RAND_bytes (key->hmac, hmac_len))
808       msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation");
810     dmsg (D_SHOW_KEY_SOURCE, "Cipher source entropy: %s", format_hex (key->cipher, cipher_len, 0, &gc));
811     dmsg (D_SHOW_KEY_SOURCE, "HMAC source entropy: %s", format_hex (key->hmac, hmac_len, 0, &gc));
813     if (kt)
814       fixup_key (key, kt);
815   } while (kt && !check_key (key, kt));
817   gc_free (&gc);
821  * Print key material
822  */
823 void
824 key2_print (const struct key2* k,
825             const struct key_type *kt,
826             const char* prefix0,
827             const char* prefix1)
829   struct gc_arena gc = gc_new ();
830   ASSERT (k->n == 2);
831   dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
832        prefix0,
833        format_hex (k->keys[0].cipher, kt->cipher_length, 0, &gc));
834   dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
835        prefix0,
836        format_hex (k->keys[0].hmac, kt->hmac_length, 0, &gc));
837   dmsg (D_SHOW_KEY_SOURCE, "%s (cipher): %s",
838        prefix1,
839        format_hex (k->keys[1].cipher, kt->cipher_length, 0, &gc));
840   dmsg (D_SHOW_KEY_SOURCE, "%s (hmac): %s",
841        prefix1,
842        format_hex (k->keys[1].hmac, kt->hmac_length, 0, &gc));
843   gc_free (&gc);
846 void
847 test_crypto (const struct crypto_options *co, struct frame* frame)
849   int i, j;
850   struct gc_arena gc = gc_new ();
851   struct buffer src = alloc_buf_gc (TUN_MTU_SIZE (frame), &gc);
852   struct buffer work = alloc_buf_gc (BUF_SIZE (frame), &gc);
853   struct buffer encrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc);
854   struct buffer decrypt_workspace = alloc_buf_gc (BUF_SIZE (frame), &gc);
855   struct buffer buf = clear_buf();
857   /* init work */
858   ASSERT (buf_init (&work, FRAME_HEADROOM (frame)));
860   msg (M_INFO, "Entering " PACKAGE_NAME " crypto self-test mode.");
861   for (i = 1; i <= TUN_MTU_SIZE (frame); ++i)
862     {
863       update_time ();
865       msg (M_INFO, "TESTING ENCRYPT/DECRYPT of packet length=%d", i);
867       /*
868        * Load src with random data.
869        */
870       ASSERT (buf_init (&src, 0));
871       ASSERT (i <= src.capacity);
872       src.len = i;
873       ASSERT (RAND_pseudo_bytes (BPTR (&src), BLEN (&src)));
875       /* copy source to input buf */
876       buf = work;
877       memcpy (buf_write_alloc (&buf, BLEN (&src)), BPTR (&src), BLEN (&src));
879       /* encrypt */
880       openvpn_encrypt (&buf, encrypt_workspace, co, frame);
882       /* decrypt */
883       openvpn_decrypt (&buf, decrypt_workspace, co, frame);
885       /* compare */
886       if (buf.len != src.len)
887         msg (M_FATAL, "SELF TEST FAILED, src.len=%d buf.len=%d", src.len, buf.len);
888       for (j = 0; j < i; ++j)
889         {
890           const uint8_t in = *(BPTR (&src) + j);
891           const uint8_t out = *(BPTR (&buf) + j);
892           if (in != out)
893             msg (M_FATAL, "SELF TEST FAILED, pos=%d in=%d out=%d", j, in, out);
894         }
895     }
896   msg (M_INFO, PACKAGE_NAME " crypto self-test mode SUCCEEDED.");
897   gc_free (&gc);
900 #ifdef USE_SSL
902 void
903 get_tls_handshake_key (const struct key_type *key_type,
904                        struct key_ctx_bi *ctx,
905                        const char *passphrase_file,
906                        const int key_direction,
907                        const unsigned int flags)
909   if (passphrase_file && key_type->hmac_length)
910     {
911       struct key2 key2;
912       struct key_type kt = *key_type;
913       struct key_direction_state kds;
915       /* for control channel we are only authenticating, not encrypting */
916       kt.cipher_length = 0;
917       kt.cipher = NULL;
919 #if ENABLE_INLINE_FILES
920       if (flags & GHK_INLINE)
921         {
922           /* key was specified inline, key text is in passphrase_file */
923           read_key_file (&key2, passphrase_file, RKF_INLINE|RKF_MUST_SUCCEED);
925           /* succeeded? */
926           if (key2.n == 2)
927             msg (M_INFO, "Control Channel Authentication: tls-auth using INLINE static key file");
928           else
929             msg (M_FATAL, "INLINE tls-auth file lacks the requisite 2 keys");
930         }
931       else
932 #endif
933       {
934         /* first try to parse as an OpenVPN static key file */
935         read_key_file (&key2, passphrase_file, 0);
937         /* succeeded? */
938         if (key2.n == 2)
939           {
940             msg (M_INFO,
941                  "Control Channel Authentication: using '%s' as a " PACKAGE_NAME " static key file",
942                  passphrase_file);
943           }
944         else
945           {
946             int hash_size;
948             CLEAR (key2);
950             /* failed, now try to get hash from a freeform file */
951             hash_size = read_passphrase_hash (passphrase_file,
952                                               kt.digest,
953                                               key2.keys[0].hmac,
954                                               MAX_HMAC_KEY_LENGTH);
955             ASSERT (hash_size == kt.hmac_length);
957             /* suceeded */
958             key2.n = 1;
960             msg (M_INFO,
961                  "Control Channel Authentication: using '%s' as a free-form passphrase file",
962                  passphrase_file);
963           }
964       }
965       /* handle key direction */
967       key_direction_state_init (&kds, key_direction);
968       must_have_n_keys (passphrase_file, "tls-auth", &key2, kds.need_keys);
970       /* initialize hmac key in both directions */
972       init_key_ctx (&ctx->encrypt, &key2.keys[kds.out_key], &kt, DO_ENCRYPT,
973                     "Outgoing Control Channel Authentication");
974       init_key_ctx (&ctx->decrypt, &key2.keys[kds.in_key], &kt, DO_DECRYPT,
975                     "Incoming Control Channel Authentication");
977       CLEAR (key2);
978     }
979   else
980     {
981       CLEAR (*ctx);
982     }
984 #endif
986 /* header and footer for static key file */
987 static const char static_key_head[] = "-----BEGIN " PACKAGE_NAME " Static key V1-----";
988 static const char static_key_foot[] = "-----END " PACKAGE_NAME " Static key V1-----";
990 static const char printable_char_fmt[] =
991   "Non-Hex character ('%c') found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
993 static const char unprintable_char_fmt[] =
994   "Non-Hex, unprintable character (0x%02x) found at line %d in key file '%s' (%d/%d/%d bytes found/min/max)";
996 /* read key from file */
998 void
999 read_key_file (struct key2 *key2, const char *file, const unsigned int flags)
1001   struct gc_arena gc = gc_new ();
1002   struct buffer in;
1003   int fd, size;
1004   uint8_t hex_byte[3] = {0, 0, 0};
1005   const char *error_filename = file;
1007   /* parse info */
1008   const unsigned char *cp;
1009   int hb_index = 0;
1010   int line_num = 1;
1011   int line_index = 0;
1012   int match = 0;
1014   /* output */
1015   uint8_t* out = (uint8_t*) &key2->keys;
1016   const int keylen = sizeof (key2->keys);
1017   int count = 0;
1019   /* parse states */
1020 # define PARSE_INITIAL        0
1021 # define PARSE_HEAD           1
1022 # define PARSE_DATA           2
1023 # define PARSE_DATA_COMPLETE  3
1024 # define PARSE_FOOT           4
1025 # define PARSE_FINISHED       5
1026   int state = PARSE_INITIAL;
1028   /* constants */
1029   const int hlen = strlen (static_key_head);
1030   const int flen = strlen (static_key_foot);
1031   const int onekeylen = sizeof (key2->keys[0]);
1033   CLEAR (*key2);
1035   /*
1036    * Key can be provided as a filename in 'file' or if RKF_INLINE
1037    * is set, the actual key data itself in ascii form.
1038    */
1039 #if ENABLE_INLINE_FILES
1040   if (flags & RKF_INLINE) /* 'file' is a string containing ascii representation of key */
1041     {
1042       size = strlen (file) + 1;
1043       buf_set_read (&in, (const uint8_t *)file, size);
1044       error_filename = INLINE_FILE_TAG;
1045     }
1046   else /* 'file' is a filename which refers to a file containing the ascii key */
1047 #endif
1048     {
1049       in = alloc_buf_gc (2048, &gc);
1050       fd = open (file, O_RDONLY);
1051       if (fd == -1)
1052         msg (M_ERR, "Cannot open file key file '%s'", file);
1053       size = read (fd, in.data, in.capacity);
1054       if (size < 0)
1055         msg (M_FATAL, "Read error on key file ('%s')", file);
1056       if (size == in.capacity)
1057         msg (M_FATAL, "Key file ('%s') can be a maximum of %d bytes", file, (int)in.capacity);
1058       close (fd);
1059     }
1061   cp = (unsigned char *)in.data;
1062   while (size > 0)
1063     {
1064       const unsigned char c = *cp;
1066 #if 0
1067       msg (M_INFO, "char='%c' s=%d ln=%d li=%d m=%d c=%d",
1068            c, state, line_num, line_index, match, count);
1069 #endif
1071       if (c == '\n')
1072         {
1073           line_index = match = 0;
1074           ++line_num;         
1075         }
1076       else
1077         {
1078           /* first char of new line */
1079           if (!line_index)
1080             {
1081               /* first char of line after header line? */
1082               if (state == PARSE_HEAD)
1083                 state = PARSE_DATA;
1085               /* first char of footer */
1086               if ((state == PARSE_DATA || state == PARSE_DATA_COMPLETE) && c == '-')
1087                 state = PARSE_FOOT;
1088             }
1090           /* compare read chars with header line */
1091           if (state == PARSE_INITIAL)
1092             {
1093               if (line_index < hlen && c == static_key_head[line_index])
1094                 {
1095                   if (++match == hlen)
1096                     state = PARSE_HEAD;
1097                 }
1098             }
1100           /* compare read chars with footer line */
1101           if (state == PARSE_FOOT)
1102             {
1103               if (line_index < flen && c == static_key_foot[line_index])
1104                 {
1105                   if (++match == flen)
1106                     state = PARSE_FINISHED;
1107                 }
1108             }
1110           /* reading key */
1111           if (state == PARSE_DATA)
1112             {
1113               if (isxdigit(c))
1114                 {
1115                   ASSERT (hb_index >= 0 && hb_index < 2);
1116                   hex_byte[hb_index++] = c;
1117                   if (hb_index == 2)
1118                     {
1119                       unsigned int u;
1120                       ASSERT(sscanf((const char *)hex_byte, "%x", &u) == 1);
1121                       *out++ = u;
1122                       hb_index = 0;
1123                       if (++count == keylen)
1124                         state = PARSE_DATA_COMPLETE;
1125                     }
1126                 }
1127               else if (isspace(c))
1128                 ;
1129               else
1130                 {
1131                   msg (M_FATAL,
1132                        (isprint (c) ? printable_char_fmt : unprintable_char_fmt),
1133                        c, line_num, error_filename, count, onekeylen, keylen);
1134                 }
1135             }
1136           ++line_index;
1137         }
1138       ++cp;
1139       --size;
1140     }
1142   /*
1143    * Normally we will read either 1 or 2 keys from file.
1144    */
1145   key2->n = count / onekeylen;
1147   ASSERT (key2->n >= 0 && key2->n <= (int) SIZE (key2->keys));
1149   if (flags & RKF_MUST_SUCCEED)
1150     {
1151       if (!key2->n)
1152         msg (M_FATAL, "Insufficient key material or header text not found found in file '%s' (%d/%d/%d bytes found/min/max)",
1153              error_filename, count, onekeylen, keylen);
1155       if (state != PARSE_FINISHED)
1156         msg (M_FATAL, "Footer text not found in file '%s' (%d/%d/%d bytes found/min/max)",
1157              error_filename, count, onekeylen, keylen);
1158     }
1160   /* zero file read buffer if not an inline file */
1161 #if ENABLE_INLINE_FILES
1162   if (!(flags & RKF_INLINE))
1163 #endif
1164     buf_clear (&in);
1166   if (key2->n)
1167     warn_if_group_others_accessible (error_filename);
1169 #if 0
1170   /* DEBUGGING */
1171   {
1172     int i;
1173     printf ("KEY READ, n=%d\n", key2->n);
1174     for (i = 0; i < (int) SIZE (key2->keys); ++i)
1175       {
1176         /* format key as ascii */
1177         const char *fmt = format_hex_ex ((const uint8_t*)&key2->keys[i],
1178                                          sizeof (key2->keys[i]),
1179                                          0,
1180                                          16,
1181                                          "\n",
1182                                          &gc);
1183         printf ("[%d]\n%s\n\n", i, fmt);
1184       }
1185   }
1186 #endif
1188   /* pop our garbage collection level */
1189   gc_free (&gc);
1193 read_passphrase_hash (const char *passphrase_file,
1194                       const EVP_MD *digest,
1195                       uint8_t *output,
1196                       int len)
1198   unsigned int outlen = 0;
1199   EVP_MD_CTX md;
1201   ASSERT (len >= EVP_MD_size (digest));
1202   memset (output, 0, len);
1204   EVP_DigestInit (&md, digest);
1206   /* read passphrase file */
1207   {
1208     const int min_passphrase_size = 8;
1209     uint8_t buf[64];
1210     int total_size = 0;
1211     int fd = open (passphrase_file, O_RDONLY);
1213     if (fd == -1)
1214       msg (M_ERR, "Cannot open passphrase file: '%s'", passphrase_file);
1216     for (;;)
1217       {
1218         int size = read (fd, buf, sizeof (buf));
1219         if (size == 0)
1220           break;
1221         if (size == -1)
1222           msg (M_ERR, "Read error on passphrase file: '%s'",
1223                passphrase_file);
1224         EVP_DigestUpdate (&md, buf, size);
1225         total_size += size;
1226       }
1227     close (fd);
1229     warn_if_group_others_accessible (passphrase_file);
1231     if (total_size < min_passphrase_size)
1232       msg (M_FATAL,
1233            "Passphrase file '%s' is too small (must have at least %d characters)",
1234            passphrase_file, min_passphrase_size);
1235   }
1237   EVP_DigestFinal (&md, output, &outlen);
1238   EVP_MD_CTX_cleanup (&md);
1239   return outlen;
1243  * Write key to file, return number of random bits
1244  * written.
1245  */
1247 write_key_file (const int nkeys, const char *filename)
1249   struct gc_arena gc = gc_new ();
1251   int fd, i;
1252   int nbits = 0;
1254   /* must be large enough to hold full key file */
1255   struct buffer out = alloc_buf_gc (2048, &gc);
1256   struct buffer nbits_head_text = alloc_buf_gc (128, &gc);
1258   /* how to format the ascii file representation of key */
1259   const int bytes_per_line = 16;
1261   /* open key file */
1262   fd = open (filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR);
1264   if (fd == -1)
1265     msg (M_ERR, "Cannot open shared secret file '%s' for write", filename);
1267   buf_printf (&out, "%s\n", static_key_head);
1269   for (i = 0; i < nkeys; ++i)
1270     {
1271       struct key key;
1272       char* fmt;
1274       /* generate random bits */
1275       generate_key_random (&key, NULL);
1277       /* format key as ascii */
1278       fmt = format_hex_ex ((const uint8_t*)&key,
1279                            sizeof (key),
1280                            0,
1281                            bytes_per_line,
1282                            "\n",
1283                            &gc);
1285       /* increment random bits counter */
1286       nbits += sizeof (key) * 8;
1288       /* write to holding buffer */
1289       buf_printf (&out, "%s\n", fmt);
1291       /* zero memory which held key component (will be freed by GC) */
1292       memset (fmt, 0, strlen(fmt));
1293       CLEAR (key);
1294     }
1296   buf_printf (&out, "%s\n", static_key_foot);
1298   /* write number of bits */
1299   buf_printf (&nbits_head_text, "#\n# %d bit " PACKAGE_NAME " static key\n#\n", nbits);
1300   buf_write_string_file (&nbits_head_text, filename, fd);
1302   /* write key file, now formatted in out, to file */
1303   buf_write_string_file (&out, filename, fd);
1305   if (close (fd))
1306     msg (M_ERR, "Close error on shared secret file %s", filename);
1308   /* zero memory which held file content (memory will be freed by GC) */
1309   buf_clear (&out);
1311   /* pop our garbage collection level */
1312   gc_free (&gc);
1314   return nbits;
1317 void
1318 must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n)
1320   if (key2->n < n)
1321     {
1322 #ifdef ENABLE_SMALL
1323       msg (M_FATAL, "Key file '%s' used in --%s contains insufficient key material [keys found=%d required=%d]", filename, option, key2->n, n);
1324 #else
1325       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);
1326 #endif
1327     }
1331 ascii2keydirection (int msglevel, const char *str)
1333   if (!str)
1334     return KEY_DIRECTION_BIDIRECTIONAL;
1335   else if (!strcmp (str, "0"))
1336     return KEY_DIRECTION_NORMAL;
1337   else if (!strcmp (str, "1"))
1338     return KEY_DIRECTION_INVERSE;
1339   else
1340     {
1341       msg (msglevel, "Unknown key direction '%s' -- must be '0' or '1'", str);
1342       return -1;
1343     }
1344   return KEY_DIRECTION_BIDIRECTIONAL; /* NOTREACHED */
1347 const char *
1348 keydirection2ascii (int kd, bool remote)
1350   if (kd == KEY_DIRECTION_BIDIRECTIONAL)
1351     return NULL;
1352   else if (kd == KEY_DIRECTION_NORMAL)
1353     return remote ? "1" : "0";
1354   else if (kd == KEY_DIRECTION_INVERSE)
1355     return remote ? "0" : "1";
1356   else
1357     {
1358       ASSERT (0);
1359     }
1360   return NULL; /* NOTREACHED */
1363 void
1364 key_direction_state_init (struct key_direction_state *kds, int key_direction)
1366   CLEAR (*kds);
1367   switch (key_direction)
1368     {
1369     case KEY_DIRECTION_NORMAL:
1370       kds->out_key = 0;
1371       kds->in_key = 1;
1372       kds->need_keys = 2;
1373       break;
1374     case KEY_DIRECTION_INVERSE:
1375       kds->out_key = 1;
1376       kds->in_key = 0;
1377       kds->need_keys = 2;
1378       break;
1379     case KEY_DIRECTION_BIDIRECTIONAL:
1380       kds->out_key = 0;
1381       kds->in_key = 0;
1382       kds->need_keys = 1;
1383       break;
1384     default:
1385       ASSERT (0);
1386     }
1389 void
1390 verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
1392   int i;
1394   for (i = 0; i < key2->n; ++i)
1395     {
1396       /* Fix parity for DES keys and make sure not a weak key */
1397       fixup_key (&key2->keys[i], kt);
1399       /* This should be a very improbable failure */
1400       if (!check_key (&key2->keys[i], kt))
1401         msg (M_FATAL, "Key #%d in '%s' is bad.  Try making a new key with --genkey.",
1402              i+1, shared_secret_file);
1403     }
1406 /* given a key and key_type, write key to buffer */
1407 bool
1408 write_key (const struct key *key, const struct key_type *kt,
1409            struct buffer *buf)
1411   ASSERT (kt->cipher_length <= MAX_CIPHER_KEY_LENGTH
1412           && kt->hmac_length <= MAX_HMAC_KEY_LENGTH);
1414   if (!buf_write (buf, &kt->cipher_length, 1))
1415     return false;
1416   if (!buf_write (buf, &kt->hmac_length, 1))
1417     return false;
1418   if (!buf_write (buf, key->cipher, kt->cipher_length))
1419     return false;
1420   if (!buf_write (buf, key->hmac, kt->hmac_length))
1421     return false;
1423   return true;
1427  * Given a key_type and buffer, read key from buffer.
1428  * Return: 1 on success
1429  *        -1 read failure
1430  *         0 on key length mismatch 
1431  */
1433 read_key (struct key *key, const struct key_type *kt, struct buffer *buf)
1435   uint8_t cipher_length;
1436   uint8_t hmac_length;
1438   CLEAR (*key);
1439   if (!buf_read (buf, &cipher_length, 1))
1440     goto read_err;
1441   if (!buf_read (buf, &hmac_length, 1))
1442     goto read_err;
1444   if (!buf_read (buf, key->cipher, cipher_length))
1445     goto read_err;
1446   if (!buf_read (buf, key->hmac, hmac_length))
1447     goto read_err;
1449   if (cipher_length != kt->cipher_length || hmac_length != kt->hmac_length)
1450     goto key_len_err;
1452   return 1;
1454 read_err:
1455   msg (D_TLS_ERRORS, "TLS Error: error reading key from remote");
1456   return -1;
1458 key_len_err:
1459   msg (D_TLS_ERRORS,
1460        "TLS Error: key length mismatch, local cipher/hmac %d/%d, remote cipher/hmac %d/%d",
1461        kt->cipher_length, kt->hmac_length, cipher_length, hmac_length);
1462   return 0;
1465 void
1466 show_available_ciphers ()
1468   int nid;
1471 #ifndef ENABLE_SMALL
1472   printf ("The following ciphers and cipher modes are available\n"
1473           "for use with " PACKAGE_NAME ".  Each cipher shown below may be\n"
1474           "used as a parameter to the --cipher option.  The default\n"
1475           "key size is shown as well as whether or not it can be\n"
1476           "changed with the --keysize directive.  Using a CBC mode\n"
1477           "is recommended.\n\n");
1478 #endif
1480   for (nid = 0; nid < 10000; ++nid)     /* is there a better way to get the size of the nid list? */
1481     {
1482       const EVP_CIPHER *cipher = EVP_get_cipherbynid (nid);
1483       if (cipher && cipher_ok (OBJ_nid2sn (nid)))
1484         {
1485           const unsigned int mode = EVP_CIPHER_mode (cipher);
1486           if (mode == EVP_CIPH_CBC_MODE
1487 #ifdef ALLOW_NON_CBC_CIPHERS
1488               || mode == EVP_CIPH_CFB_MODE || mode == EVP_CIPH_OFB_MODE
1489 #endif
1490               )
1491             printf ("%s %d bit default key (%s)\n",
1492                     OBJ_nid2sn (nid),
1493                     EVP_CIPHER_key_length (cipher) * 8,
1494                     ((EVP_CIPHER_flags (cipher) & EVP_CIPH_VARIABLE_LENGTH) ?
1495                      "variable" : "fixed"));
1496         }
1497     }
1498   printf ("\n");
1501 void
1502 show_available_digests ()
1504   int nid;
1506 #ifndef ENABLE_SMALL
1507   printf ("The following message digests are available for use with\n"
1508           PACKAGE_NAME ".  A message digest is used in conjunction with\n"
1509           "the HMAC function, to authenticate received packets.\n"
1510           "You can specify a message digest as parameter to\n"
1511           "the --auth option.\n\n");
1512 #endif
1514   for (nid = 0; nid < 10000; ++nid)
1515     {
1516       const EVP_MD *digest = EVP_get_digestbynid (nid);
1517       if (digest)
1518         {
1519           printf ("%s %d bit digest size\n",
1520                   OBJ_nid2sn (nid), EVP_MD_size (digest) * 8);
1521         }
1522     }
1523   printf ("\n");
1526 void
1527 show_available_engines ()
1529 #if CRYPTO_ENGINE
1530   ENGINE *e;
1532   printf ("OpenSSL Crypto Engines\n\n");
1534   ENGINE_load_builtin_engines ();
1536   e = ENGINE_get_first ();
1537   while (e)
1538     {
1539       printf ("%s [%s]\n",
1540               ENGINE_get_name (e),
1541               ENGINE_get_id (e));
1542       e = ENGINE_get_next (e);
1543     }
1544   ENGINE_cleanup ();
1545 #else
1546   printf ("Sorry, OpenSSL hardware crypto engine functionality is not available.\n");
1547 #endif
1551  * Enable crypto acceleration, if available
1552  */
1554 static bool engine_initialized = false; /* GLOBAL */
1556 #if CRYPTO_ENGINE
1558 static ENGINE *engine_persist = NULL;   /* GLOBAL */
1560 /* Try to load an engine in a shareable library */
1561 static ENGINE *
1562 try_load_engine (const char *engine)
1564   ENGINE *e = ENGINE_by_id ("dynamic");
1565   if (e)
1566     {
1567       if (!ENGINE_ctrl_cmd_string (e, "SO_PATH", engine, 0)
1568           || !ENGINE_ctrl_cmd_string (e, "LOAD", NULL, 0))
1569         {
1570           ENGINE_free (e);
1571           e = NULL;
1572         }
1573     }
1574   return e;
1577 static ENGINE *
1578 setup_engine (const char *engine)
1580   ENGINE *e = NULL;
1582   ENGINE_load_builtin_engines ();
1584   if (engine)
1585     {
1586       if (strcmp (engine, "auto") == 0)
1587         {
1588           msg (M_INFO, "Initializing OpenSSL auto engine support");
1589           ENGINE_register_all_complete ();
1590           return NULL;
1591         }
1592       if ((e = ENGINE_by_id (engine)) == NULL
1593          && (e = try_load_engine (engine)) == NULL)
1594         {
1595           msg (M_FATAL, "OpenSSL error: cannot load engine '%s'", engine);
1596         }
1598       if (!ENGINE_set_default (e, ENGINE_METHOD_ALL))
1599         {
1600           msg (M_FATAL, "OpenSSL error: ENGINE_set_default failed on engine '%s'",
1601                engine);
1602         }
1604       msg (M_INFO, "Initializing OpenSSL support for engine '%s'",
1605            ENGINE_get_id (e));
1606     }
1607   return e;
1609 #endif
1611 void
1612 init_crypto_lib_engine (const char *engine_name)
1614   if (!engine_initialized)
1615     {
1616 #if CRYPTO_ENGINE
1617       ASSERT (engine_name);
1618       ASSERT (!engine_persist);
1619       engine_persist = setup_engine (engine_name);
1620 #else
1621       msg (M_WARN, "Note: OpenSSL hardware crypto engine functionality is not available");
1622 #endif
1623       engine_initialized = true;
1624     }
1628  * This routine should have additional OpenSSL crypto library initialisations
1629  * used by both crypto and ssl components of OpenVPN.
1630  */
1631 void init_crypto_lib ()
1635 void uninit_crypto_lib ()
1637 #if CRYPTO_ENGINE
1638   if (engine_initialized)
1639     {
1640       ENGINE_cleanup ();
1641       engine_persist = NULL;
1642       engine_initialized = false;
1643     }
1644 #endif
1645   prng_uninit ();
1649  * Random number functions, used in cases where we want
1650  * reasonably strong cryptographic random number generation
1651  * without depleting our entropy pool.  Used for random
1652  * IV values and a number of other miscellaneous tasks.
1653  */
1655 static uint8_t *nonce_data; /* GLOBAL */
1656 static const EVP_MD *nonce_md = NULL; /* GLOBAL */
1657 static int nonce_secret_len; /* GLOBAL */
1659 void
1660 prng_init (const char *md_name, const int nonce_secret_len_parm)
1662   prng_uninit ();
1663   nonce_md = md_name ? get_md (md_name) : NULL;
1664   if (nonce_md)
1665     {
1666       ASSERT (nonce_secret_len_parm >= NONCE_SECRET_LEN_MIN && nonce_secret_len_parm <= NONCE_SECRET_LEN_MAX);
1667       nonce_secret_len = nonce_secret_len_parm;
1668       {
1669         const int size = EVP_MD_size (nonce_md) + nonce_secret_len;
1670         dmsg (D_CRYPTO_DEBUG, "PRNG init md=%s size=%d", EVP_MD_name (nonce_md), size);
1671         nonce_data = (uint8_t*) malloc (size);
1672         check_malloc_return (nonce_data);
1673 #if 1 /* Must be 1 for real usage */
1674         if (!RAND_bytes (nonce_data, size))
1675           msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for PRNG");
1676 #else
1677         /* Only for testing -- will cause a predictable PRNG sequence */
1678         {
1679           int i;
1680           for (i = 0; i < size; ++i)
1681             nonce_data[i] = (uint8_t) i;
1682         }
1683 #endif
1684       }
1685     }
1688 void
1689 prng_uninit (void)
1691   free (nonce_data);
1692   nonce_data = NULL;
1693   nonce_md = NULL;
1694   nonce_secret_len = 0;
1697 void
1698 prng_bytes (uint8_t *output, int len)
1700   if (nonce_md)
1701     {
1702       EVP_MD_CTX ctx;
1703       const int md_size = EVP_MD_size (nonce_md);
1704       mutex_lock_static (L_PRNG);
1705       while (len > 0)
1706         {
1707           unsigned int outlen = 0;
1708           const int blen = min_int (len, md_size);
1709           EVP_DigestInit (&ctx, nonce_md);
1710           EVP_DigestUpdate (&ctx, nonce_data, md_size + nonce_secret_len);
1711           EVP_DigestFinal (&ctx, nonce_data, &outlen);
1712           ASSERT (outlen == md_size);
1713           EVP_MD_CTX_cleanup (&ctx);
1714           memcpy (output, nonce_data, blen);
1715           output += blen;
1716           len -= blen;
1717         }
1718       mutex_unlock_static (L_PRNG);
1719     }
1720   else
1721     RAND_bytes (output, len);
1724 /* an analogue to the random() function, but use prng_bytes */
1725 long int
1726 get_random()
1728   long int l;
1729   prng_bytes ((unsigned char *)&l, sizeof(l));
1730   if (l < 0)
1731     l = -l;
1732   return l;
1735 const char *
1736 md5sum (uint8_t *buf, int len, int n_print_chars, struct gc_arena *gc)
1738   uint8_t digest[MD5_DIGEST_LENGTH];
1739   MD5 (buf, len, digest);
1740   return format_hex (digest, MD5_DIGEST_LENGTH, n_print_chars, gc);
1744  * OpenSSL memory debugging.  If dmalloc debugging is enabled, tell
1745  * OpenSSL to use our private malloc/realloc/free functions so that
1746  * we can dispatch them to dmalloc.
1747  */
1749 #ifdef DMALLOC
1751 static void *
1752 crypto_malloc (size_t size, const char *file, int line)
1754   return dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
1757 static void *
1758 crypto_realloc (void *ptr, size_t size, const char *file, int line)
1760   return dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
1763 static void
1764 crypto_free (void *ptr)
1766   dmalloc_free (__FILE__, __LINE__, ptr, DMALLOC_FUNC_FREE);
1769 void
1770 openssl_dmalloc_init (void)
1772    CRYPTO_set_mem_ex_functions (crypto_malloc,
1773                                 crypto_realloc,
1774                                 crypto_free);
1777 #endif /* DMALLOC */
1779 #ifndef USE_SSL
1781 void
1782 init_ssl_lib (void)
1784   ERR_load_crypto_strings ();
1785   OpenSSL_add_all_algorithms ();
1786   init_crypto_lib ();
1789 void
1790 free_ssl_lib (void)
1792   uninit_crypto_lib ();
1793   EVP_cleanup ();
1794   ERR_free_strings ();
1797 #endif /* USE_SSL */
1798 #endif /* USE_CRYPTO */