OpenVPN
crypto_openssl.c
Go to the documentation of this file.
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-2023 OpenVPN Inc <sales@openvpn.net>
9  * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.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 along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24 
29 #ifdef HAVE_CONFIG_H
30 #include "config.h"
31 #endif
32 
33 #include "syshead.h"
34 
35 #if defined(ENABLE_CRYPTO_OPENSSL)
36 
37 #include "basic.h"
38 #include "buffer.h"
39 #include "integer.h"
40 #include "crypto.h"
41 #include "crypto_backend.h"
42 #include "openssl_compat.h"
43 
44 #include <openssl/conf.h>
45 #include <openssl/des.h>
46 #include <openssl/err.h>
47 #include <openssl/evp.h>
48 #include <openssl/objects.h>
49 #include <openssl/rand.h>
50 #include <openssl/ssl.h>
51 
52 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
53 #include <openssl/kdf.h>
54 #endif
55 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
56 #include <openssl/provider.h>
57 #endif
58 
59 #if defined(_WIN32) && defined(OPENSSL_NO_EC)
60 #error Windows build with OPENSSL_NO_EC: disabling EC key is not supported.
61 #endif
62 
63 #ifdef _MSC_VER
64 /* mute ossl3 deprecation warnings treated as errors in msvc */
65 #pragma warning(disable: 4996)
66 #endif
67 
68 /*
69  * Check for key size creepage.
70  */
71 
72 #if MAX_CIPHER_KEY_LENGTH < EVP_MAX_KEY_LENGTH
73 #warning Some OpenSSL EVP ciphers now support key lengths greater than MAX_CIPHER_KEY_LENGTH -- consider increasing MAX_CIPHER_KEY_LENGTH
74 #endif
75 
76 #if MAX_HMAC_KEY_LENGTH < EVP_MAX_MD_SIZE
77 #warning Some OpenSSL HMAC message digests now support key lengths greater than MAX_HMAC_KEY_LENGTH -- consider increasing MAX_HMAC_KEY_LENGTH
78 #endif
79 
80 #if HAVE_OPENSSL_ENGINE
81 #include <openssl/ui.h>
82 #include <openssl/engine.h>
83 
84 static bool engine_initialized = false; /* GLOBAL */
85 
86 static ENGINE *engine_persist = NULL; /* GLOBAL */
87 
88 /* Try to load an engine in a shareable library */
89 static ENGINE *
90 try_load_engine(const char *engine)
91 {
92  ENGINE *e = ENGINE_by_id("dynamic");
93  if (e)
94  {
95  if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0)
96  || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
97  {
98  ENGINE_free(e);
99  e = NULL;
100  }
101  }
102  return e;
103 }
104 
105 static ENGINE *
106 setup_engine(const char *engine)
107 {
108  ENGINE *e = NULL;
109 
110  ENGINE_load_builtin_engines();
111 
112  if (engine)
113  {
114  if (strcmp(engine, "auto") == 0)
115  {
116  msg(M_INFO, "Initializing OpenSSL auto engine support");
117  ENGINE_register_all_complete();
118  return NULL;
119  }
120  if ((e = ENGINE_by_id(engine)) == NULL
121  && (e = try_load_engine(engine)) == NULL)
122  {
123  crypto_msg(M_FATAL, "OpenSSL error: cannot load engine '%s'",
124  engine);
125  }
126 
127  if (!ENGINE_set_default(e, ENGINE_METHOD_ALL))
128  {
130  "OpenSSL error: ENGINE_set_default failed on engine '%s'",
131  engine);
132  }
133 
134  msg(M_INFO, "Initializing OpenSSL support for engine '%s'",
135  ENGINE_get_id(e));
136  }
137  return e;
138 }
139 
140 #endif /* HAVE_OPENSSL_ENGINE */
141 
142 void
143 crypto_init_lib_engine(const char *engine_name)
144 {
145 #if HAVE_OPENSSL_ENGINE
146  if (!engine_initialized)
147  {
148  ASSERT(engine_name);
149  ASSERT(!engine_persist);
150  engine_persist = setup_engine(engine_name);
151  engine_initialized = true;
152  }
153 #else /* if HAVE_OPENSSL_ENGINE */
154  msg(M_WARN, "Note: OpenSSL hardware crypto engine functionality is not available");
155 #endif
156 }
157 
158 provider_t *
159 crypto_load_provider(const char *provider)
160 {
161 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
162  /* Load providers into the default (NULL) library context */
163  OSSL_PROVIDER *prov = OSSL_PROVIDER_load(NULL, provider);
164  if (!prov)
165  {
166  crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
167  }
168  return prov;
169 #else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
170  msg(M_WARN, "Note: OpenSSL provider functionality is not available");
171  return NULL;
172 #endif
173 }
174 
175 void
176 crypto_unload_provider(const char *provname, provider_t *provider)
177 {
178 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
179  if (!OSSL_PROVIDER_unload(provider))
180  {
181  crypto_msg(M_FATAL, "failed to unload provider '%s'", provname);
182  }
183 #endif
184 }
185 
186 /*
187  *
188  * Functions related to the core crypto library
189  *
190  */
191 
192 void
194 {
195 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
196  OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
197 #else
198  OPENSSL_config(NULL);
199 #endif
200  /*
201  * If you build the OpenSSL library and OpenVPN with
202  * CRYPTO_MDEBUG, you will get a listing of OpenSSL
203  * memory leaks on program termination.
204  */
205 
206 #ifdef CRYPTO_MDEBUG
207  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
208 #endif
209 }
210 
211 void
213 {
214 #ifdef CRYPTO_MDEBUG
215  FILE *fp = fopen("sdlog", "w");
216  ASSERT(fp);
217  CRYPTO_mem_leaks_fp(fp);
218  fclose(fp);
219 #endif
220 
221 #if HAVE_OPENSSL_ENGINE
222  if (engine_initialized)
223  {
224  ENGINE_cleanup();
225  engine_persist = NULL;
226  engine_initialized = false;
227  }
228 #endif
229 }
230 
231 void
233 {
234  ERR_clear_error();
235 }
236 
237 void
238 crypto_print_openssl_errors(const unsigned int flags)
239 {
240  unsigned long err = 0;
241  int line, errflags;
242  const char *file, *data, *func;
243 
244  while ((err = ERR_get_error_all(&file, &line, &func, &data, &errflags)) != 0)
245  {
246  if (!(errflags & ERR_TXT_STRING))
247  {
248  data = "";
249  }
250 
251  /* Be more clear about frequently occurring "no shared cipher" error */
252  if (ERR_GET_REASON(err) == SSL_R_NO_SHARED_CIPHER)
253  {
254  msg(D_CRYPT_ERRORS, "TLS error: The server has no TLS ciphersuites "
255  "in common with the client. Your --tls-cipher setting might be "
256  "too restrictive.");
257  }
258  else if (ERR_GET_REASON(err) == SSL_R_UNSUPPORTED_PROTOCOL)
259  {
260  msg(D_CRYPT_ERRORS, "TLS error: Unsupported protocol. This typically "
261  "indicates that client and server have no common TLS version enabled. "
262  "This can be caused by mismatched tls-version-min and tls-version-max "
263  "options on client and server. "
264  "If your OpenVPN client is between v2.3.6 and v2.3.2 try adding "
265  "tls-version-min 1.0 to the client configuration to use TLS 1.0+ "
266  "instead of TLS 1.0 only");
267  }
268 
269  /* print file and line if verb >=8 */
271  {
272  msg(flags, "OpenSSL: %s:%s", ERR_error_string(err, NULL), data);
273  }
274  else
275  {
276  msg(flags, "OpenSSL: %s:%s:%s:%d:%s", ERR_error_string(err, NULL),
277  data, file, line, func);
278  }
279  }
280 }
281 
282 
283 /*
284  *
285  * OpenSSL memory debugging. If dmalloc debugging is enabled, tell
286  * OpenSSL to use our private malloc/realloc/free functions so that
287  * we can dispatch them to dmalloc.
288  *
289  */
290 
291 #ifdef DMALLOC
292 static void *
293 crypto_malloc(size_t size, const char *file, int line)
294 {
295  return dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
296 }
297 
298 static void *
299 crypto_realloc(void *ptr, size_t size, const char *file, int line)
300 {
301  return dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
302 }
303 
304 static void
305 crypto_free(void *ptr)
306 {
307  dmalloc_free(__FILE__, __LINE__, ptr, DMALLOC_FUNC_FREE);
308 }
309 
310 void
311 crypto_init_dmalloc(void)
312 {
313  CRYPTO_set_mem_ex_functions(crypto_malloc,
314  crypto_realloc,
315  crypto_free);
316 }
317 #endif /* DMALLOC */
318 
320  { "AES-128-GCM", "id-aes128-GCM" },
321  { "AES-192-GCM", "id-aes192-GCM" },
322  { "AES-256-GCM", "id-aes256-GCM" },
323  { "CHACHA20-POLY1305", "ChaCha20-Poly1305" },
324 };
327 
328 
329 static int
330 cipher_name_cmp(const void *a, const void *b)
331 {
332  const EVP_CIPHER *const *cipher_a = a;
333  const EVP_CIPHER *const *cipher_b = b;
334 
335  return strcmp(EVP_CIPHER_get0_name(*cipher_a), EVP_CIPHER_get0_name(*cipher_b));
336 }
337 
339  /* If we ever exceed this, we must be more selective */
340  const EVP_CIPHER *list[1000];
341  size_t num;
342 };
343 
344 static void
345 collect_ciphers(EVP_CIPHER *cipher, void *list)
346 {
347  if (!cipher)
348  {
349  return;
350  }
351  struct collect_ciphers *cipher_list = list;
352  if (cipher_list->num == SIZE(cipher_list->list))
353  {
354  msg(M_WARN, "WARNING: Too many ciphers, not showing all");
355  return;
356  }
357 
358  const char *ciphername = EVP_CIPHER_get0_name(cipher);
359 
360  if (ciphername && (cipher_kt_mode_cbc(ciphername)
361 #ifdef ENABLE_OFB_CFB_MODE
362  || cipher_kt_mode_ofb_cfb(ciphername)
363 #endif
364  || cipher_kt_mode_aead(ciphername)
365  ))
366  {
367  cipher_list->list[cipher_list->num++] = cipher;
368  }
369 }
370 
371 void
373 {
374  struct collect_ciphers cipher_list = { 0 };
375 
376 #ifndef ENABLE_SMALL
377  printf("The following ciphers and cipher modes are available for use\n"
378  "with " PACKAGE_NAME ". Each cipher shown below may be used as a\n"
379  "parameter to the --data-ciphers (or --cipher) option. In static \n"
380  "key mode only CBC mode is allowed.\n");
381  printf("See also openssl list -cipher-algorithms\n\n");
382 #endif
383 
384 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
385  EVP_CIPHER_do_all_provided(NULL, collect_ciphers, &cipher_list);
386 #else
387  for (int nid = 0; nid < 10000; ++nid)
388  {
389  const EVP_CIPHER *cipher = EVP_get_cipherbynid(nid);
390  /* We cast the const away so we can keep the function prototype
391  * compatible with EVP_CIPHER_do_all_provided */
392  collect_ciphers((EVP_CIPHER *) cipher, &cipher_list);
393  }
394 #endif
395 
396  /* cast to non-const to prevent warning */
397  qsort((EVP_CIPHER *)cipher_list.list, cipher_list.num, sizeof(*cipher_list.list), cipher_name_cmp);
398 
399  for (size_t i = 0; i < cipher_list.num; i++)
400  {
401  if (!cipher_kt_insecure(EVP_CIPHER_get0_name(cipher_list.list[i])))
402  {
403  print_cipher(EVP_CIPHER_get0_name(cipher_list.list[i]));
404  }
405  }
406 
407  printf("\nThe following ciphers have a block size of less than 128 bits, \n"
408  "and are therefore deprecated. Do not use unless you have to.\n\n");
409  for (int i = 0; i < cipher_list.num; i++)
410  {
411  if (cipher_kt_insecure(EVP_CIPHER_get0_name(cipher_list.list[i])))
412  {
413  print_cipher(EVP_CIPHER_get0_name(cipher_list.list[i]));
414  }
415  }
416  printf("\n");
417 }
418 
419 void
420 print_digest(EVP_MD *digest, void *unused)
421 {
422  printf("%s %d bit digest size\n", md_kt_name(EVP_MD_get0_name(digest)),
423  EVP_MD_size(digest) * 8);
424 }
425 
426 void
428 {
429 #ifndef ENABLE_SMALL
430  printf("The following message digests are available for use with\n"
431  PACKAGE_NAME ". A message digest is used in conjunction with\n"
432  "the HMAC function, to authenticate received packets.\n"
433  "You can specify a message digest as parameter to\n"
434  "the --auth option.\n");
435  printf("See also openssl list -digest-algorithms\n\n");
436 #endif
437 
438 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
439  EVP_MD_do_all_provided(NULL, print_digest, NULL);
440 #else
441  for (int nid = 0; nid < 10000; ++nid)
442  {
443  const EVP_MD *digest = EVP_get_digestbynid(nid);
444  if (digest)
445  {
446  /* We cast the const away so we can keep the function prototype
447  * compatible with EVP_MD_do_all_provided */
448  print_digest((EVP_MD *)digest, NULL);
449  }
450  }
451 #endif
452  printf("\n");
453 }
454 
455 void
457 {
458 #if HAVE_OPENSSL_ENGINE /* Only defined for OpenSSL */
459  ENGINE *e;
460 
461  printf("OpenSSL Crypto Engines\n\n");
462 
463  ENGINE_load_builtin_engines();
464 
465  e = ENGINE_get_first();
466  while (e)
467  {
468  printf("%s [%s]\n",
469  ENGINE_get_name(e),
470  ENGINE_get_id(e));
471  e = ENGINE_get_next(e);
472  }
473  ENGINE_cleanup();
474 #else /* if HAVE_OPENSSL_ENGINE */
475  printf("Sorry, OpenSSL hardware crypto engine functionality is not available.\n");
476 #endif
477 }
478 
479 
480 bool
481 crypto_pem_encode(const char *name, struct buffer *dst,
482  const struct buffer *src, struct gc_arena *gc)
483 {
484  bool ret = false;
485  BIO *bio = BIO_new(BIO_s_mem());
486  if (!bio || !PEM_write_bio(bio, name, "", BPTR(src), BLEN(src)))
487  {
488  ret = false;
489  goto cleanup;
490  }
491 
492  BUF_MEM *bptr;
493  BIO_get_mem_ptr(bio, &bptr);
494 
495  *dst = alloc_buf_gc(bptr->length, gc);
496  ASSERT(buf_write(dst, bptr->data, bptr->length));
497 
498  ret = true;
499 cleanup:
500  if (!BIO_free(bio))
501  {
502  ret = false;
503  }
504 
505  return ret;
506 }
507 
508 bool
509 crypto_pem_decode(const char *name, struct buffer *dst,
510  const struct buffer *src)
511 {
512  bool ret = false;
513 
514  BIO *bio = BIO_new_mem_buf((char *)BPTR(src), BLEN(src));
515  if (!bio)
516  {
517  crypto_msg(M_FATAL, "Cannot open memory BIO for PEM decode");
518  }
519 
520  char *name_read = NULL;
521  char *header_read = NULL;
522  uint8_t *data_read = NULL;
523  long data_read_len = 0;
524  if (!PEM_read_bio(bio, &name_read, &header_read, &data_read,
525  &data_read_len))
526  {
527  dmsg(D_CRYPT_ERRORS, "%s: PEM decode failed", __func__);
528  goto cleanup;
529  }
530 
531  if (strcmp(name, name_read))
532  {
534  "%s: unexpected PEM name (got '%s', expected '%s')",
535  __func__, name_read, name);
536  goto cleanup;
537  }
538 
539  uint8_t *dst_data = buf_write_alloc(dst, data_read_len);
540  if (!dst_data)
541  {
542  dmsg(D_CRYPT_ERRORS, "%s: dst too small (%i, needs %li)", __func__,
543  BCAP(dst), data_read_len);
544  goto cleanup;
545  }
546  memcpy(dst_data, data_read, data_read_len);
547 
548  ret = true;
549 cleanup:
550  OPENSSL_free(name_read);
551  OPENSSL_free(header_read);
552  OPENSSL_free(data_read);
553  if (!BIO_free(bio))
554  {
555  ret = false;
556  }
557 
558  return ret;
559 }
560 
561 /*
562  *
563  * Random number functions, used in cases where we want
564  * reasonably strong cryptographic random number generation
565  * without depleting our entropy pool. Used for random
566  * IV values and a number of other miscellaneous tasks.
567  *
568  */
569 
570 int
571 rand_bytes(uint8_t *output, int len)
572 {
573  if (unlikely(1 != RAND_bytes(output, len)))
574  {
575  crypto_msg(D_CRYPT_ERRORS, "RAND_bytes() failed");
576  return 0;
577  }
578  return 1;
579 }
580 
581 /*
582  *
583  * Generic cipher key type functions
584  *
585  */
586 
587 static evp_cipher_type *
588 cipher_get(const char *ciphername)
589 {
590  ASSERT(ciphername);
591 
592  ciphername = translate_cipher_name_from_openvpn(ciphername);
593  return EVP_CIPHER_fetch(NULL, ciphername, NULL);
594 }
595 
596 bool
597 cipher_valid_reason(const char *ciphername, const char **reason)
598 {
599  bool ret = false;
600  evp_cipher_type *cipher = cipher_get(ciphername);
601  if (!cipher)
602  {
603  crypto_msg(D_LOW, "Cipher algorithm '%s' not found", ciphername);
604  *reason = "disabled because unknown";
605  goto out;
606  }
607 
608 #ifdef OPENSSL_FIPS
609  /* Rhel 8/CentOS 8 have a patched OpenSSL version that return a cipher
610  * here that is actually not usable if in FIPS mode */
611 
612  if (FIPS_mode() && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_FIPS))
613  {
614  msg(D_LOW, "Cipher algorithm '%s' is known by OpenSSL library but "
615  "currently disabled by running in FIPS mode.", ciphername);
616  *reason = "disabled by FIPS mode";
617  goto out;
618  }
619 #endif
620  if (EVP_CIPHER_key_length(cipher) > MAX_CIPHER_KEY_LENGTH)
621  {
622  msg(D_LOW, "Cipher algorithm '%s' uses a default key size (%d bytes) "
623  "which is larger than " PACKAGE_NAME "'s current maximum key size "
624  "(%d bytes)", ciphername, EVP_CIPHER_key_length(cipher),
626  *reason = "disabled due to key size too large";
627  goto out;
628  }
629 
630  ret = true;
631  *reason = NULL;
632 out:
633  EVP_CIPHER_free(cipher);
634  return ret;
635 }
636 
637 const char *
638 cipher_kt_name(const char *ciphername)
639 {
640  ASSERT(ciphername);
641  if (strcmp("none", ciphername) == 0)
642  {
643  return "[null-cipher]";
644  }
645 
646  evp_cipher_type *cipher_kt = cipher_get(ciphername);
647  if (!cipher_kt)
648  {
649  return NULL;
650  }
651 
652  const char *name = EVP_CIPHER_name(cipher_kt);
653  EVP_CIPHER_free(cipher_kt);
655 }
656 
657 int
658 cipher_kt_key_size(const char *ciphername)
659 {
660  evp_cipher_type *cipher = cipher_get(ciphername);
661  int size = EVP_CIPHER_key_length(cipher);
662  EVP_CIPHER_free(cipher);
663  return size;
664 }
665 
666 int
667 cipher_kt_iv_size(const char *ciphername)
668 {
669  evp_cipher_type *cipher = cipher_get(ciphername);
670  int ivsize = EVP_CIPHER_iv_length(cipher);
671  EVP_CIPHER_free(cipher);
672  return ivsize;
673 }
674 
675 int
676 cipher_kt_block_size(const char *ciphername)
677 {
678  /*
679  * OpenSSL reports OFB/CFB/GCM cipher block sizes as '1 byte'. To work
680  * around that, try to replace the mode with 'CBC' and return the block size
681  * reported for that cipher, if possible. If that doesn't work, just return
682  * the value reported by OpenSSL.
683  */
684  char *name = NULL;
685  char *mode_str = NULL;
686  const char *orig_name = NULL;
687  evp_cipher_type *cbc_cipher = NULL;
688  evp_cipher_type *cipher = cipher_get(ciphername);
689  if (!cipher)
690  {
691  return 0;
692  }
693 
694  int block_size = EVP_CIPHER_block_size(cipher);
695 
696  orig_name = EVP_CIPHER_name(cipher);
697  if (!orig_name)
698  {
699  goto cleanup;
700  }
701 
702  name = string_alloc(translate_cipher_name_to_openvpn(orig_name), NULL);
703  mode_str = strrchr(name, '-');
704  if (!mode_str || strlen(mode_str) < 4)
705  {
706  goto cleanup;
707  }
708 
709  strcpy(mode_str, "-CBC");
710 
711  cbc_cipher = EVP_CIPHER_fetch(NULL, translate_cipher_name_from_openvpn(name), NULL);
712  if (cbc_cipher)
713  {
714  block_size = EVP_CIPHER_block_size(cbc_cipher);
715  }
716 
717 cleanup:
718  EVP_CIPHER_free(cbc_cipher);
719  EVP_CIPHER_free(cipher);
720  free(name);
721  return block_size;
722 }
723 
724 int
725 cipher_kt_tag_size(const char *ciphername)
726 {
727  if (cipher_kt_mode_aead(ciphername))
728  {
730  }
731  else
732  {
733  return 0;
734  }
735 }
736 
737 bool
738 cipher_kt_insecure(const char *ciphername)
739 {
740 
741  if (cipher_kt_block_size(ciphername) >= 128 / 8)
742  {
743  return false;
744  }
745 #ifdef NID_chacha20_poly1305
746  evp_cipher_type *cipher = cipher_get(ciphername);
747  if (cipher)
748  {
749  bool ischachapoly = (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305);
750  EVP_CIPHER_free(cipher);
751  if (ischachapoly)
752  {
753  return false;
754  }
755  }
756 #endif
757  return true;
758 }
759 
760 int
761 cipher_kt_mode(const EVP_CIPHER *cipher_kt)
762 {
763  ASSERT(NULL != cipher_kt);
764  return EVP_CIPHER_mode(cipher_kt);
765 }
766 
767 bool
768 cipher_kt_mode_cbc(const char *ciphername)
769 {
770  evp_cipher_type *cipher = cipher_get(ciphername);
771 
772  bool ret = cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_CBC
773  /* Exclude AEAD cipher modes, they require a different API */
774 #ifdef EVP_CIPH_FLAG_CTS
775  && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_CTS)
776 #endif
777  && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER));
778  EVP_CIPHER_free(cipher);
779  return ret;
780 }
781 
782 bool
783 cipher_kt_mode_ofb_cfb(const char *ciphername)
784 {
785  evp_cipher_type *cipher = cipher_get(ciphername);
786  bool ofb_cfb = cipher && (cipher_kt_mode(cipher) == OPENVPN_MODE_OFB
787  || cipher_kt_mode(cipher) == OPENVPN_MODE_CFB)
788  /* Exclude AEAD cipher modes, they require a different API */
789  && !(EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER);
790  EVP_CIPHER_free(cipher);
791  return ofb_cfb;
792 }
793 
794 bool
795 cipher_kt_mode_aead(const char *ciphername)
796 {
797  bool isaead = false;
798 
799  evp_cipher_type *cipher = cipher_get(ciphername);
800  if (cipher)
801  {
802  if (EVP_CIPHER_mode(cipher) == OPENVPN_MODE_GCM)
803  {
804  isaead = true;
805  }
806 
807 #ifdef NID_chacha20_poly1305
808  if (EVP_CIPHER_nid(cipher) == NID_chacha20_poly1305)
809  {
810  isaead = true;
811  }
812 #endif
813  }
814 
815  EVP_CIPHER_free(cipher);
816 
817  return isaead;
818 }
819 
820 /*
821  *
822  * Generic cipher context functions
823  *
824  */
825 
826 cipher_ctx_t *
828 {
829  EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
830  check_malloc_return(ctx);
831  return ctx;
832 }
833 
834 void
835 cipher_ctx_free(EVP_CIPHER_CTX *ctx)
836 {
837  EVP_CIPHER_CTX_free(ctx);
838 }
839 
840 void
841 cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key,
842  const char *ciphername, int enc)
843 {
844  ASSERT(NULL != ciphername && NULL != ctx);
845  evp_cipher_type *kt = cipher_get(ciphername);
846 
848  if (!EVP_CipherInit(ctx, kt, NULL, NULL, enc))
849  {
850  crypto_msg(M_FATAL, "EVP cipher init #1");
851  }
852  if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, enc))
853  {
854  crypto_msg(M_FATAL, "EVP cipher init #2");
855  }
856 
857  /* make sure we used a big enough key */
858  ASSERT(EVP_CIPHER_CTX_key_length(ctx) <= EVP_CIPHER_key_length(kt));
859  EVP_CIPHER_free(kt);
860 }
861 
862 int
863 cipher_ctx_iv_length(const EVP_CIPHER_CTX *ctx)
864 {
865  return EVP_CIPHER_CTX_iv_length(ctx);
866 }
867 
868 int
869 cipher_ctx_get_tag(EVP_CIPHER_CTX *ctx, uint8_t *tag_buf, int tag_size)
870 {
871  return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag_size, tag_buf);
872 }
873 
874 int
875 cipher_ctx_block_size(const EVP_CIPHER_CTX *ctx)
876 {
877  return EVP_CIPHER_CTX_block_size(ctx);
878 }
879 
880 int
881 cipher_ctx_mode(const EVP_CIPHER_CTX *ctx)
882 {
883  return EVP_CIPHER_CTX_mode(ctx);
884 }
885 
886 
887 bool
889 {
890  if (!ctx)
891  {
892  return false;
893  }
894 
895  int flags = EVP_CIPHER_CTX_flags(ctx);
896  int mode = EVP_CIPHER_CTX_mode(ctx);
897 
898  return mode == EVP_CIPH_CBC_MODE
899  /* Exclude AEAD cipher modes, they require a different API */
900 #ifdef EVP_CIPH_FLAG_CTS
901  && !(flags & EVP_CIPH_FLAG_CTS)
902 #endif
903  && !(flags & EVP_CIPH_FLAG_AEAD_CIPHER);
904 }
905 
906 bool
908 {
909  if (!ctx)
910  {
911  return false;
912  }
913 
914  int mode = EVP_CIPHER_CTX_get_mode(ctx);
915 
916  return (mode == EVP_CIPH_OFB_MODE || mode == EVP_CIPH_CFB_MODE)
917  /* Exclude AEAD cipher modes, they require a different API */
918  && !(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER);
919 }
920 
921 bool
923 {
924  if (ctx)
925  {
926  int flags = EVP_CIPHER_CTX_flags(ctx);
927  if (flags & EVP_CIPH_FLAG_AEAD_CIPHER)
928  {
929  return true;
930  }
931 
932 #if defined(NID_chacha20_poly1305) && OPENSSL_VERSION_NUMBER < 0x30000000L
933  if (EVP_CIPHER_CTX_nid(ctx) == NID_chacha20_poly1305)
934  {
935  return true;
936  }
937 #endif
938  }
939 
940  return false;
941 }
942 
943 
944 int
945 cipher_ctx_reset(EVP_CIPHER_CTX *ctx, const uint8_t *iv_buf)
946 {
947  return EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv_buf, -1);
948 }
949 
950 int
951 cipher_ctx_update_ad(EVP_CIPHER_CTX *ctx, const uint8_t *src, int src_len)
952 {
953  int len;
954  if (!EVP_CipherUpdate(ctx, NULL, &len, src, src_len))
955  {
956  crypto_msg(M_FATAL, "%s: EVP_CipherUpdate() failed", __func__);
957  }
958  return 1;
959 }
960 
961 int
962 cipher_ctx_update(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len,
963  uint8_t *src, int src_len)
964 {
965  if (!EVP_CipherUpdate(ctx, dst, dst_len, src, src_len))
966  {
967  crypto_msg(M_FATAL, "%s: EVP_CipherUpdate() failed", __func__);
968  }
969  return 1;
970 }
971 
972 int
973 cipher_ctx_final(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len)
974 {
975  return EVP_CipherFinal(ctx, dst, dst_len);
976 }
977 
978 int
979 cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len,
980  uint8_t *tag, size_t tag_len)
981 {
982  ASSERT(tag_len < SIZE_MAX);
983  if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag))
984  {
985  return 0;
986  }
987 
988  return cipher_ctx_final(ctx, dst, dst_len);
989 }
990 
991 void
993  unsigned char src[DES_KEY_LENGTH],
994  unsigned char dst[DES_KEY_LENGTH])
995 {
996  /* We are using 3DES here with three times the same key to cheat
997  * and emulate DES as 3DES is better supported than DES */
998  EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
999  if (!ctx)
1000  {
1001  crypto_msg(M_FATAL, "%s: EVP_CIPHER_CTX_new() failed", __func__);
1002  }
1003 
1004  unsigned char key3[DES_KEY_LENGTH*3];
1005  for (int i = 0; i < 3; i++)
1006  {
1007  memcpy(key3 + (i * DES_KEY_LENGTH), key, DES_KEY_LENGTH);
1008  }
1009 
1010  if (!EVP_EncryptInit_ex(ctx, EVP_des_ede3_ecb(), NULL, key3, NULL))
1011  {
1012  crypto_msg(M_FATAL, "%s: EVP_EncryptInit_ex() failed", __func__);
1013  }
1014 
1015  int len;
1016 
1017  /* The EVP_EncryptFinal method will write to the dst+len pointer even
1018  * though there is nothing to encrypt anymore, provide space for that to
1019  * not overflow the stack */
1020  unsigned char dst2[DES_KEY_LENGTH * 2];
1021  if (!EVP_EncryptUpdate(ctx, dst2, &len, src, DES_KEY_LENGTH))
1022  {
1023  crypto_msg(M_FATAL, "%s: EVP_EncryptUpdate() failed", __func__);
1024  }
1025 
1026  if (!EVP_EncryptFinal(ctx, dst2 + len, &len))
1027  {
1028  crypto_msg(M_FATAL, "%s: EVP_EncryptFinal() failed", __func__);
1029  }
1030 
1031  memcpy(dst, dst2, DES_KEY_LENGTH);
1032 
1033  EVP_CIPHER_CTX_free(ctx);
1034 }
1035 
1036 /*
1037  *
1038  * Generic message digest information functions
1039  *
1040  */
1041 
1042 
1043 static evp_md_type *
1044 md_get(const char *digest)
1045 {
1046  evp_md_type *md = NULL;
1047  ASSERT(digest);
1048  md = EVP_MD_fetch(NULL, digest, NULL);
1049  if (!md)
1050  {
1051  crypto_msg(M_FATAL, "Message hash algorithm '%s' not found", digest);
1052  }
1053  if (EVP_MD_size(md) > MAX_HMAC_KEY_LENGTH)
1054  {
1055  crypto_msg(M_FATAL, "Message hash algorithm '%s' uses a default hash "
1056  "size (%d bytes) which is larger than " PACKAGE_NAME "'s current "
1057  "maximum hash size (%d bytes)",
1058  digest, EVP_MD_size(md), MAX_HMAC_KEY_LENGTH);
1059  }
1060  return md;
1061 }
1062 
1063 
1064 bool
1065 md_valid(const char *digest)
1066 {
1067  evp_md_type *md = EVP_MD_fetch(NULL, digest, NULL);
1068  bool valid = (md != NULL);
1069  EVP_MD_free(md);
1070  return valid;
1071 }
1072 
1073 
1074 /* Since we used the OpenSSL <=1.1 names as part of our OCC message, they
1075  * are now unfortunately part of our wire protocol.
1076  *
1077  * OpenSSL 3.0 will still accept the "old" names so we do not need to use
1078  * this translation table for forward lookup, only for returning the name
1079  * with md_kt_name() */
1081  { "BLAKE2s256", "BLAKE2S-256"},
1082  { "BLAKE2b512", "BLAKE2B-512"},
1083  { "RIPEMD160", "RIPEMD-160" },
1084  { "SHA224", "SHA2-224"},
1085  { "SHA256", "SHA2-256"},
1086  { "SHA384", "SHA2-384"},
1087  { "SHA512", "SHA2-512"},
1088  { "SHA512-224", "SHA2-512/224"},
1089  { "SHA512-256", "SHA2-512/256"},
1090  { "SHAKE128", "SHAKE-128"},
1091  { "SHAKE256", "SHAKE-256"},
1092 };
1095 
1096 const char *
1097 md_kt_name(const char *mdname)
1098 {
1099  if (!strcmp("none", mdname))
1100  {
1101  return "[null-digest]";
1102  }
1103  evp_md_type *kt = md_get(mdname);
1104  const char *name = EVP_MD_get0_name(kt);
1105 
1106  /* Search for a digest name translation */
1107  for (size_t i = 0; i < digest_name_translation_table_count; i++)
1108  {
1110  if (!strcmp(name, pair->lib_name))
1111  {
1112  name = pair->openvpn_name;
1113  }
1114  }
1115 
1116  EVP_MD_free(kt);
1117  return name;
1118 }
1119 
1120 unsigned char
1121 md_kt_size(const char *mdname)
1122 {
1123  if (!strcmp("none", mdname))
1124  {
1125  return 0;
1126  }
1127  evp_md_type *kt = md_get(mdname);
1128  unsigned char size = (unsigned char)EVP_MD_size(kt);
1129  EVP_MD_free(kt);
1130  return size;
1131 }
1132 
1133 
1134 /*
1135  *
1136  * Generic message digest functions
1137  *
1138  */
1139 
1140 int
1141 md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst)
1142 {
1143  unsigned int in_md_len = 0;
1144  evp_md_type *kt = md_get(mdname);
1145 
1146  int ret = EVP_Digest(src, src_len, dst, &in_md_len, kt, NULL);
1147  EVP_MD_free(kt);
1148  return ret;
1149 }
1150 
1151 EVP_MD_CTX *
1153 {
1154  EVP_MD_CTX *ctx = EVP_MD_CTX_new();
1155  check_malloc_return(ctx);
1156  return ctx;
1157 }
1158 
1159 void
1160 md_ctx_free(EVP_MD_CTX *ctx)
1161 {
1162  EVP_MD_CTX_free(ctx);
1163 }
1164 
1165 void
1166 md_ctx_init(EVP_MD_CTX *ctx, const char *mdname)
1167 {
1168  evp_md_type *kt = md_get(mdname);
1169  ASSERT(NULL != ctx && NULL != kt);
1170 
1171  EVP_MD_CTX_init(ctx);
1172  if (!EVP_DigestInit(ctx, kt))
1173  {
1174  crypto_msg(M_FATAL, "EVP_DigestInit failed");
1175  }
1176  EVP_MD_free(kt);
1177 }
1178 
1179 void
1180 md_ctx_cleanup(EVP_MD_CTX *ctx)
1181 {
1182  EVP_MD_CTX_reset(ctx);
1183 }
1184 
1185 int
1186 md_ctx_size(const EVP_MD_CTX *ctx)
1187 {
1188  return EVP_MD_CTX_size(ctx);
1189 }
1190 
1191 void
1192 md_ctx_update(EVP_MD_CTX *ctx, const uint8_t *src, int src_len)
1193 {
1194  EVP_DigestUpdate(ctx, src, src_len);
1195 }
1196 
1197 void
1198 md_ctx_final(EVP_MD_CTX *ctx, uint8_t *dst)
1199 {
1200  unsigned int in_md_len = 0;
1201 
1202  EVP_DigestFinal(ctx, dst, &in_md_len);
1203 }
1204 
1205 
1206 /*
1207  *
1208  * Generic HMAC functions
1209  *
1210  */
1211 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1212 HMAC_CTX *
1214 {
1215  HMAC_CTX *ctx = HMAC_CTX_new();
1216  check_malloc_return(ctx);
1217  return ctx;
1218 }
1219 
1220 void
1221 hmac_ctx_free(HMAC_CTX *ctx)
1222 {
1223  HMAC_CTX_free(ctx);
1224 }
1225 
1226 void
1227 hmac_ctx_init(HMAC_CTX *ctx, const uint8_t *key, const char *mdname)
1228 {
1229  evp_md_type *kt = md_get(mdname);
1230  ASSERT(NULL != kt && NULL != ctx);
1231 
1232  int key_len = EVP_MD_size(kt);
1233  HMAC_CTX_reset(ctx);
1234  if (!HMAC_Init_ex(ctx, key, key_len, kt, NULL))
1235  {
1236  crypto_msg(M_FATAL, "HMAC_Init_ex failed");
1237  }
1238 
1239  /* make sure we used a big enough key */
1240  ASSERT(HMAC_size(ctx) <= key_len);
1241 }
1242 
1243 void
1244 hmac_ctx_cleanup(HMAC_CTX *ctx)
1245 {
1246  HMAC_CTX_reset(ctx);
1247 }
1248 
1249 int
1250 hmac_ctx_size(HMAC_CTX *ctx)
1251 {
1252  return HMAC_size(ctx);
1253 }
1254 
1255 void
1256 hmac_ctx_reset(HMAC_CTX *ctx)
1257 {
1258  if (!HMAC_Init_ex(ctx, NULL, 0, NULL, NULL))
1259  {
1260  crypto_msg(M_FATAL, "HMAC_Init_ex failed");
1261  }
1262 }
1263 
1264 void
1265 hmac_ctx_update(HMAC_CTX *ctx, const uint8_t *src, int src_len)
1266 {
1267  HMAC_Update(ctx, src, src_len);
1268 }
1269 
1270 void
1271 hmac_ctx_final(HMAC_CTX *ctx, uint8_t *dst)
1272 {
1273  unsigned int in_hmac_len = 0;
1274 
1275  HMAC_Final(ctx, dst, &in_hmac_len);
1276 }
1277 #else /* if OPENSSL_VERSION_NUMBER < 0x30000000L */
1278 hmac_ctx_t *
1279 hmac_ctx_new(void)
1280 {
1281  hmac_ctx_t *ctx;
1283  EVP_MAC *hmac = EVP_MAC_fetch(NULL, "HMAC", NULL);
1284  ctx->ctx = EVP_MAC_CTX_new(hmac);
1285  check_malloc_return(ctx->ctx);
1286 
1287  EVP_MAC_free(hmac);
1288 
1289  return ctx;
1290 }
1291 
1292 void
1294 {
1295  EVP_MAC_CTX_free(ctx->ctx);
1296  secure_memzero(ctx, sizeof(hmac_ctx_t));
1297  free(ctx);
1298 }
1299 
1300 void
1301 hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname)
1302 {
1303  evp_md_type *kt = md_get(mdname);
1304  ASSERT(NULL != kt && NULL != ctx && ctx->ctx != NULL);
1305 
1306  /* We need to make a copy of the key since the OSSL parameters
1307  * only reference it */
1308  memcpy(ctx->key, key, EVP_MD_size(kt));
1309 
1310  /* Lookup/setting of parameters in OpenSSL 3.0 are string based
1311  *
1312  * The OSSL_PARAM_construct_utf8_string needs a non const str but this
1313  * only used for lookup so we cast (as OpenSSL also does internally)
1314  * the constness away here.
1315  */
1316  ctx->params[0] = OSSL_PARAM_construct_utf8_string("digest",
1317  (char *) EVP_MD_get0_name(kt), 0);
1318  ctx->params[1] = OSSL_PARAM_construct_octet_string("key",
1319  ctx->key, EVP_MD_size(kt));
1320  ctx->params[2] = OSSL_PARAM_construct_end();
1321 
1322  if (!EVP_MAC_init(ctx->ctx, NULL, 0, ctx->params))
1323  {
1324  crypto_msg(M_FATAL, "EVP_MAC_init failed");
1325  }
1326 
1327  EVP_MD_free(kt);
1328 }
1329 
1330 void
1332 {
1333  EVP_MAC_init(ctx->ctx, NULL, 0, NULL);
1334 }
1335 
1336 int
1338 {
1339  return (int)EVP_MAC_CTX_get_mac_size(ctx->ctx);
1340 }
1341 
1342 void
1344 {
1345  /* The OpenSSL MAC API lacks a reset method and passing NULL as params
1346  * does not reset it either, so use the params array to reinitialise it the
1347  * same way as before */
1348  if (!EVP_MAC_init(ctx->ctx, NULL, 0, ctx->params))
1349  {
1350  crypto_msg(M_FATAL, "EVP_MAC_init failed");
1351  }
1352 }
1353 
1354 void
1355 hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
1356 {
1357  EVP_MAC_update(ctx->ctx, src, src_len);
1358 }
1359 
1360 void
1361 hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
1362 {
1363  /* The calling code always gives us a buffer that has the size of our
1364  * algorithm */
1365  size_t in_hmac_len = EVP_MAC_CTX_get_mac_size(ctx->ctx);
1366 
1367  EVP_MAC_final(ctx->ctx, dst, &in_hmac_len, in_hmac_len);
1368 }
1369 #endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L */
1370 
1371 int
1372 memcmp_constant_time(const void *a, const void *b, size_t size)
1373 {
1374  return CRYPTO_memcmp(a, b, size);
1375 }
1376 
1377 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
1378 bool
1379 ssl_tls1_PRF(const uint8_t *seed, int seed_len, const uint8_t *secret,
1380  int secret_len, uint8_t *output, int output_len)
1381 {
1382  EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL);
1383  if (!pctx)
1384  {
1385  return false;
1386  }
1387 
1388  bool ret = false;
1389  if (!EVP_PKEY_derive_init(pctx))
1390  {
1391  goto out;
1392  }
1393 
1394  if (!EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_md5_sha1()))
1395  {
1396  goto out;
1397  }
1398 
1399  if (!EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, secret, secret_len))
1400  {
1401  goto out;
1402  }
1403 
1404  if (!EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed, seed_len))
1405  {
1406  goto out;
1407  }
1408 
1409  size_t out_len = output_len;
1410  if (!EVP_PKEY_derive(pctx, output, &out_len))
1411  {
1412  goto out;
1413  }
1414  if (out_len != output_len)
1415  {
1416  goto out;
1417  }
1418  ret = true;
1419 out:
1420  EVP_PKEY_CTX_free(pctx);
1421  return ret;
1422 }
1423 #else /* if OPENSSL_VERSION_NUMBER >= 0x10100000L */
1424 /*
1425  * Generate the hash required by for the \c tls1_PRF function.
1426  *
1427  * We cannot use our normal hmac_* function as they do not work
1428  * in a FIPS environment (no MD5 allowed, which we need). Instead
1429  * we need to directly use the EVP_MD_* API with the special
1430  * EVP_MD_CTX_FLAG_NON_FIPS_ALLOW flag.
1431  *
1432  * The function below is adapted from OpenSSL 1.0.2t
1433  *
1434  * @param md_kt Message digest to use
1435  * @param sec Secret to base the hash on
1436  * @param sec_len Length of the secret
1437  * @param seed Seed to hash
1438  * @param seed_len Length of the seed
1439  * @param out Output buffer
1440  * @param olen Length of the output buffer
1441  */
1442 static
1443 bool
1444 tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
1445  int sec_len, const void *seed, int seed_len,
1446  unsigned char *out, int olen)
1447 {
1448  int chunk;
1449  size_t j;
1450  EVP_MD_CTX *ctx, *ctx_tmp, *ctx_init;
1451  EVP_PKEY *mac_key;
1452  unsigned char A1[EVP_MAX_MD_SIZE];
1453  size_t A1_len = EVP_MAX_MD_SIZE;
1454  int ret = false;
1455 
1456  chunk = EVP_MD_size(md);
1457  OPENSSL_assert(chunk >= 0);
1458 
1459  ctx = md_ctx_new();
1460  ctx_tmp = md_ctx_new();
1461  ctx_init = md_ctx_new();
1462  EVP_MD_CTX_set_flags(ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1463  mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
1464  if (!mac_key)
1465  {
1466  goto err;
1467  }
1468  if (!EVP_DigestSignInit(ctx_init, NULL, md, NULL, mac_key))
1469  {
1470  goto err;
1471  }
1472  if (!EVP_MD_CTX_copy_ex(ctx, ctx_init))
1473  {
1474  goto err;
1475  }
1476  if (!EVP_DigestSignUpdate(ctx, seed, seed_len))
1477  {
1478  goto err;
1479  }
1480  if (!EVP_DigestSignFinal(ctx, A1, &A1_len))
1481  {
1482  goto err;
1483  }
1484 
1485  for (;; )
1486  {
1487  /* Reinit mac contexts */
1488  if (!EVP_MD_CTX_copy_ex(ctx, ctx_init))
1489  {
1490  goto err;
1491  }
1492  if (!EVP_DigestSignUpdate(ctx, A1, A1_len))
1493  {
1494  goto err;
1495  }
1496  if (olen > chunk && !EVP_MD_CTX_copy_ex(ctx_tmp, ctx))
1497  {
1498  goto err;
1499  }
1500  if (!EVP_DigestSignUpdate(ctx, seed, seed_len))
1501  {
1502  goto err;
1503  }
1504 
1505  if (olen > chunk)
1506  {
1507  j = olen;
1508  if (!EVP_DigestSignFinal(ctx, out, &j))
1509  {
1510  goto err;
1511  }
1512  out += j;
1513  olen -= j;
1514  /* calc the next A1 value */
1515  if (!EVP_DigestSignFinal(ctx_tmp, A1, &A1_len))
1516  {
1517  goto err;
1518  }
1519  }
1520  else
1521  {
1522  A1_len = EVP_MAX_MD_SIZE;
1523  /* last one */
1524  if (!EVP_DigestSignFinal(ctx, A1, &A1_len))
1525  {
1526  goto err;
1527  }
1528  memcpy(out, A1, olen);
1529  break;
1530  }
1531  }
1532  ret = true;
1533 err:
1534  EVP_PKEY_free(mac_key);
1535  EVP_MD_CTX_free(ctx);
1536  EVP_MD_CTX_free(ctx_tmp);
1537  EVP_MD_CTX_free(ctx_init);
1538  OPENSSL_cleanse(A1, sizeof(A1));
1539  return ret;
1540 }
1541 
1542 /*
1543  * Use the TLS PRF function for generating data channel keys.
1544  * This code is based on the OpenSSL library.
1545  *
1546  * TLS generates keys as such:
1547  *
1548  * master_secret[48] = PRF(pre_master_secret[48], "master secret",
1549  * ClientHello.random[32] + ServerHello.random[32])
1550  *
1551  * key_block[] = PRF(SecurityParameters.master_secret[48],
1552  * "key expansion",
1553  * SecurityParameters.server_random[32] +
1554  * SecurityParameters.client_random[32]);
1555  *
1556  * Notes:
1557  *
1558  * (1) key_block contains a full set of 4 keys.
1559  * (2) The pre-master secret is generated by the client.
1560  */
1561 bool
1562 ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec,
1563  int slen, uint8_t *out1, int olen)
1564 {
1565  bool ret = true;
1566  struct gc_arena gc = gc_new();
1567  /* For some reason our md_get("MD5") fails otherwise in the unit test */
1568  const EVP_MD *md5 = EVP_md5();
1569  const EVP_MD *sha1 = EVP_sha1();
1570 
1571  uint8_t *out2 = (uint8_t *)gc_malloc(olen, false, &gc);
1572 
1573  int len = slen/2;
1574  const uint8_t *S1 = sec;
1575  const uint8_t *S2 = &(sec[len]);
1576  len += (slen&1); /* add for odd, make longer */
1577 
1578  if (!tls1_P_hash(md5, S1, len, label, label_len, out1, olen))
1579  {
1580  ret = false;
1581  goto done;
1582  }
1583 
1584  if (!tls1_P_hash(sha1, S2, len, label, label_len, out2, olen))
1585  {
1586  ret = false;
1587  goto done;
1588  }
1589 
1590  for (int i = 0; i < olen; i++)
1591  {
1592  out1[i] ^= out2[i];
1593  }
1594 
1595  secure_memzero(out2, olen);
1596 
1597  dmsg(D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex(out1, olen, 0, &gc));
1598 done:
1599  gc_free(&gc);
1600  return ret;
1601 }
1602 #endif /* if OPENSSL_VERSION_NUMBER >= 0x10100000L */
1603 #endif /* ENABLE_CRYPTO_OPENSSL */
collect_ciphers
static void collect_ciphers(EVP_CIPHER *cipher, void *list)
Definition: crypto_openssl.c:345
EVP_CIPHER_free
static void EVP_CIPHER_free(const EVP_CIPHER *cipher)
Definition: openssl_compat.h:796
cipher_name_translation_table
const cipher_name_pair cipher_name_translation_table[]
Cipher name translation table.
Definition: crypto_openssl.c:319
OPENVPN_MODE_CBC
#define OPENVPN_MODE_CBC
Cipher is in CBC mode.
Definition: crypto_mbedtls.h:55
M_INFO
#define M_INFO
Definition: errlevel.h:55
HMAC_CTX_new
static HMAC_CTX * HMAC_CTX_new(void)
Allocate a new HMAC context object.
Definition: openssl_compat.h:166
gc_new
static struct gc_arena gc_new(void)
Definition: buffer.h:1011
hmac_ctx_t
mbedtls_md_context_t hmac_ctx_t
Generic HMAC context.
Definition: crypto_mbedtls.h:46
collect_ciphers::num
size_t num
Definition: crypto_openssl.c:341
HMAC_CTX_free
static void HMAC_CTX_free(HMAC_CTX *ctx)
Cleanup and free an existing HMAC context.
Definition: openssl_compat.h:154
EVP_CIPHER_get0_name
#define EVP_CIPHER_get0_name
Definition: openssl_compat.h:766
cipher_ctx_mode_aead
bool cipher_ctx_mode_aead(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported AEAD mode cipher.
Definition: crypto_openssl.c:922
EVP_MD_fetch
static const EVP_MD * EVP_MD_fetch(void *ctx, const char *algorithm, const char *properties)
Definition: openssl_compat.h:788
PACKAGE_NAME
#define PACKAGE_NAME
Definition: config.h:492
hmac_ctx_final
void hmac_ctx_final(HMAC_CTX *ctx, uint8_t *dst)
Definition: crypto_openssl.c:1271
M_FATAL
#define M_FATAL
Definition: error.h:95
OPENVPN_MODE_OFB
#define OPENVPN_MODE_OFB
Cipher is in OFB mode.
Definition: crypto_mbedtls.h:58
unlikely
#define unlikely(x)
Definition: syshead.h:36
translate_cipher_name_to_openvpn
const char * translate_cipher_name_to_openvpn(const char *cipher_name)
Translate a crypto library cipher name to an OpenVPN cipher name.
Definition: crypto.c:1686
cipher_kt_key_size
int cipher_kt_key_size(const char *ciphername)
Returns the size of keys used by the cipher, in bytes.
Definition: crypto_openssl.c:658
OPENVPN_MODE_CFB
#define OPENVPN_MODE_CFB
Cipher is in CFB mode.
Definition: crypto_mbedtls.h:61
print_digest
void print_digest(EVP_MD *digest, void *unused)
Definition: crypto_openssl.c:420
EVP_MD_CTX_new
static EVP_MD_CTX * EVP_MD_CTX_new(void)
Allocate a new message digest object.
Definition: openssl_compat.h:114
alloc_buf_gc
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition: buffer.c:88
print_cipher
void print_cipher(const char *ciphername)
Print a cipher list entry.
Definition: crypto.c:1622
cipher_ctx_free
void cipher_ctx_free(EVP_CIPHER_CTX *ctx)
Definition: crypto_openssl.c:835
dmsg
#define dmsg(flags,...)
Definition: error.h:154
EVP_MD_CTX_reset
static int EVP_MD_CTX_reset(EVP_MD_CTX *ctx)
Reset a message digest context.
Definition: openssl_compat.h:91
cipher_ctx_final_check_tag
int cipher_ctx_final_check_tag(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, uint8_t *tag, size_t tag_len)
Definition: crypto_openssl.c:979
D_LOW
#define D_LOW
Definition: errlevel.h:97
cipher_kt_name
const char * cipher_kt_name(const char *ciphername)
Retrieve a normalised string describing the cipher (e.g.
Definition: crypto_openssl.c:638
translate_cipher_name_from_openvpn
const char * translate_cipher_name_from_openvpn(const char *cipher_name)
Translate an OpenVPN cipher name to a crypto library cipher name.
Definition: crypto.c:1673
crypto_pem_encode
bool crypto_pem_encode(const char *name, struct buffer *dst, const struct buffer *src, struct gc_arena *gc)
Encode binary data as PEM.
Definition: crypto_openssl.c:481
EVP_MD_free
static void EVP_MD_free(const EVP_MD *md)
Definition: openssl_compat.h:802
MAX_CIPHER_KEY_LENGTH
#define MAX_CIPHER_KEY_LENGTH
Definition: crypto_backend.h:188
md_full
int md_full(const char *mdname, const uint8_t *src, int src_len, uint8_t *dst)
Calculates the message digest for the given buffer.
Definition: crypto_openssl.c:1141
ssl_tls1_PRF
bool ssl_tls1_PRF(const uint8_t *label, int label_len, const uint8_t *sec, int slen, uint8_t *out1, int olen)
Calculates the TLS 1.0-1.1 PRF function.
Definition: crypto_openssl.c:1562
EVP_CIPHER_fetch
static const EVP_CIPHER * EVP_CIPHER_fetch(void *ctx, const char *algorithm, const char *properties)
Definition: openssl_compat.h:780
key
Container for unidirectional cipher and HMAC key material.
Definition: crypto.h:149
cipher_kt_mode_cbc
bool cipher_kt_mode_cbc(const char *ciphername)
Check if the supplied cipher is a supported CBC mode cipher.
Definition: crypto_openssl.c:768
crypto_clear_error
void crypto_clear_error(void)
Definition: crypto_openssl.c:232
md_ctx_init
void md_ctx_init(EVP_MD_CTX *ctx, const char *mdname)
Definition: crypto_openssl.c:1166
cipher_name_cmp
static int cipher_name_cmp(const void *a, const void *b)
Definition: crypto_openssl.c:330
crypto_init_lib
void crypto_init_lib(void)
Definition: crypto_openssl.c:193
cipher_kt_mode_ofb_cfb
bool cipher_kt_mode_ofb_cfb(const char *ciphername)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
Definition: crypto_openssl.c:783
string_alloc
char * string_alloc(const char *str, struct gc_arena *gc)
Definition: buffer.c:693
secure_memzero
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition: buffer.h:414
crypto_init_lib_engine
void crypto_init_lib_engine(const char *engine_name)
Definition: crypto_openssl.c:143
ASSERT
#define ASSERT(x)
Definition: error.h:201
MAX_HMAC_KEY_LENGTH
#define MAX_HMAC_KEY_LENGTH
Definition: crypto_backend.h:506
ENABLE_OFB_CFB_MODE
#define ENABLE_OFB_CFB_MODE
Definition: config.h:56
OPENVPN_AEAD_TAG_LENGTH
#define OPENVPN_AEAD_TAG_LENGTH
Definition: crypto_backend.h:42
cipher_valid_reason
bool cipher_valid_reason(const char *ciphername, const char **reason)
Returns if the cipher is valid, based on the given cipher name and provides a reason if invalid.
Definition: crypto_openssl.c:597
BLEN
#define BLEN(buf)
Definition: buffer.h:127
cipher_ctx_reset
int cipher_ctx_reset(EVP_CIPHER_CTX *ctx, const uint8_t *iv_buf)
Definition: crypto_openssl.c:945
cipher_name_pair::openvpn_name
const char * openvpn_name
Cipher name used by OpenVPN.
Definition: crypto_backend.h:58
crypto_load_provider
provider_t * crypto_load_provider(const char *provider)
Load the given (OpenSSL) providers.
Definition: crypto_openssl.c:159
memcmp_constant_time
int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
Definition: crypto_openssl.c:1372
cipher_name_translation_table_count
const size_t cipher_name_translation_table_count
Definition: crypto_openssl.c:325
ERR_get_error_all
static unsigned long ERR_get_error_all(const char **file, int *line, const char **func, const char **data, int *flags)
Definition: openssl_compat.h:808
cipher_ctx_init
void cipher_ctx_init(EVP_CIPHER_CTX *ctx, const uint8_t *key, const char *ciphername, int enc)
Definition: crypto_openssl.c:841
md_ctx_new
EVP_MD_CTX * md_ctx_new(void)
Definition: crypto_openssl.c:1152
cipher_ctx_t
mbedtls_cipher_context_t cipher_ctx_t
Generic cipher context.
Definition: crypto_mbedtls.h:40
digest_name_translation_table_count
const size_t digest_name_translation_table_count
Definition: crypto_openssl.c:1093
cipher_ctx_iv_length
int cipher_ctx_iv_length(const EVP_CIPHER_CTX *ctx)
Definition: crypto_openssl.c:863
cipher_kt_mode
int cipher_kt_mode(const EVP_CIPHER *cipher_kt)
Definition: crypto_openssl.c:761
M_WARN
#define M_WARN
Definition: error.h:97
show_available_digests
void show_available_digests(void)
Definition: crypto_openssl.c:427
cipher_kt_iv_size
int cipher_kt_iv_size(const char *ciphername)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
Definition: crypto_openssl.c:667
cipher_ctx_mode_cbc
bool cipher_ctx_mode_cbc(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported CBC mode cipher.
Definition: crypto_openssl.c:888
hmac_ctx_init
void hmac_ctx_init(HMAC_CTX *ctx, const uint8_t *key, const char *mdname)
Definition: crypto_openssl.c:1227
tls1_P_hash
static bool tls1_P_hash(const EVP_MD *md, const unsigned char *sec, int sec_len, const void *seed, int seed_len, unsigned char *out, int olen)
Definition: crypto_openssl.c:1444
cipher_des_encrypt_ecb
void cipher_des_encrypt_ecb(const unsigned char key[DES_KEY_LENGTH], unsigned char src[DES_KEY_LENGTH], unsigned char dst[DES_KEY_LENGTH])
Encrypt the given block, using DES ECB mode.
Definition: crypto_openssl.c:992
md_get
static evp_md_type * md_get(const char *digest)
Definition: crypto_openssl.c:1044
cipher_ctx_update
int cipher_ctx_update(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len, uint8_t *src, int src_len)
Definition: crypto_openssl.c:962
show_available_ciphers
void show_available_ciphers(void)
Definition: crypto_openssl.c:372
crypto.h
rand_bytes
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
Definition: crypto_openssl.c:571
hmac_ctx_reset
void hmac_ctx_reset(HMAC_CTX *ctx)
Definition: crypto_openssl.c:1256
cipher_ctx_mode
int cipher_ctx_mode(const EVP_CIPHER_CTX *ctx)
Definition: crypto_openssl.c:881
EVP_MD_CTX_free
static void EVP_MD_CTX_free(EVP_MD_CTX *ctx)
Free an existing message digest context.
Definition: openssl_compat.h:103
crypto_unload_provider
void crypto_unload_provider(const char *provname, provider_t *provider)
Unloads the given (OpenSSL) provider.
Definition: crypto_openssl.c:176
hmac_ctx_free
void hmac_ctx_free(HMAC_CTX *ctx)
Definition: crypto_openssl.c:1221
cipher_ctx_get_tag
int cipher_ctx_get_tag(EVP_CIPHER_CTX *ctx, uint8_t *tag_buf, int tag_size)
Definition: crypto_openssl.c:869
EVP_MD_get0_name
#define EVP_MD_get0_name
Definition: openssl_compat.h:765
md_valid
bool md_valid(const char *digest)
Return if a message digest parameters is valid given the name of the digest.
Definition: crypto_openssl.c:1065
md_ctx_size
int md_ctx_size(const EVP_MD_CTX *ctx)
Definition: crypto_openssl.c:1186
key3
static const char *const key3
Definition: cert_data.h:108
cipher_kt_mode_aead
bool cipher_kt_mode_aead(const char *ciphername)
Check if the supplied cipher is a supported AEAD mode cipher.
Definition: crypto_openssl.c:795
buffer
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
SIZE
#define SIZE(x)
Definition: basic.h:30
md_ctx_final
void md_ctx_final(EVP_MD_CTX *ctx, uint8_t *dst)
Definition: crypto_openssl.c:1198
provider_t
void provider_t
Definition: crypto_mbedtls.h:49
cipher_ctx_mode_ofb_cfb
bool cipher_ctx_mode_ofb_cfb(const cipher_ctx_t *ctx)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
Definition: crypto_openssl.c:907
cipher_name_pair
Struct used in cipher name translation table.
Definition: crypto_backend.h:57
md_ctx_update
void md_ctx_update(EVP_MD_CTX *ctx, const uint8_t *src, int src_len)
Definition: crypto_openssl.c:1192
D_CRYPT_ERRORS
#define D_CRYPT_ERRORS
Definition: errlevel.h:58
hmac_ctx_update
void hmac_ctx_update(HMAC_CTX *ctx, const uint8_t *src, int src_len)
Definition: crypto_openssl.c:1265
buf_write
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Definition: buffer.h:686
hmac_ctx_size
int hmac_ctx_size(HMAC_CTX *ctx)
Definition: crypto_openssl.c:1250
BCAP
#define BCAP(buf)
Definition: buffer.h:130
openssl_compat.h
cipher_ctx_block_size
int cipher_ctx_block_size(const EVP_CIPHER_CTX *ctx)
Definition: crypto_openssl.c:875
buffer.h
cipher_kt_insecure
bool cipher_kt_insecure(const char *ciphername)
Returns true if we consider this cipher to be insecure.
Definition: crypto_openssl.c:738
syshead.h
EVP_CIPHER_CTX_reset
#define EVP_CIPHER_CTX_reset
Definition: openssl_compat.h:121
BPTR
#define BPTR(buf)
Definition: buffer.h:124
md_ctx_free
void md_ctx_free(EVP_MD_CTX *ctx)
Definition: crypto_openssl.c:1160
collect_ciphers
Definition: crypto_openssl.c:338
gc_arena
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
collect_ciphers::list
const EVP_CIPHER * list[1000]
Definition: crypto_openssl.c:340
OPENVPN_MODE_GCM
#define OPENVPN_MODE_GCM
Cipher is in GCM mode.
Definition: crypto_mbedtls.h:64
crypto_print_openssl_errors
void crypto_print_openssl_errors(const unsigned int flags)
Retrieve any occurred OpenSSL errors and print those errors.
Definition: crypto_openssl.c:238
md_kt_name
const char * md_kt_name(const char *mdname)
Retrieve a string describing the digest digest (e.g.
Definition: crypto_openssl.c:1097
EVP_CTRL_AEAD_SET_TAG
#define EVP_CTRL_AEAD_SET_TAG
Definition: openssl_compat.h:70
md_ctx_cleanup
void md_ctx_cleanup(EVP_MD_CTX *ctx)
Definition: crypto_openssl.c:1180
digest_name_translation_table
const cipher_name_pair digest_name_translation_table[]
Definition: crypto_openssl.c:1080
evp_cipher_type
const typedef EVP_CIPHER evp_cipher_type
Definition: crypto_openssl.h:66
md_kt_size
unsigned char md_kt_size(const char *mdname)
Returns the size of the message digest, in bytes.
Definition: crypto_openssl.c:1121
cipher_get
static evp_cipher_type * cipher_get(const char *ciphername)
Definition: crypto_openssl.c:588
check_debug_level
static bool check_debug_level(unsigned int level)
Definition: error.h:226
show_available_engines
void show_available_engines(void)
Definition: crypto_openssl.c:456
crypto_msg
#define crypto_msg(flags,...)
Retrieve any OpenSSL errors, then print the supplied error message.
Definition: crypto_openssl.h:115
basic.h
cipher_ctx_final
int cipher_ctx_final(EVP_CIPHER_CTX *ctx, uint8_t *dst, int *dst_len)
Definition: crypto_openssl.c:973
cipher_ctx_new
cipher_ctx_t * cipher_ctx_new(void)
Generic cipher functions.
Definition: crypto_openssl.c:827
cipher_kt_block_size
int cipher_kt_block_size(const char *ciphername)
Returns the block size of the cipher, in bytes.
Definition: crypto_openssl.c:676
hmac_ctx_cleanup
void hmac_ctx_cleanup(HMAC_CTX *ctx)
Definition: crypto_openssl.c:1244
gc_malloc
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Definition: buffer.c:380
D_TLS_DEBUG_MED
#define D_TLS_DEBUG_MED
Definition: errlevel.h:157
D_SHOW_KEY_SOURCE
#define D_SHOW_KEY_SOURCE
Definition: errlevel.h:122
crypto_uninit_lib
void crypto_uninit_lib(void)
Definition: crypto_openssl.c:212
gc_free
static void gc_free(struct gc_arena *a)
Definition: buffer.h:1019
EVP_CTRL_AEAD_GET_TAG
#define EVP_CTRL_AEAD_GET_TAG
Definition: openssl_compat.h:71
ALLOC_OBJ_CLEAR
#define ALLOC_OBJ_CLEAR(dptr, type)
Definition: buffer.h:1046
evp_md_type
const typedef EVP_MD evp_md_type
Definition: crypto_openssl.h:67
OSSL_PROVIDER
void OSSL_PROVIDER
Definition: openssl_compat.h:775
buf_write_alloc
static uint8_t * buf_write_alloc(struct buffer *buf, size_t size)
Definition: buffer.h:653
config.h
HMAC_CTX_reset
static int HMAC_CTX_reset(HMAC_CTX *ctx)
Reset a HMAC context.
Definition: openssl_compat.h:141
hmac_ctx_new
HMAC_CTX * hmac_ctx_new(void)
Definition: crypto_openssl.c:1213
cipher_kt_tag_size
int cipher_kt_tag_size(const char *ciphername)
Returns the MAC tag size of the cipher, in bytes.
Definition: crypto_openssl.c:725
format_hex
static char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *gc)
Definition: buffer.h:523
check_malloc_return
static void check_malloc_return(void *p)
Definition: buffer.h:1089
cipher_name_pair::lib_name
const char * lib_name
Cipher name used by crypto library.
Definition: crypto_backend.h:59
DES_KEY_LENGTH
#define DES_KEY_LENGTH
Definition: crypto_mbedtls.h:76
msg
#define msg(flags,...)
Definition: error.h:150
crypto_pem_decode
bool crypto_pem_decode(const char *name, struct buffer *dst, const struct buffer *src)
Decode a PEM buffer to binary data.
Definition: crypto_openssl.c:509
cipher_ctx_update_ad
int cipher_ctx_update_ad(EVP_CIPHER_CTX *ctx, const uint8_t *src, int src_len)
Definition: crypto_openssl.c:951
integer.h
crypto_backend.h
EVP_CIPHER_CTX_get_mode
#define EVP_CIPHER_CTX_get_mode
Definition: openssl_compat.h:767
buffer::data
uint8_t * data
Pointer to the allocated memory.
Definition: buffer.h:68
cleanup
static int cleanup(void **state)
Definition: test_pkcs11.c:278