OpenVPN
ssl_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-2018 OpenVPN Inc <sales@openvpn.net>
9  * Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2
13  * as published by the Free Software Foundation.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License 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 #elif defined(_MSC_VER)
32 #include "config-msvc.h"
33 #endif
34 
35 #include "syshead.h"
36 
37 #if defined(ENABLE_CRYPTO_OPENSSL)
38 
39 #include "errlevel.h"
40 #include "buffer.h"
41 #include "misc.h"
42 #include "manage.h"
43 #include "memdbg.h"
44 #include "ssl_backend.h"
45 #include "ssl_common.h"
46 #include "base64.h"
47 #include "openssl_compat.h"
48 
49 #ifdef ENABLE_CRYPTOAPI
50 #include "cryptoapi.h"
51 #endif
52 
53 #include "ssl_verify_openssl.h"
54 
55 #include <openssl/bn.h>
56 #include <openssl/crypto.h>
57 #include <openssl/dh.h>
58 #include <openssl/dsa.h>
59 #include <openssl/err.h>
60 #include <openssl/pkcs12.h>
61 #include <openssl/rsa.h>
62 #include <openssl/x509.h>
63 #include <openssl/ssl.h>
64 #ifndef OPENSSL_NO_EC
65 #include <openssl/ec.h>
66 #endif
67 
68 /*
69  * Allocate space in SSL objects in which to store a struct tls_session
70  * pointer back to parent.
71  *
72  */
73 
74 int mydata_index; /* GLOBAL */
75 
76 void
78 {
79 #if (OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER))
80  SSL_library_init();
81 #ifndef ENABLE_SMALL
82  SSL_load_error_strings();
83 #endif
84  OpenSSL_add_all_algorithms();
85 #endif
86  mydata_index = SSL_get_ex_new_index(0, "struct session *", NULL, NULL, NULL);
87  ASSERT(mydata_index >= 0);
88 }
89 
90 void
92 {
93 #if (OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER))
94  EVP_cleanup();
95 #ifndef ENABLE_SMALL
96  ERR_free_strings();
97 #endif
98 #endif
99 }
100 
101 void
103 {
104  ERR_clear_error();
105 }
106 
107 void
109 {
110  ASSERT(NULL != ctx);
111 
112  ctx->ctx = SSL_CTX_new(SSLv23_server_method());
113 
114  if (ctx->ctx == NULL)
115  {
116  crypto_msg(M_FATAL, "SSL_CTX_new SSLv23_server_method");
117  }
118  if (ERR_peek_error() != 0)
119  {
120  crypto_msg(M_WARN, "Warning: TLS server context initialisation "
121  "has warnings.");
122  }
123 }
124 
125 void
127 {
128  ASSERT(NULL != ctx);
129 
130  ctx->ctx = SSL_CTX_new(SSLv23_client_method());
131 
132  if (ctx->ctx == NULL)
133  {
134  crypto_msg(M_FATAL, "SSL_CTX_new SSLv23_client_method");
135  }
136  if (ERR_peek_error() != 0)
137  {
138  crypto_msg(M_WARN, "Warning: TLS client context initialisation "
139  "has warnings.");
140  }
141 }
142 
143 void
145 {
146  ASSERT(NULL != ctx);
147  if (NULL != ctx->ctx)
148  {
149  SSL_CTX_free(ctx->ctx);
150  }
151  ctx->ctx = NULL;
152 }
153 
154 bool
156 {
157  ASSERT(NULL != ctx);
158  return NULL != ctx->ctx;
159 }
160 
161 void
163  struct tls_session *session)
164 {
165  if (session->opt->ekm_size > 0)
166  {
167  unsigned int size = session->opt->ekm_size;
168  struct gc_arena gc = gc_new();
169  unsigned char *ekm = (unsigned char *) gc_malloc(size, true, &gc);
170 
171  if (SSL_export_keying_material(ssl->ssl, ekm, size,
172  session->opt->ekm_label,
173  session->opt->ekm_label_size,
174  NULL, 0, 0))
175  {
176  unsigned int len = (size * 2) + 2;
177 
178  const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
179  setenv_str(session->opt->es, "exported_keying_material", key);
180 
181  dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s",
182  __func__, key);
183  }
184  else
185  {
186  msg(M_WARN, "WARNING: Export keying material failed!");
187  setenv_del(session->opt->es, "exported_keying_material");
188  }
189  gc_free(&gc);
190  }
191 }
192 
193 /*
194  * Print debugging information on SSL/TLS session negotiation.
195  */
196 
197 #ifndef INFO_CALLBACK_SSL_CONST
198 #define INFO_CALLBACK_SSL_CONST const
199 #endif
200 static void
201 info_callback(INFO_CALLBACK_SSL_CONST SSL *s, int where, int ret)
202 {
203  if (where & SSL_CB_LOOP)
204  {
205  dmsg(D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
206  where & SSL_ST_CONNECT ? "connect" :
207  where &SSL_ST_ACCEPT ? "accept" :
208  "undefined", SSL_state_string_long(s));
209  }
210  else if (where & SSL_CB_ALERT)
211  {
212  dmsg(D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
213  where & SSL_CB_READ ? "read" : "write",
214  SSL_alert_type_string_long(ret),
215  SSL_alert_desc_string_long(ret));
216  }
217 }
218 
219 /*
220  * Return maximum TLS version supported by local OpenSSL library.
221  * Assume that presence of SSL_OP_NO_TLSvX macro indicates that
222  * TLSvX is supported.
223  */
224 int
226 {
227 #if defined(TLS1_3_VERSION)
228  /* If this is defined we can safely assume TLS 1.3 support */
229  return TLS_VER_1_3;
230 #elif OPENSSL_VERSION_NUMBER >= 0x10100000L
231  /*
232  * If TLS_VER_1_3 is not defined, we were compiled against a version that
233  * did not support TLS 1.3.
234  *
235  * However, the library we are *linked* against might be OpenSSL 1.1.1
236  * and therefore supports TLS 1.3. This needs to be checked at runtime
237  * since we can be compiled against 1.1.0 and then the library can be
238  * upgraded to 1.1.1.
239  * We only need to check this for OpenSSL versions that can be
240  * upgraded to 1.1.1 without recompile (>= 1.1.0)
241  */
242  if (OpenSSL_version_num() >= 0x1010100fL)
243  {
244  return TLS_VER_1_3;
245  }
246  else
247  {
248  return TLS_VER_1_2;
249  }
250 #elif defined(TLS1_2_VERSION) || defined(SSL_OP_NO_TLSv1_2)
251  return TLS_VER_1_2;
252 #elif defined(TLS1_1_VERSION) || defined(SSL_OP_NO_TLSv1_1)
253  return TLS_VER_1_1;
254 #else /* if defined(TLS1_3_VERSION) */
255  return TLS_VER_1_0;
256 #endif
257 }
258 
260 static int
262 {
263  if (ver == TLS_VER_1_0)
264  {
265  return TLS1_VERSION;
266  }
267  else if (ver == TLS_VER_1_1)
268  {
269  return TLS1_1_VERSION;
270  }
271  else if (ver == TLS_VER_1_2)
272  {
273  return TLS1_2_VERSION;
274  }
275  else if (ver == TLS_VER_1_3)
276  {
277  /*
278  * Supporting the library upgraded to TLS1.3 without recompile
279  * is enough to support here with a simple constant that the same
280  * as in the TLS 1.3, so spec it is very unlikely that OpenSSL
281  * will change this constant
282  */
283 #ifndef TLS1_3_VERSION
284  /*
285  * We do not want to define TLS_VER_1_3 if not defined
286  * since other parts of the code use the existance of this macro
287  * as proxy for TLS 1.3 support
288  */
289  return 0x0304;
290 #else
291  return TLS1_3_VERSION;
292 #endif
293  }
294  return 0;
295 }
296 
297 static bool
298 tls_ctx_set_tls_versions(struct tls_root_ctx *ctx, unsigned int ssl_flags)
299 {
300  int tls_ver_min = openssl_tls_version(
302  int tls_ver_max = openssl_tls_version(
304 
305  if (!tls_ver_min)
306  {
307  /* Enforce at least TLS 1.0 */
308  int cur_min = SSL_CTX_get_min_proto_version(ctx->ctx);
309  tls_ver_min = cur_min < TLS1_VERSION ? TLS1_VERSION : cur_min;
310  }
311 
312  if (!SSL_CTX_set_min_proto_version(ctx->ctx, tls_ver_min))
313  {
314  msg(D_TLS_ERRORS, "%s: failed to set minimum TLS version", __func__);
315  return false;
316  }
317 
318  if (tls_ver_max && !SSL_CTX_set_max_proto_version(ctx->ctx, tls_ver_max))
319  {
320  msg(D_TLS_ERRORS, "%s: failed to set maximum TLS version", __func__);
321  return false;
322  }
323 
324  return true;
325 }
326 
327 bool
328 tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
329 {
330  ASSERT(NULL != ctx);
331 
332  /* process SSL options */
333  long sslopt = SSL_OP_SINGLE_DH_USE | SSL_OP_NO_TICKET;
334 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
335  sslopt |= SSL_OP_CIPHER_SERVER_PREFERENCE;
336 #endif
337  sslopt |= SSL_OP_NO_COMPRESSION;
338 
339  SSL_CTX_set_options(ctx->ctx, sslopt);
340 
341  if (!tls_ctx_set_tls_versions(ctx, ssl_flags))
342  {
343  return false;
344  }
345 
346 #ifdef SSL_MODE_RELEASE_BUFFERS
347  SSL_CTX_set_mode(ctx->ctx, SSL_MODE_RELEASE_BUFFERS);
348 #endif
349  SSL_CTX_set_session_cache_mode(ctx->ctx, SSL_SESS_CACHE_OFF);
350  SSL_CTX_set_default_passwd_cb(ctx->ctx, pem_password_callback);
351 
352  /* Require peer certificate verification */
353  int verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
354  if (ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED)
355  {
356  verify_flags = 0;
357  }
358  else if (ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
359  {
360  verify_flags = SSL_VERIFY_PEER;
361  }
362  SSL_CTX_set_verify(ctx->ctx, verify_flags, verify_callback);
363 
364  SSL_CTX_set_info_callback(ctx->ctx, info_callback);
365 
366  return true;
367 }
368 
369 void
370 convert_tls_list_to_openssl(char *openssl_ciphers, size_t len,const char *ciphers)
371 {
372  /* Parse supplied cipher list and pass on to OpenSSL */
373  size_t begin_of_cipher, end_of_cipher;
374 
375  const char *current_cipher;
376  size_t current_cipher_len;
377 
378  const tls_cipher_name_pair *cipher_pair;
379 
380  size_t openssl_ciphers_len = 0;
381  openssl_ciphers[0] = '\0';
382 
383  /* Translate IANA cipher suite names to OpenSSL names */
384  begin_of_cipher = end_of_cipher = 0;
385  for (; begin_of_cipher < strlen(ciphers); begin_of_cipher = end_of_cipher)
386  {
387  end_of_cipher += strcspn(&ciphers[begin_of_cipher], ":");
388  cipher_pair = tls_get_cipher_name_pair(&ciphers[begin_of_cipher], end_of_cipher - begin_of_cipher);
389 
390  if (NULL == cipher_pair)
391  {
392  /* No translation found, use original */
393  current_cipher = &ciphers[begin_of_cipher];
394  current_cipher_len = end_of_cipher - begin_of_cipher;
395 
396  /* Issue warning on missing translation */
397  /* %.*s format specifier expects length of type int, so guarantee */
398  /* that length is small enough and cast to int. */
399  msg(D_LOW, "No valid translation found for TLS cipher '%.*s'",
400  constrain_int(current_cipher_len, 0, 256), current_cipher);
401  }
402  else
403  {
404  /* Use OpenSSL name */
405  current_cipher = cipher_pair->openssl_name;
406  current_cipher_len = strlen(current_cipher);
407 
408  if (end_of_cipher - begin_of_cipher == current_cipher_len
409  && 0 != memcmp(&ciphers[begin_of_cipher], cipher_pair->iana_name,
410  end_of_cipher - begin_of_cipher))
411  {
412  /* Non-IANA name used, show warning */
413  msg(M_WARN, "Deprecated TLS cipher name '%s', please use IANA name '%s'", cipher_pair->openssl_name, cipher_pair->iana_name);
414  }
415  }
416 
417  /* Make sure new cipher name fits in cipher string */
418  if ((SIZE_MAX - openssl_ciphers_len) < current_cipher_len
419  || (len - 1) < (openssl_ciphers_len + current_cipher_len))
420  {
421  msg(M_FATAL,
422  "Failed to set restricted TLS cipher list, too long (>%d).",
423  (int)(len - 1));
424  }
425 
426  /* Concatenate cipher name to OpenSSL cipher string */
427  memcpy(&openssl_ciphers[openssl_ciphers_len], current_cipher, current_cipher_len);
428  openssl_ciphers_len += current_cipher_len;
429  openssl_ciphers[openssl_ciphers_len] = ':';
430  openssl_ciphers_len++;
431 
432  end_of_cipher++;
433  }
434 
435  if (openssl_ciphers_len > 0)
436  {
437  openssl_ciphers[openssl_ciphers_len-1] = '\0';
438  }
439 }
440 
441 void
442 tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
443 {
444  if (ciphers == NULL)
445  {
446  /* Use sane default TLS cipher list */
447  if (!SSL_CTX_set_cipher_list(ctx->ctx,
448  /* Use openssl's default list as a basis */
449  "DEFAULT"
450  /* Disable export ciphers and openssl's 'low' and 'medium' ciphers */
451  ":!EXP:!LOW:!MEDIUM"
452  /* Disable static (EC)DH keys (no forward secrecy) */
453  ":!kDH:!kECDH"
454  /* Disable DSA private keys */
455  ":!DSS"
456  /* Disable unsupported TLS modes */
457  ":!PSK:!SRP:!kRSA"))
458  {
459  crypto_msg(M_FATAL, "Failed to set default TLS cipher list.");
460  }
461  return;
462  }
463 
464  char openssl_ciphers[4096];
465  convert_tls_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers), ciphers);
466 
467  ASSERT(NULL != ctx);
468 
469  /* Set OpenSSL cipher list */
470  if (!SSL_CTX_set_cipher_list(ctx->ctx, openssl_ciphers))
471  {
472  crypto_msg(M_FATAL, "Failed to set restricted TLS cipher list: %s", openssl_ciphers);
473  }
474 }
475 
476 void
477 convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len,
478  const char *ciphers)
479 {
480  /*
481  * OpenSSL (and official IANA) cipher names have _ in them. We
482  * historically used names with - in them. Silently convert names
483  * with - to names with _ to support both
484  */
485  if (strlen(ciphers) >= (len - 1))
486  {
487  msg(M_FATAL,
488  "Failed to set restricted TLS 1.3 cipher list, too long (>%d).",
489  (int) (len - 1));
490  }
491 
492  strncpy(openssl_ciphers, ciphers, len);
493 
494  for (size_t i = 0; i < strlen(openssl_ciphers); i++)
495  {
496  if (openssl_ciphers[i] == '-')
497  {
498  openssl_ciphers[i] = '_';
499  }
500  }
501 }
502 
503 void
504 tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
505 {
506  if (ciphers == NULL)
507  {
508  /* default cipher list of OpenSSL 1.1.1 is sane, do not set own
509  * default as we do with tls-cipher */
510  return;
511  }
512 
513 #if !defined(TLS1_3_VERSION)
514  crypto_msg(M_WARN, "Not compiled with OpenSSL 1.1.1 or higher. "
515  "Ignoring TLS 1.3 only tls-ciphersuites '%s' setting.",
516  ciphers);
517 #else
518  ASSERT(NULL != ctx);
519 
520  char openssl_ciphers[4096];
521  convert_tls13_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers),
522  ciphers);
523 
524  if (!SSL_CTX_set_ciphersuites(ctx->ctx, openssl_ciphers))
525  {
526  crypto_msg(M_FATAL, "Failed to set restricted TLS 1.3 cipher list: %s",
527  openssl_ciphers);
528  }
529 #endif
530 }
531 
532 void
533 tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
534 {
535 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
536  /* OpenSSL does not have certificate profiles, but a complex set of
537  * callbacks that we could try to implement to achieve something similar.
538  * For now, use OpenSSL's security levels to achieve similar (but not equal)
539  * behaviour. */
540  if (!profile || 0 == strcmp(profile, "legacy"))
541  {
542  SSL_CTX_set_security_level(ctx->ctx, 1);
543  }
544  else if (0 == strcmp(profile, "preferred"))
545  {
546  SSL_CTX_set_security_level(ctx->ctx, 2);
547  }
548  else if (0 == strcmp(profile, "suiteb"))
549  {
550  SSL_CTX_set_security_level(ctx->ctx, 3);
551  SSL_CTX_set_cipher_list(ctx->ctx, "SUITEB128");
552  }
553  else
554  {
555  msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
556  }
557 #else /* ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL */
558  if (profile)
559  {
560  msg(M_WARN, "WARNING: OpenSSL 1.0.2 does not support --tls-cert-profile"
561  ", ignoring user-set profile: '%s'", profile);
562  }
563 #endif /* ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL */
564 }
565 
566 void
567 tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
568 {
569  ASSERT(ctx);
570  struct gc_arena gc = gc_new();
571  /* This method could be as easy as
572  * SSL_CTX_set1_groups_list(ctx->ctx, groups)
573  * but OpenSSL does not like the name secp256r1 for prime256v1
574  * This is one of the important curves.
575  * To support the same name for OpenSSL and mbedTLS, we do
576  * this dance.
577  */
578 
579  int groups_count = get_num_elements(groups, ':');
580 
581  int *glist;
582  /* Allocate an array for them */
583  ALLOC_ARRAY_CLEAR_GC(glist, int, groups_count, &gc);
584 
585  /* Parse allowed ciphers, getting IDs */
586  int glistlen = 0;
587  char *tmp_groups = string_alloc(groups, &gc);
588 
589  const char *token;
590  while ((token = strsep(&tmp_groups, ":")))
591  {
592  if (streq(token, "secp256r1"))
593  {
594  token = "prime256v1";
595  }
596  int nid = OBJ_sn2nid(token);
597 
598  if (nid == 0)
599  {
600  msg(M_WARN, "Warning unknown curve/group specified: %s", token);
601  }
602  else
603  {
604  glist[glistlen] = nid;
605  glistlen++;
606  }
607  }
608 
609  if (!SSL_CTX_set1_groups(ctx->ctx, glist, glistlen))
610  {
611  crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s",
612  groups);
613  }
614  gc_free(&gc);
615 }
616 
617 void
619 {
620  int ret;
621  const X509 *cert;
622 
623  ASSERT(ctx);
624 
625  cert = SSL_CTX_get0_certificate(ctx->ctx);
626 
627  if (cert == NULL)
628  {
629  return; /* Nothing to check if there is no certificate */
630  }
631 
632  ret = X509_cmp_time(X509_get0_notBefore(cert), NULL);
633  if (ret == 0)
634  {
635  msg(D_TLS_DEBUG_MED, "Failed to read certificate notBefore field.");
636  }
637  if (ret > 0)
638  {
639  msg(M_WARN, "WARNING: Your certificate is not yet valid!");
640  }
641 
642  ret = X509_cmp_time(X509_get0_notAfter(cert), NULL);
643  if (ret == 0)
644  {
645  msg(D_TLS_DEBUG_MED, "Failed to read certificate notAfter field.");
646  }
647  if (ret < 0)
648  {
649  msg(M_WARN, "WARNING: Your certificate has expired!");
650  }
651 }
652 
653 void
654 tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,
655  bool dh_file_inline)
656 {
657  DH *dh;
658  BIO *bio;
659 
660  ASSERT(NULL != ctx);
661 
662  if (dh_file_inline)
663  {
664  if (!(bio = BIO_new_mem_buf((char *)dh_file, -1)))
665  {
666  crypto_msg(M_FATAL, "Cannot open memory BIO for inline DH parameters");
667  }
668  }
669  else
670  {
671  /* Get Diffie Hellman Parameters */
672  if (!(bio = BIO_new_file(dh_file, "r")))
673  {
674  crypto_msg(M_FATAL, "Cannot open %s for DH parameters", dh_file);
675  }
676  }
677 
678  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
679  BIO_free(bio);
680 
681  if (!dh)
682  {
683  crypto_msg(M_FATAL, "Cannot load DH parameters from %s",
684  print_key_filename(dh_file, dh_file_inline));
685  }
686  if (!SSL_CTX_set_tmp_dh(ctx->ctx, dh))
687  {
688  crypto_msg(M_FATAL, "SSL_CTX_set_tmp_dh");
689  }
690 
691  msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
692  8 * DH_size(dh));
693 
694  DH_free(dh);
695 }
696 
697 void
698 tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name
699  )
700 {
701 #ifndef OPENSSL_NO_EC
702  int nid = NID_undef;
703  EC_KEY *ecdh = NULL;
704  const char *sname = NULL;
705 
706  /* Generate a new ECDH key for each SSL session (for non-ephemeral ECDH) */
707  SSL_CTX_set_options(ctx->ctx, SSL_OP_SINGLE_ECDH_USE);
708 
709  if (curve_name != NULL)
710  {
711  /* Use user supplied curve if given */
712  msg(D_TLS_DEBUG, "Using user specified ECDH curve (%s)", curve_name);
713  nid = OBJ_sn2nid(curve_name);
714  }
715  else
716  {
717 #if (OPENSSL_VERSION_NUMBER < 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER))
718 
719  /* OpenSSL 1.0.2 and newer can automatically handle ECDH parameter
720  * loading */
721  SSL_CTX_set_ecdh_auto(ctx->ctx, 1);
722 
723  /* OpenSSL 1.1.0 and newer have always ecdh auto loading enabled,
724  * so do nothing */
725 #endif
726  return;
727  }
728 
729  /* Translate NID back to name , just for kicks */
730  sname = OBJ_nid2sn(nid);
731  if (sname == NULL)
732  {
733  sname = "(Unknown)";
734  }
735 
736  /* Create new EC key and set as ECDH key */
737  if (NID_undef == nid || NULL == (ecdh = EC_KEY_new_by_curve_name(nid)))
738  {
739  /* Creating key failed, fall back on sane default */
740  ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
741  const char *source = (NULL == curve_name) ?
742  "extract curve from certificate" : "use supplied curve";
744  "Failed to %s (%s), using secp384r1 instead.", source, sname);
745  sname = OBJ_nid2sn(NID_secp384r1);
746  }
747 
748  if (!SSL_CTX_set_tmp_ecdh(ctx->ctx, ecdh))
749  {
750  crypto_msg(M_FATAL, "SSL_CTX_set_tmp_ecdh: cannot add curve");
751  }
752 
753  msg(D_TLS_DEBUG_LOW, "ECDH curve %s added", sname);
754 
755  EC_KEY_free(ecdh);
756 #else /* ifndef OPENSSL_NO_EC */
757  msg(D_LOW, "Your OpenSSL library was built without elliptic curve support."
758  " Skipping ECDH parameter loading.");
759 #endif /* OPENSSL_NO_EC */
760 }
761 
762 int
763 tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,
764  bool pkcs12_file_inline, bool load_ca_file)
765 {
766  FILE *fp;
767  EVP_PKEY *pkey;
768  X509 *cert;
769  STACK_OF(X509) *ca = NULL;
770  PKCS12 *p12;
771  int i;
772  char password[256];
773 
774  ASSERT(NULL != ctx);
775 
776  if (pkcs12_file_inline)
777  {
778  BIO *b64 = BIO_new(BIO_f_base64());
779  BIO *bio = BIO_new_mem_buf((void *) pkcs12_file,
780  (int) strlen(pkcs12_file));
781  ASSERT(b64 && bio);
782  BIO_push(b64, bio);
783  p12 = d2i_PKCS12_bio(b64, NULL);
784  if (!p12)
785  {
786  crypto_msg(M_FATAL, "Error reading inline PKCS#12 file");
787  }
788  BIO_free(b64);
789  BIO_free(bio);
790  }
791  else
792  {
793  /* Load the PKCS #12 file */
794  if (!(fp = platform_fopen(pkcs12_file, "rb")))
795  {
796  crypto_msg(M_FATAL, "Error opening file %s", pkcs12_file);
797  }
798  p12 = d2i_PKCS12_fp(fp, NULL);
799  fclose(fp);
800  if (!p12)
801  {
802  crypto_msg(M_FATAL, "Error reading PKCS#12 file %s", pkcs12_file);
803  }
804  }
805 
806  /* Parse the PKCS #12 file */
807  if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
808  {
809  pem_password_callback(password, sizeof(password) - 1, 0, NULL);
810  /* Reparse the PKCS #12 file with password */
811  ca = NULL;
812  if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
813  {
814 #ifdef ENABLE_MANAGEMENT
815  if (management && (ERR_GET_REASON(ERR_peek_error()) == PKCS12_R_MAC_VERIFY_FAILURE))
816  {
818  }
819 #endif
820  PKCS12_free(p12);
821  return 1;
822  }
823  }
824  PKCS12_free(p12);
825 
826  /* Load Certificate */
827  if (!SSL_CTX_use_certificate(ctx->ctx, cert))
828  {
829  crypto_msg(M_FATAL, "Cannot use certificate");
830  }
831 
832  /* Load Private Key */
833  if (!SSL_CTX_use_PrivateKey(ctx->ctx, pkey))
834  {
835  crypto_msg(M_FATAL, "Cannot use private key");
836  }
837 
838  /* Check Private Key */
839  if (!SSL_CTX_check_private_key(ctx->ctx))
840  {
841  crypto_msg(M_FATAL, "Private key does not match the certificate");
842  }
843 
844  /* Set Certificate Verification chain */
845  if (load_ca_file)
846  {
847  /* Add CAs from PKCS12 to the cert store and mark them as trusted.
848  * They're also used to fill in the chain of intermediate certs as
849  * necessary.
850  */
851  if (ca && sk_X509_num(ca))
852  {
853  for (i = 0; i < sk_X509_num(ca); i++)
854  {
855  X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx->ctx);
856  if (!X509_STORE_add_cert(cert_store,sk_X509_value(ca, i)))
857  {
858  crypto_msg(M_FATAL,"Cannot add certificate to certificate chain (X509_STORE_add_cert)");
859  }
860  if (!SSL_CTX_add_client_CA(ctx->ctx, sk_X509_value(ca, i)))
861  {
862  crypto_msg(M_FATAL,"Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
863  }
864  }
865  }
866  }
867  else
868  {
869  /* If trusted CA certs were loaded from a PEM file, and we ignore the
870  * ones in PKCS12, do load PKCS12-provided certs to the client extra
871  * certs chain just in case they include intermediate CAs needed to
872  * prove my identity to the other end. This does not make them trusted.
873  */
874  if (ca && sk_X509_num(ca))
875  {
876  for (i = 0; i < sk_X509_num(ca); i++)
877  {
878  if (!SSL_CTX_add_extra_chain_cert(ctx->ctx,sk_X509_value(ca, i)))
879  {
880  crypto_msg(M_FATAL, "Cannot add extra certificate to chain (SSL_CTX_add_extra_chain_cert)");
881  }
882  }
883  }
884  }
885  return 0;
886 }
887 
888 #ifdef ENABLE_CRYPTOAPI
889 void
890 tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
891 {
892  ASSERT(NULL != ctx);
893 
894  /* Load Certificate and Private Key */
895  if (!SSL_CTX_use_CryptoAPI_certificate(ctx->ctx, cryptoapi_cert))
896  {
897  crypto_msg(M_FATAL, "Cannot load certificate \"%s\" from Microsoft Certificate Store", cryptoapi_cert);
898  }
899 }
900 #endif /* ENABLE_CRYPTOAPI */
901 
902 static void
903 tls_ctx_add_extra_certs(struct tls_root_ctx *ctx, BIO *bio, bool optional)
904 {
905  X509 *cert;
906  while (true)
907  {
908  cert = NULL;
909  if (!PEM_read_bio_X509(bio, &cert, NULL, NULL))
910  {
911  /* a PEM_R_NO_START_LINE "Error" indicates that no certificate
912  * is found in the buffer. If loading more certificates is
913  * optional, break without raising an error
914  */
915  if (optional
916  && ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
917  {
918  /* remove that error from error stack */
919  (void)ERR_get_error();
920  break;
921  }
922 
923  /* Otherwise, bail out with error */
924  crypto_msg(M_FATAL, "Error reading extra certificate");
925  }
926  /* takes ownership of cert like a set1 method */
927  if (SSL_CTX_add_extra_chain_cert(ctx->ctx, cert) != 1)
928  {
929  crypto_msg(M_FATAL, "Error adding extra certificate");
930  }
931  /* We loaded at least one certificate, so loading more is optional */
932  optional = true;
933  }
934 }
935 
936 void
937 tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file,
938  bool cert_file_inline)
939 {
940  BIO *in = NULL;
941  X509 *x = NULL;
942  int ret = 0;
943 
944  ASSERT(NULL != ctx);
945 
946  if (cert_file_inline)
947  {
948  in = BIO_new_mem_buf((char *) cert_file, -1);
949  }
950  else
951  {
952  in = BIO_new_file(cert_file, "r");
953  }
954 
955  if (in == NULL)
956  {
957  SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
958  goto end;
959  }
960 
961  x = PEM_read_bio_X509(in, NULL,
964  if (x == NULL)
965  {
966  SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_PEM_LIB);
967  goto end;
968  }
969 
970  ret = SSL_CTX_use_certificate(ctx->ctx, x);
971  if (ret)
972  {
973  tls_ctx_add_extra_certs(ctx, in, true);
974  }
975 
976 end:
977  if (!ret)
978  {
979  if (cert_file_inline)
980  {
981  crypto_msg(M_FATAL, "Cannot load inline certificate file");
982  }
983  else
984  {
985  crypto_msg(M_FATAL, "Cannot load certificate file %s", cert_file);
986  }
987  }
988  else
989  {
991  }
992 
993  if (in != NULL)
994  {
995  BIO_free(in);
996  }
997  if (x)
998  {
999  X509_free(x);
1000  }
1001 }
1002 
1003 int
1004 tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file,
1005  bool priv_key_file_inline)
1006 {
1007  SSL_CTX *ssl_ctx = NULL;
1008  BIO *in = NULL;
1009  EVP_PKEY *pkey = NULL;
1010  int ret = 1;
1011 
1012  ASSERT(NULL != ctx);
1013 
1014  ssl_ctx = ctx->ctx;
1015 
1016  if (priv_key_file_inline)
1017  {
1018  in = BIO_new_mem_buf((char *) priv_key_file, -1);
1019  }
1020  else
1021  {
1022  in = BIO_new_file(priv_key_file, "r");
1023  }
1024 
1025  if (!in)
1026  {
1027  goto end;
1028  }
1029 
1030  pkey = PEM_read_bio_PrivateKey(in, NULL,
1033  if (!pkey)
1034  {
1035  pkey = engine_load_key(priv_key_file, ctx->ctx);
1036  }
1037 
1038  if (!pkey || !SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1039  {
1040 #ifdef ENABLE_MANAGEMENT
1041  if (management && (ERR_GET_REASON(ERR_peek_error()) == EVP_R_BAD_DECRYPT))
1042  {
1044  }
1045 #endif
1046  crypto_msg(M_WARN, "Cannot load private key file %s",
1047  print_key_filename(priv_key_file, priv_key_file_inline));
1048  goto end;
1049  }
1050 
1051  /* Check Private Key */
1052  if (!SSL_CTX_check_private_key(ssl_ctx))
1053  {
1054  crypto_msg(M_FATAL, "Private key does not match the certificate");
1055  }
1056  ret = 0;
1057 
1058 end:
1059  if (pkey)
1060  {
1061  EVP_PKEY_free(pkey);
1062  }
1063  if (in)
1064  {
1065  BIO_free(in);
1066  }
1067  return ret;
1068 }
1069 
1070 void
1071 backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file,
1072  bool crl_inline)
1073 {
1074  BIO *in = NULL;
1075 
1076  X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx->ctx);
1077  if (!store)
1078  {
1079  crypto_msg(M_FATAL, "Cannot get certificate store");
1080  }
1081 
1082  /* Always start with a cleared CRL list, for that we
1083  * we need to manually find the CRL object from the stack
1084  * and remove it */
1085  STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
1086  for (int i = 0; i < sk_X509_OBJECT_num(objs); i++)
1087  {
1088  X509_OBJECT *obj = sk_X509_OBJECT_value(objs, i);
1089  ASSERT(obj);
1090  if (X509_OBJECT_get_type(obj) == X509_LU_CRL)
1091  {
1092  sk_X509_OBJECT_delete(objs, i);
1093  X509_OBJECT_free(obj);
1094  }
1095  }
1096 
1097  X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1098 
1099  if (crl_inline)
1100  {
1101  in = BIO_new_mem_buf((char *) crl_file, -1);
1102  }
1103  else
1104  {
1105  in = BIO_new_file(crl_file, "r");
1106  }
1107 
1108  if (in == NULL)
1109  {
1110  msg(M_WARN, "CRL: cannot read: %s",
1111  print_key_filename(crl_file, crl_inline));
1112  goto end;
1113  }
1114 
1115  int num_crls_loaded = 0;
1116  while (true)
1117  {
1118  X509_CRL *crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
1119  if (crl == NULL)
1120  {
1121  /*
1122  * PEM_R_NO_START_LINE can be considered equivalent to EOF.
1123  */
1124  bool eof = ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE;
1125  /* but warn if no CRLs have been loaded */
1126  if (num_crls_loaded > 0 && eof)
1127  {
1128  /* remove that error from error stack */
1129  (void)ERR_get_error();
1130  break;
1131  }
1132 
1133  crypto_msg(M_WARN, "CRL: cannot read CRL from file %s",
1134  print_key_filename(crl_file, crl_inline));
1135  break;
1136  }
1137 
1138  if (!X509_STORE_add_crl(store, crl))
1139  {
1140  X509_CRL_free(crl);
1141  crypto_msg(M_WARN, "CRL: cannot add %s to store",
1142  print_key_filename(crl_file, crl_inline));
1143  break;
1144  }
1145  X509_CRL_free(crl);
1146  num_crls_loaded++;
1147  }
1148  msg(M_INFO, "CRL: loaded %d CRLs from file %s", num_crls_loaded, crl_file);
1149 end:
1150  BIO_free(in);
1151 }
1152 
1153 
1154 #ifdef ENABLE_MANAGEMENT
1155 
1156 /* encrypt */
1157 static int
1158 rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1159 {
1160  ASSERT(0);
1161  return -1;
1162 }
1163 
1164 /* verify arbitrary data */
1165 static int
1166 rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1167 {
1168  ASSERT(0);
1169  return -1;
1170 }
1171 
1172 /* decrypt */
1173 static int
1174 rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1175 {
1176  ASSERT(0);
1177  return -1;
1178 }
1179 
1180 /* called at RSA_free */
1181 static int
1183 {
1184  /* meth was allocated in tls_ctx_use_management_external_key() ; since
1185  * this function is called when the parent RSA object is destroyed,
1186  * it is no longer used after this point so kill it. */
1187  const RSA_METHOD *meth = RSA_get_method(rsa);
1188  RSA_meth_free((RSA_METHOD *)meth);
1189  return 1;
1190 }
1191 
1192 /*
1193  * Convert OpenSSL's constant to the strings used in the management
1194  * interface query
1195  */
1196 const char *
1197 get_rsa_padding_name(const int padding)
1198 {
1199  switch (padding)
1200  {
1201  case RSA_PKCS1_PADDING:
1202  return "RSA_PKCS1_PADDING";
1203 
1204  case RSA_NO_PADDING:
1205  return "RSA_NO_PADDING";
1206 
1207  default:
1208  return "UNKNOWN";
1209  }
1210 }
1211 
1223 static int
1224 get_sig_from_man(const unsigned char *dgst, unsigned int dgstlen,
1225  unsigned char *sig, unsigned int siglen,
1226  const char *algorithm)
1227 {
1228  char *in_b64 = NULL;
1229  char *out_b64 = NULL;
1230  int len = -1;
1231 
1232  int bencret = openvpn_base64_encode(dgst, dgstlen, &in_b64);
1233 
1234  if (management && bencret > 0)
1235  {
1236  out_b64 = management_query_pk_sig(management, in_b64, algorithm);
1237 
1238  }
1239  if (out_b64)
1240  {
1241  len = openvpn_base64_decode(out_b64, sig, siglen);
1242  }
1243 
1244  free(in_b64);
1245  free(out_b64);
1246  return len;
1247 }
1248 
1249 /* sign arbitrary data */
1250 static int
1251 rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,
1252  int padding)
1253 {
1254  unsigned int len = RSA_size(rsa);
1255  int ret = -1;
1256 
1257  if (padding != RSA_PKCS1_PADDING && padding != RSA_NO_PADDING)
1258  {
1259  RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
1260  return -1;
1261  }
1262 
1263  ret = get_sig_from_man(from, flen, to, len, get_rsa_padding_name(padding));
1264 
1265  return (ret == len) ? ret : -1;
1266 }
1267 
1268 static int
1269 tls_ctx_use_external_rsa_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
1270 {
1271  RSA *rsa = NULL;
1272  RSA *pub_rsa;
1273  RSA_METHOD *rsa_meth;
1274 
1275  ASSERT(NULL != ctx);
1276 
1277  pub_rsa = EVP_PKEY_get0_RSA(pkey);
1278  ASSERT(NULL != pub_rsa);
1279 
1280  /* allocate custom RSA method object */
1281  rsa_meth = RSA_meth_new("OpenVPN external private key RSA Method",
1282  RSA_METHOD_FLAG_NO_CHECK);
1283  check_malloc_return(rsa_meth);
1284  RSA_meth_set_pub_enc(rsa_meth, rsa_pub_enc);
1285  RSA_meth_set_pub_dec(rsa_meth, rsa_pub_dec);
1288  RSA_meth_set_init(rsa_meth, NULL);
1290  RSA_meth_set0_app_data(rsa_meth, NULL);
1291 
1292  /* allocate RSA object */
1293  rsa = RSA_new();
1294  if (rsa == NULL)
1295  {
1296  SSLerr(SSL_F_SSL_USE_PRIVATEKEY, ERR_R_MALLOC_FAILURE);
1297  goto err;
1298  }
1299 
1300  /* initialize RSA object */
1301  const BIGNUM *n = NULL;
1302  const BIGNUM *e = NULL;
1303  RSA_get0_key(pub_rsa, &n, &e, NULL);
1304  RSA_set0_key(rsa, BN_dup(n), BN_dup(e), NULL);
1305  RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY);
1306  if (!RSA_set_method(rsa, rsa_meth))
1307  {
1308  RSA_meth_free(rsa_meth);
1309  goto err;
1310  }
1311  /* from this point rsa_meth will get freed with rsa */
1312 
1313  /* bind our custom RSA object to ssl_ctx */
1314  if (!SSL_CTX_use_RSAPrivateKey(ctx->ctx, rsa))
1315  {
1316  goto err;
1317  }
1318 
1319  RSA_free(rsa); /* doesn't necessarily free, just decrements refcount */
1320  return 1;
1321 
1322 err:
1323  if (rsa)
1324  {
1325  RSA_free(rsa);
1326  }
1327  else
1328  {
1329  if (rsa_meth)
1330  {
1331  RSA_meth_free(rsa_meth);
1332  }
1333  }
1334  return 0;
1335 }
1336 
1337 #if ((OPENSSL_VERSION_NUMBER > 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)) \
1338  || LIBRESSL_VERSION_NUMBER > 0x2090000fL) \
1339  && !defined(OPENSSL_NO_EC)
1340 
1341 /* called when EC_KEY is destroyed */
1342 static void
1343 openvpn_extkey_ec_finish(EC_KEY *ec)
1344 {
1345  /* release the method structure */
1346  const EC_KEY_METHOD *ec_meth = EC_KEY_get_method(ec);
1347  EC_KEY_METHOD_free((EC_KEY_METHOD *) ec_meth);
1348 }
1349 
1350 /* EC_KEY_METHOD callback: sign().
1351  * Sign the hash using EC key and return DER encoded signature in sig,
1352  * its length in siglen. Return value is 1 on success, 0 on error.
1353  */
1354 static int
1355 ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig,
1356  unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *ec)
1357 {
1358  int capacity = ECDSA_size(ec);
1359  /*
1360  * ECDSA does not seem to have proper constants for paddings since
1361  * there are only signatures without padding at the moment, use
1362  * a generic ECDSA for the moment
1363  */
1364  int len = get_sig_from_man(dgst, dgstlen, sig, capacity, "ECDSA");
1365 
1366  if (len > 0)
1367  {
1368  *siglen = len;
1369  return 1;
1370  }
1371  return 0;
1372 }
1373 
1374 /* EC_KEY_METHOD callback: sign_setup(). We do no precomputations */
1375 static int
1376 ecdsa_sign_setup(EC_KEY *ec, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
1377 {
1378  return 1;
1379 }
1380 
1381 /* EC_KEY_METHOD callback: sign_sig().
1382  * Sign the hash and return the result as a newly allocated ECDS_SIG
1383  * struct or NULL on error.
1384  */
1385 static ECDSA_SIG *
1386 ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_kinv,
1387  const BIGNUM *in_r, EC_KEY *ec)
1388 {
1389  ECDSA_SIG *ecsig = NULL;
1390  unsigned int len = ECDSA_size(ec);
1391  struct gc_arena gc = gc_new();
1392 
1393  unsigned char *buf = gc_malloc(len, false, &gc);
1394  if (ecdsa_sign(0, dgst, dgstlen, buf, &len, NULL, NULL, ec) != 1)
1395  {
1396  goto out;
1397  }
1398  /* const char ** should be avoided: not up to us, so we cast our way through */
1399  ecsig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&buf, len);
1400 
1401 out:
1402  gc_free(&gc);
1403  return ecsig;
1404 }
1405 
1406 static int
1407 tls_ctx_use_external_ec_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
1408 {
1409  EC_KEY *ec = NULL;
1410  EVP_PKEY *privkey = NULL;
1411  EC_KEY_METHOD *ec_method;
1412 
1413  ASSERT(ctx);
1414 
1415  ec_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL());
1416  if (!ec_method)
1417  {
1418  goto err;
1419  }
1420 
1421  /* Among init methods, we only need the finish method */
1422  EC_KEY_METHOD_set_init(ec_method, NULL, openvpn_extkey_ec_finish, NULL, NULL, NULL, NULL);
1423  EC_KEY_METHOD_set_sign(ec_method, ecdsa_sign, ecdsa_sign_setup, ecdsa_sign_sig);
1424 
1425  ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(pkey));
1426  if (!ec)
1427  {
1428  EC_KEY_METHOD_free(ec_method);
1429  goto err;
1430  }
1431  if (!EC_KEY_set_method(ec, ec_method))
1432  {
1433  EC_KEY_METHOD_free(ec_method);
1434  goto err;
1435  }
1436  /* from this point ec_method will get freed when ec is freed */
1437 
1438  privkey = EVP_PKEY_new();
1439  if (!EVP_PKEY_assign_EC_KEY(privkey, ec))
1440  {
1441  goto err;
1442  }
1443  /* from this point ec will get freed when privkey is freed */
1444 
1445  if (!SSL_CTX_use_PrivateKey(ctx->ctx, privkey))
1446  {
1447  ec = NULL; /* avoid double freeing it below */
1448  goto err;
1449  }
1450 
1451  EVP_PKEY_free(privkey); /* this will down ref privkey and ec */
1452  return 1;
1453 
1454 err:
1455  /* Reach here only when ec and privkey can be independenly freed */
1456  if (privkey)
1457  {
1458  EVP_PKEY_free(privkey);
1459  }
1460  if (ec)
1461  {
1462  EC_KEY_free(ec);
1463  }
1464  return 0;
1465 }
1466 #endif /* OPENSSL_VERSION_NUMBER > 1.1.0 dev && !defined(OPENSSL_NO_EC) */
1467 
1468 int
1470 {
1471  int ret = 1;
1472 
1473  ASSERT(NULL != ctx);
1474 
1475  X509 *cert = SSL_CTX_get0_certificate(ctx->ctx);
1476 
1477  ASSERT(NULL != cert);
1478 
1479  /* get the public key */
1480  EVP_PKEY *pkey = X509_get0_pubkey(cert);
1481  ASSERT(pkey); /* NULL before SSL_CTX_use_certificate() is called */
1482 
1483  if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
1484  {
1485  if (!tls_ctx_use_external_rsa_key(ctx, pkey))
1486  {
1487  goto cleanup;
1488  }
1489  }
1490 #if ((OPENSSL_VERSION_NUMBER > 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)) \
1491  || LIBRESSL_VERSION_NUMBER > 0x2090000fL) \
1492  && !defined(OPENSSL_NO_EC)
1493  else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC)
1494  {
1495  if (!tls_ctx_use_external_ec_key(ctx, pkey))
1496  {
1497  goto cleanup;
1498  }
1499  }
1500  else
1501  {
1502  crypto_msg(M_WARN, "management-external-key requires an RSA or EC certificate");
1503  goto cleanup;
1504  }
1505 #else /* OPENSSL_VERSION_NUMBER > 1.1.0 dev && !defined(OPENSSL_NO_EC) */
1506  else
1507  {
1508  crypto_msg(M_WARN, "management-external-key requires an RSA certificate");
1509  goto cleanup;
1510  }
1511 #endif /* OPENSSL_VERSION_NUMBER > 1.1.0 dev && !defined(OPENSSL_NO_EC) */
1512 
1513  ret = 0;
1514 cleanup:
1515  if (ret)
1516  {
1517  crypto_msg(M_FATAL, "Cannot enable SSL external private key capability");
1518  }
1519  return ret;
1520 }
1521 
1522 #endif /* ifdef ENABLE_MANAGEMENT */
1523 
1524 static int
1525 sk_x509_name_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1526 {
1527  return X509_NAME_cmp(*a, *b);
1528 }
1529 
1530 void
1531 tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file,
1532  bool ca_file_inline, const char *ca_path, bool tls_server)
1533 {
1534  STACK_OF(X509_INFO) *info_stack = NULL;
1535  STACK_OF(X509_NAME) *cert_names = NULL;
1536  X509_LOOKUP *lookup = NULL;
1537  X509_STORE *store = NULL;
1538  X509_NAME *xn = NULL;
1539  BIO *in = NULL;
1540  int i, added = 0, prev = 0;
1541 
1542  ASSERT(NULL != ctx);
1543 
1544  store = SSL_CTX_get_cert_store(ctx->ctx);
1545  if (!store)
1546  {
1547  crypto_msg(M_FATAL, "Cannot get certificate store");
1548  }
1549 
1550  /* Try to add certificates and CRLs from ca_file */
1551  if (ca_file)
1552  {
1553  if (ca_file_inline)
1554  {
1555  in = BIO_new_mem_buf((char *)ca_file, -1);
1556  }
1557  else
1558  {
1559  in = BIO_new_file(ca_file, "r");
1560  }
1561 
1562  if (in)
1563  {
1564  info_stack = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
1565  }
1566 
1567  if (info_stack)
1568  {
1569  for (i = 0; i < sk_X509_INFO_num(info_stack); i++)
1570  {
1571  X509_INFO *info = sk_X509_INFO_value(info_stack, i);
1572  if (info->crl)
1573  {
1574  X509_STORE_add_crl(store, info->crl);
1575  }
1576 
1577  if (tls_server && !info->x509)
1578  {
1579  crypto_msg(M_FATAL, "X509 name was missing in TLS mode");
1580  }
1581 
1582  if (info->x509)
1583  {
1584  X509_STORE_add_cert(store, info->x509);
1585  added++;
1586 
1587  if (!tls_server)
1588  {
1589  continue;
1590  }
1591 
1592  /* Use names of CAs as a client CA list */
1593  if (cert_names == NULL)
1594  {
1595  cert_names = sk_X509_NAME_new(sk_x509_name_cmp);
1596  if (!cert_names)
1597  {
1598  continue;
1599  }
1600  }
1601 
1602  xn = X509_get_subject_name(info->x509);
1603  if (!xn)
1604  {
1605  continue;
1606  }
1607 
1608  /* Don't add duplicate CA names */
1609  if (sk_X509_NAME_find(cert_names, xn) == -1)
1610  {
1611  xn = X509_NAME_dup(xn);
1612  if (!xn)
1613  {
1614  continue;
1615  }
1616  sk_X509_NAME_push(cert_names, xn);
1617  }
1618  }
1619 
1620  if (tls_server)
1621  {
1622  int cnum = sk_X509_NAME_num(cert_names);
1623  if (cnum != (prev + 1))
1624  {
1626  "Cannot load CA certificate file %s (entry %d did not validate)",
1627  print_key_filename(ca_file, ca_file_inline),
1628  added);
1629  }
1630  prev = cnum;
1631  }
1632  }
1633  sk_X509_INFO_pop_free(info_stack, X509_INFO_free);
1634  }
1635 
1636  if (tls_server)
1637  {
1638  SSL_CTX_set_client_CA_list(ctx->ctx, cert_names);
1639  }
1640 
1641  if (!added)
1642  {
1644  "Cannot load CA certificate file %s (no entries were read)",
1645  print_key_filename(ca_file, ca_file_inline));
1646  }
1647 
1648  if (tls_server)
1649  {
1650  int cnum = sk_X509_NAME_num(cert_names);
1651  if (cnum != added)
1652  {
1653  crypto_msg(M_FATAL, "Cannot load CA certificate file %s (only %d "
1654  "of %d entries were valid X509 names)",
1655  print_key_filename(ca_file, ca_file_inline), cnum,
1656  added);
1657  }
1658  }
1659 
1660  if (in)
1661  {
1662  BIO_free(in);
1663  }
1664  }
1665 
1666  /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
1667  if (ca_path)
1668  {
1669  lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1670  if (lookup && X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM))
1671  {
1672  msg(M_WARN, "WARNING: experimental option --capath %s", ca_path);
1673  }
1674  else
1675  {
1676  crypto_msg(M_FATAL, "Cannot add lookup at --capath %s", ca_path);
1677  }
1678  X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1679  }
1680 }
1681 
1682 void
1683 tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
1684  bool extra_certs_file_inline)
1685 {
1686  BIO *in;
1687  if (extra_certs_file_inline)
1688  {
1689  in = BIO_new_mem_buf((char *)extra_certs_file, -1);
1690  }
1691  else
1692  {
1693  in = BIO_new_file(extra_certs_file, "r");
1694  }
1695 
1696  if (in == NULL)
1697  {
1698  crypto_msg(M_FATAL, "Cannot load extra-certs file: %s",
1699  print_key_filename(extra_certs_file,
1700  extra_certs_file_inline));
1701 
1702  }
1703  else
1704  {
1705  tls_ctx_add_extra_certs(ctx, in, false);
1706  }
1707 
1708  BIO_free(in);
1709 }
1710 
1711 /* **************************************
1712  *
1713  * Key-state specific functions
1714  *
1715  ***************************************/
1716 /*
1717  *
1718  * BIO functions
1719  *
1720  */
1721 
1722 #ifdef BIO_DEBUG
1723 
1724 #warning BIO_DEBUG defined
1725 
1726 static FILE *biofp; /* GLOBAL */
1727 static bool biofp_toggle; /* GLOBAL */
1728 static time_t biofp_last_open; /* GLOBAL */
1729 static const int biofp_reopen_interval = 600; /* GLOBAL */
1730 
1731 static void
1732 close_biofp(void)
1733 {
1734  if (biofp)
1735  {
1736  ASSERT(!fclose(biofp));
1737  biofp = NULL;
1738  }
1739 }
1740 
1741 static void
1742 open_biofp(void)
1743 {
1744  const time_t current = time(NULL);
1745  const pid_t pid = getpid();
1746 
1747  if (biofp_last_open + biofp_reopen_interval < current)
1748  {
1749  close_biofp();
1750  }
1751  if (!biofp)
1752  {
1753  char fn[256];
1754  openvpn_snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
1755  biofp = fopen(fn, "w");
1756  ASSERT(biofp);
1757  biofp_last_open = time(NULL);
1758  biofp_toggle ^= 1;
1759  }
1760 }
1761 
1762 static void
1763 bio_debug_data(const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
1764 {
1765  struct gc_arena gc = gc_new();
1766  if (len > 0)
1767  {
1768  open_biofp();
1769  fprintf(biofp, "BIO_%s %s time=%" PRIi64 " bio=" ptr_format " len=%d data=%s\n",
1770  mode, desc, (int64_t)time(NULL), (ptr_type)bio, len, format_hex(buf, len, 0, &gc));
1771  fflush(biofp);
1772  }
1773  gc_free(&gc);
1774 }
1775 
1776 static void
1777 bio_debug_oc(const char *mode, BIO *bio)
1778 {
1779  open_biofp();
1780  fprintf(biofp, "BIO %s time=%" PRIi64 " bio=" ptr_format "\n",
1781  mode, (int64_t)time(NULL), (ptr_type)bio);
1782  fflush(biofp);
1783 }
1784 
1785 #endif /* ifdef BIO_DEBUG */
1786 
1787 /*
1788  * Write to an OpenSSL BIO in non-blocking mode.
1789  */
1790 static int
1791 bio_write(BIO *bio, const uint8_t *data, int size, const char *desc)
1792 {
1793  int i;
1794  int ret = 0;
1795  ASSERT(size >= 0);
1796  if (size)
1797  {
1798  /*
1799  * Free the L_TLS lock prior to calling BIO routines
1800  * so that foreground thread can still call
1801  * tls_pre_decrypt or tls_pre_encrypt,
1802  * allowing tunnel packet forwarding to continue.
1803  */
1804 #ifdef BIO_DEBUG
1805  bio_debug_data("write", bio, data, size, desc);
1806 #endif
1807  i = BIO_write(bio, data, size);
1808 
1809  if (i < 0)
1810  {
1811  if (BIO_should_retry(bio))
1812  {
1813  }
1814  else
1815  {
1816  crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s error", desc);
1817  ret = -1;
1818  ERR_clear_error();
1819  }
1820  }
1821  else if (i != size)
1822  {
1823  crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s incomplete %d/%d",
1824  desc, i, size);
1825  ret = -1;
1826  ERR_clear_error();
1827  }
1828  else
1829  { /* successful write */
1830  dmsg(D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
1831  ret = 1;
1832  }
1833  }
1834  return ret;
1835 }
1836 
1837 /*
1838  * Inline functions for reading from and writing
1839  * to BIOs.
1840  */
1841 
1842 static void
1843 bio_write_post(const int status, struct buffer *buf)
1844 {
1845  if (status == 1) /* success status return from bio_write? */
1846  {
1847  memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
1848  buf->len = 0;
1849  }
1850 }
1851 
1852 /*
1853  * Read from an OpenSSL BIO in non-blocking mode.
1854  */
1855 static int
1856 bio_read(BIO *bio, struct buffer *buf, int maxlen, const char *desc)
1857 {
1858  int i;
1859  int ret = 0;
1860  ASSERT(buf->len >= 0);
1861  if (buf->len)
1862  {
1863  }
1864  else
1865  {
1866  int len = buf_forward_capacity(buf);
1867  if (maxlen < len)
1868  {
1869  len = maxlen;
1870  }
1871 
1872  /*
1873  * BIO_read brackets most of the serious RSA
1874  * key negotiation number crunching.
1875  */
1876  i = BIO_read(bio, BPTR(buf), len);
1877 
1878  VALGRIND_MAKE_READABLE((void *) &i, sizeof(i));
1879 
1880 #ifdef BIO_DEBUG
1881  bio_debug_data("read", bio, BPTR(buf), i, desc);
1882 #endif
1883  if (i < 0)
1884  {
1885  if (BIO_should_retry(bio))
1886  {
1887  }
1888  else
1889  {
1890  crypto_msg(D_TLS_ERRORS, "TLS_ERROR: BIO read %s error", desc);
1891  buf->len = 0;
1892  ret = -1;
1893  ERR_clear_error();
1894  }
1895  }
1896  else if (!i)
1897  {
1898  buf->len = 0;
1899  }
1900  else
1901  { /* successful read */
1902  dmsg(D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
1903  buf->len = i;
1904  ret = 1;
1905  VALGRIND_MAKE_READABLE((void *) BPTR(buf), BLEN(buf));
1906  }
1907  }
1908  return ret;
1909 }
1910 
1911 void
1912 key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
1913 {
1914  ASSERT(NULL != ssl_ctx);
1915  ASSERT(ks_ssl);
1916  CLEAR(*ks_ssl);
1917 
1918  ks_ssl->ssl = SSL_new(ssl_ctx->ctx);
1919  if (!ks_ssl->ssl)
1920  {
1921  crypto_msg(M_FATAL, "SSL_new failed");
1922  }
1923 
1924  /* put session * in ssl object so we can access it
1925  * from verify callback*/
1926  SSL_set_ex_data(ks_ssl->ssl, mydata_index, session);
1927 
1928  ASSERT((ks_ssl->ssl_bio = BIO_new(BIO_f_ssl())));
1929  ASSERT((ks_ssl->ct_in = BIO_new(BIO_s_mem())));
1930  ASSERT((ks_ssl->ct_out = BIO_new(BIO_s_mem())));
1931 
1932 #ifdef BIO_DEBUG
1933  bio_debug_oc("open ssl_bio", ks_ssl->ssl_bio);
1934  bio_debug_oc("open ct_in", ks_ssl->ct_in);
1935  bio_debug_oc("open ct_out", ks_ssl->ct_out);
1936 #endif
1937 
1938  if (is_server)
1939  {
1940  SSL_set_accept_state(ks_ssl->ssl);
1941  }
1942  else
1943  {
1944  SSL_set_connect_state(ks_ssl->ssl);
1945  }
1946 
1947  SSL_set_bio(ks_ssl->ssl, ks_ssl->ct_in, ks_ssl->ct_out);
1948  BIO_set_ssl(ks_ssl->ssl_bio, ks_ssl->ssl, BIO_NOCLOSE);
1949 }
1950 
1951 void
1953 {
1954  if (ks_ssl->ssl)
1955  {
1956 #ifdef BIO_DEBUG
1957  bio_debug_oc("close ssl_bio", ks_ssl->ssl_bio);
1958  bio_debug_oc("close ct_in", ks_ssl->ct_in);
1959  bio_debug_oc("close ct_out", ks_ssl->ct_out);
1960 #endif
1961  BIO_free_all(ks_ssl->ssl_bio);
1962  SSL_free(ks_ssl->ssl);
1963  }
1964 }
1965 
1966 int
1967 key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
1968 {
1969  int ret = 0;
1971 
1972 #ifdef ENABLE_CRYPTO_OPENSSL
1973  ASSERT(NULL != ks_ssl);
1974 
1975  ret = bio_write(ks_ssl->ssl_bio, BPTR(buf), BLEN(buf),
1976  "tls_write_plaintext");
1977  bio_write_post(ret, buf);
1978 #endif /* ENABLE_CRYPTO_OPENSSL */
1979 
1980  perf_pop();
1981  return ret;
1982 }
1983 
1984 int
1985 key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
1986 {
1987  int ret = 0;
1989 
1990  ASSERT(NULL != ks_ssl);
1991 
1992  ret = bio_write(ks_ssl->ssl_bio, data, len, "tls_write_plaintext_const");
1993 
1994  perf_pop();
1995  return ret;
1996 }
1997 
1998 int
1999 key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf,
2000  int maxlen)
2001 {
2002  int ret = 0;
2004 
2005  ASSERT(NULL != ks_ssl);
2006 
2007  ret = bio_read(ks_ssl->ct_out, buf, maxlen, "tls_read_ciphertext");
2008 
2009  perf_pop();
2010  return ret;
2011 }
2012 
2013 int
2015 {
2016  int ret = 0;
2018 
2019  ASSERT(NULL != ks_ssl);
2020 
2021  ret = bio_write(ks_ssl->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
2022  bio_write_post(ret, buf);
2023 
2024  perf_pop();
2025  return ret;
2026 }
2027 
2028 int
2029 key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf,
2030  int maxlen)
2031 {
2032  int ret = 0;
2034 
2035  ASSERT(NULL != ks_ssl);
2036 
2037  ret = bio_read(ks_ssl->ssl_bio, buf, maxlen, "tls_read_plaintext");
2038 
2039  perf_pop();
2040  return ret;
2041 }
2042 
2043 /* **************************************
2044  *
2045  * Information functions
2046  *
2047  * Print information for the end user.
2048  *
2049  ***************************************/
2050 void
2051 print_details(struct key_state_ssl *ks_ssl, const char *prefix)
2052 {
2053  const SSL_CIPHER *ciph;
2054  X509 *cert;
2055  char s1[256];
2056  char s2[256];
2057 
2058  s1[0] = s2[0] = 0;
2059  ciph = SSL_get_current_cipher(ks_ssl->ssl);
2060  openvpn_snprintf(s1, sizeof(s1), "%s %s, cipher %s %s",
2061  prefix,
2062  SSL_get_version(ks_ssl->ssl),
2063  SSL_CIPHER_get_version(ciph),
2064  SSL_CIPHER_get_name(ciph));
2065  cert = SSL_get_peer_certificate(ks_ssl->ssl);
2066  if (cert != NULL)
2067  {
2068  EVP_PKEY *pkey = X509_get_pubkey(cert);
2069  if (pkey != NULL)
2070  {
2071  if ((EVP_PKEY_id(pkey) == EVP_PKEY_RSA) && (EVP_PKEY_get0_RSA(pkey) != NULL))
2072  {
2073  RSA *rsa = EVP_PKEY_get0_RSA(pkey);
2074  openvpn_snprintf(s2, sizeof(s2), ", %d bit RSA",
2075  RSA_bits(rsa));
2076  }
2077  else if ((EVP_PKEY_id(pkey) == EVP_PKEY_DSA) && (EVP_PKEY_get0_DSA(pkey) != NULL))
2078  {
2079  DSA *dsa = EVP_PKEY_get0_DSA(pkey);
2080  openvpn_snprintf(s2, sizeof(s2), ", %d bit DSA",
2081  DSA_bits(dsa));
2082  }
2083 #ifndef OPENSSL_NO_EC
2084  else if ((EVP_PKEY_id(pkey) == EVP_PKEY_EC) && (EVP_PKEY_get0_EC_KEY(pkey) != NULL))
2085  {
2086  EC_KEY *ec = EVP_PKEY_get0_EC_KEY(pkey);
2087  const EC_GROUP *group = EC_KEY_get0_group(ec);
2088  const char *curve;
2089 
2090  int nid = EC_GROUP_get_curve_name(group);
2091  if (nid == 0 || (curve = OBJ_nid2sn(nid)) == NULL)
2092  {
2093  curve = "Error getting curve name";
2094  }
2095 
2096  openvpn_snprintf(s2, sizeof(s2), ", %d bit EC, curve: %s",
2097  EC_GROUP_order_bits(group), curve);
2098 
2099  }
2100 #endif
2101  EVP_PKEY_free(pkey);
2102  }
2103  X509_free(cert);
2104  }
2105  /* The SSL API does not allow us to look at temporary RSA/DH keys,
2106  * otherwise we should print their lengths too */
2107  msg(D_HANDSHAKE, "%s%s", s1, s2);
2108 }
2109 
2110 void
2111 show_available_tls_ciphers_list(const char *cipher_list,
2112  const char *tls_cert_profile,
2113  bool tls13)
2114 {
2115  struct tls_root_ctx tls_ctx;
2116 
2117  tls_ctx.ctx = SSL_CTX_new(SSLv23_method());
2118  if (!tls_ctx.ctx)
2119  {
2120  crypto_msg(M_FATAL, "Cannot create SSL_CTX object");
2121  }
2122 
2123 #if defined(TLS1_3_VERSION)
2124  if (tls13)
2125  {
2128  tls_ctx_restrict_ciphers_tls13(&tls_ctx, cipher_list);
2129  }
2130  else
2131 #endif
2132  {
2133  SSL_CTX_set_max_proto_version(tls_ctx.ctx, TLS1_2_VERSION);
2134  tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
2135  }
2136 
2137  tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
2138 
2139  SSL *ssl = SSL_new(tls_ctx.ctx);
2140  if (!ssl)
2141  {
2142  crypto_msg(M_FATAL, "Cannot create SSL object");
2143  }
2144 
2145 #if (OPENSSL_VERSION_NUMBER < 0x1010000fL) \
2146  || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER <= 0x2090000fL)
2147  STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
2148 #else
2149  STACK_OF(SSL_CIPHER) *sk = SSL_get1_supported_ciphers(ssl);
2150 #endif
2151  for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++)
2152  {
2153  const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i);
2154 
2155  const char *cipher_name = SSL_CIPHER_get_name(c);
2156 
2157  const tls_cipher_name_pair *pair =
2158  tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
2159 
2160  if (tls13)
2161  {
2162  printf("%s\n", cipher_name);
2163  }
2164  else if (NULL == pair)
2165  {
2166  /* No translation found, print warning */
2167  printf("%s (No IANA name known to OpenVPN, use OpenSSL name.)\n",
2168  cipher_name);
2169  }
2170  else
2171  {
2172  printf("%s\n", pair->iana_name);
2173  }
2174  }
2175 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL)
2176  sk_SSL_CIPHER_free(sk);
2177 #endif
2178  SSL_free(ssl);
2179  SSL_CTX_free(tls_ctx.ctx);
2180 }
2181 
2182 /*
2183  * Show the Elliptic curves that are available for us to use
2184  * in the OpenSSL library.
2185  */
2186 void
2188 {
2189  printf("Consider using openssl 'ecparam -list_curves' as\n"
2190  "alternative to running this command.\n");
2191 #ifndef OPENSSL_NO_EC
2192  EC_builtin_curve *curves = NULL;
2193  size_t crv_len = 0;
2194  size_t n = 0;
2195 
2196  crv_len = EC_get_builtin_curves(NULL, 0);
2197  ALLOC_ARRAY(curves, EC_builtin_curve, crv_len);
2198  if (EC_get_builtin_curves(curves, crv_len))
2199  {
2200  printf("\nAvailable Elliptic curves/groups:\n");
2201  for (n = 0; n < crv_len; n++)
2202  {
2203  const char *sname;
2204  sname = OBJ_nid2sn(curves[n].nid);
2205  if (sname == NULL)
2206  {
2207  sname = "";
2208  }
2209 
2210  printf("%s\n", sname);
2211  }
2212  }
2213  else
2214  {
2215  crypto_msg(M_FATAL, "Cannot get list of builtin curves");
2216  }
2217  free(curves);
2218 #else /* ifndef OPENSSL_NO_EC */
2219  msg(M_WARN, "Your OpenSSL library was built without elliptic curve support. "
2220  "No curves available.");
2221 #endif /* ifndef OPENSSL_NO_EC */
2222 }
2223 
2224 void
2226 {
2227  SSL_CTX *ctx;
2228  SSL *ssl;
2229  const char *cipher_name;
2230 
2231  ctx = SSL_CTX_new(SSLv23_method());
2232  if (!ctx)
2233  {
2234  crypto_msg(M_FATAL, "Cannot create SSL_CTX object");
2235  }
2236  ssl = SSL_new(ctx);
2237  if (!ssl)
2238  {
2239  crypto_msg(M_FATAL, "Cannot create SSL object");
2240  }
2241 
2242  cipher_name = SSL_get_cipher_list(ssl, 0);
2243  strncpynt(buf, cipher_name, size);
2244 
2245  SSL_free(ssl);
2246  SSL_CTX_free(ctx);
2247 }
2248 
2249 const char *
2251 {
2253 }
2254 
2255 #endif /* defined(ENABLE_CRYPTO_OPENSSL) */
void tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context for TLS 1.3 and higher...
Definition: ssl_openssl.c:504
#define INFO_CALLBACK_SSL_CONST
Definition: ssl_openssl.c:198
void print_details(struct key_state_ssl *ks_ssl, const char *prefix)
Definition: ssl_openssl.c:2051
static int rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1174
EVP_PKEY * engine_load_key(const char *file, SSL_CTX *ctx)
Load a key file from an engine.
static void strncpynt(char *dest, const char *src, size_t maxlen)
Definition: buffer.h:348
bool tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Set any library specific options.
Definition: ssl_openssl.c:328
#define D_TLS_DEBUG_LOW
Definition: errlevel.h:77
static void * SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
Fetch the default password callback user data from the SSL context.
void tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
Definition: ssl_openssl.c:890
char * string_alloc(const char *str, struct gc_arena *gc)
Definition: buffer.c:688
#define D_TLS_DEBUG
Definition: errlevel.h:162
void tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
Set the TLS certificate profile.
Definition: ssl_openssl.c:533
#define streq(x, y)
Definition: options.h:653
void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_file_inline, const char *ca_path, bool tls_server)
Load certificate authority certificates from the given file or path.
Definition: ssl_openssl.c:1531
int key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
Insert plaintext data into the TLS module.
Definition: ssl_openssl.c:1985
#define M_INFO
Definition: errlevel.h:55
static pem_password_cb * SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
Fetch the default password callback from the SSL context.
unsigned long ptr_type
Definition: common.h:67
static DSA * EVP_PKEY_get0_DSA(EVP_PKEY *pkey)
Get the DSA object of a public key.
struct tls_options * opt
Definition: ssl_common.h:417
static void gc_free(struct gc_arena *a)
Definition: buffer.h:1023
void crypto_print_openssl_errors(const unsigned int flags)
Retrieve any occurred OpenSSL errors and print those errors.
#define PERF_BIO_WRITE_CIPHERTEXT
Definition: perf.h:41
#define dmsg
Definition: error.h:174
void management_auth_failure(struct management *man, const char *type, const char *reason)
Definition: manage.c:3094
#define D_TLS_ERRORS
Definition: errlevel.h:59
static int rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1158
void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_inline)
Use Windows cryptoapi for key and cert, and add to library-specific TLS context.
Definition: ssl_openssl.c:937
int pem_password_callback(char *buf, int size, int rwflag, void *u)
Callback to retrieve the user&#39;s password.
Definition: ssl.c:369
static int RSA_meth_set_priv_dec(RSA_METHOD *meth, int(*priv_dec)(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding))
Set the private decoding function of an RSA_METHOD object.
void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file, bool extra_certs_file_inline)
Load extra certificate authority certificates from the given file or path.
Definition: ssl_openssl.c:1683
static int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, long tls_ver_min)
Mimics SSL_CTX_set_min_proto_version for OpenSSL < 1.1.
static int RSA_meth_set0_app_data(RSA_METHOD *meth, void *app_data)
Set the application data of an RSA_METHOD object.
bool tls_ctx_initialised(struct tls_root_ctx *ctx)
Checks whether the given TLS context is initialised.
Definition: ssl_openssl.c:155
static void perf_pop(void)
Definition: perf.h:82
#define crypto_msg(flags,...)
Retrieve any OpenSSL errors, then print the supplied error message.
static void perf_push(int type)
Definition: perf.h:78
static char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *gc)
Definition: buffer.h:526
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition: env_set.c:285
#define PERF_BIO_READ_PLAINTEXT
Definition: perf.h:38
static int RSA_meth_set_priv_enc(RSA_METHOD *meth, int(*priv_enc)(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding))
Set the private encoding function of an RSA_METHOD object.
static int RSA_meth_set_pub_dec(RSA_METHOD *meth, int(*pub_dec)(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding))
Set the public decoding function of an RSA_METHOD object.
#define TLS_VER_1_1
Definition: ssl_backend.h:115
const char * ekm_label
Definition: ssl_common.h:378
int key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a plaintext buffer into the TLS module.
Definition: ssl_openssl.c:1967
static EC_KEY * EVP_PKEY_get0_EC_KEY(EVP_PKEY *pkey)
Get the EC_KEY object of a public key.
#define ALLOC_ARRAY(dptr, type, n)
Definition: buffer.h:1056
static void RSA_get0_key(const RSA *rsa, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
Get the RSA parameters.
static int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, long tls_ver_max)
Mimics SSL_CTX_set_max_proto_version for OpenSSL < 1.1.
#define ASSERT(x)
Definition: error.h:221
static int RSA_bits(const RSA *rsa)
Number of significant RSA bits.
#define SSLF_CLIENT_CERT_NOT_REQUIRED
Definition: ssl_common.h:352
int SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
Definition: cryptoapi.c:1128
#define D_LOW
Definition: errlevel.h:97
void tls_ctx_free(struct tls_root_ctx *ctx)
Frees the library-specific TLSv1 context.
Definition: ssl_openssl.c:144
void tls_clear_error(void)
Clear the underlying SSL library&#39;s error state.
Definition: ssl_openssl.c:102
const char * get_rsa_padding_name(const int padding)
Definition: ssl_openssl.c:1197
static void RSA_meth_free(RSA_METHOD *meth)
Free an existing RSA_METHOD object.
static void X509_OBJECT_free(X509_OBJECT *obj)
Destroy a X509 object.
void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool dh_file_inline)
Load Diffie Hellman Parameters, and load them into the library-specific TLS context.
Definition: ssl_openssl.c:654
void convert_tls_list_to_openssl(char *openssl_ciphers, size_t len, const char *ciphers)
Definition: ssl_openssl.c:370
#define TLS_VER_1_2
Definition: ssl_backend.h:116
int len
Length in bytes of the actual content within the allocated memory.
Definition: buffer.h:66
void setenv_del(struct env_set *es, const char *name)
Definition: env_set.c:330
static int rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1251
static void bio_write_post(const int status, struct buffer *buf)
Definition: ssl_openssl.c:1843
#define SSL_CTX_set1_groups
FILE * platform_fopen(const char *path, const char *mode)
Definition: platform.c:302
void convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len, const char *ciphers)
Definition: ssl_openssl.c:477
size_t ekm_size
Definition: ssl_common.h:380
#define CLEAR(x)
Definition: basic.h:33
#define BPTR(buf)
Definition: buffer.h:124
static int tls_ctx_use_external_rsa_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
Definition: ssl_openssl.c:1269
bool openvpn_snprintf(char *str, size_t size, const char *format,...)
Definition: buffer.c:299
static EVP_PKEY * X509_get0_pubkey(const X509 *x)
Get the public key from a X509 certificate.
int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, bool pkcs12_file_inline, bool load_ca_file)
Load PKCS #12 file for key, cert and (optionally) CA certs, and add to library-specific TLS context...
Definition: ssl_openssl.c:763
#define SSLF_TLS_VERSION_MAX_SHIFT
Definition: ssl_common.h:360
const char * iana_name
Definition: ssl_backend.h:62
void show_available_curves(void)
Definition: ssl_openssl.c:2187
#define PERF_BIO_READ_CIPHERTEXT
Definition: perf.h:40
static struct gc_arena gc_new(void)
Definition: buffer.h:1015
void show_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert_profile, bool tls13)
Definition: ssl_openssl.c:2111
int tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_file_inline)
Load private key file into the given TLS context.
Definition: ssl_openssl.c:1004
char * management_query_pk_sig(struct management *man, const char *b64_data, const char *algorithm)
Definition: manage.c:3753
static int RSA_meth_set_pub_enc(RSA_METHOD *meth, int(*pub_enc)(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding))
Set the public encoding function of an RSA_METHOD object.
const char * print_key_filename(const char *str, bool is_inline)
To be used when printing a string that may contain inline data.
Definition: crypto.c:1172
void get_highest_preference_tls_cipher(char *buf, int size)
Definition: ssl_openssl.c:2225
#define SSLF_TLS_VERSION_MIN_MASK
Definition: ssl_common.h:359
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Definition: buffer.c:408
int openvpn_base64_decode(const char *str, void *data, int size)
Definition: base64.c:160
void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_inline)
Reload the Certificate Revocation List for the SSL channel.
Definition: ssl_openssl.c:1071
#define M_DEBUG
Definition: error.h:97
#define PERF_BIO_WRITE_PLAINTEXT
Definition: perf.h:39
int tls_version_max(void)
Return the maximum TLS version (as a TLS_VER_x constant) supported by current SSL implementation...
Definition: ssl_openssl.c:225
static RSA * EVP_PKEY_get0_RSA(EVP_PKEY *pkey)
Get the RSA object of a public key.
static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store)
Fetch the X509 object stack from the X509 store.
int key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf, int maxlen)
Extract plaintext data from the TLS module.
Definition: ssl_openssl.c:2029
static RSA_METHOD * RSA_meth_new(const char *name, int flags)
Allocate a new RSA method object.
static SERVICE_STATUS status
Definition: automatic.c:43
int verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
Verify that the remote OpenVPN peer&#39;s certificate allows setting up a VPN tunnel. ...
static int buf_forward_capacity(const struct buffer *buf)
Definition: buffer.h:562
void key_state_export_keying_material(struct key_state_ssl *ssl, struct tls_session *session)
Keying Material Exporters [RFC 5705] allows additional keying material to be derived from existing TL...
Definition: ssl_openssl.c:162
void tls_init_lib(void)
Perform any static initialisation necessary by the library.
Definition: ssl_openssl.c:77
const char * get_ssl_library_version(void)
return a pointer to a static memory area containing the name and version number of the SSL library in...
Definition: ssl_openssl.c:2250
#define msg
Definition: error.h:173
char * format_hex_ex(const uint8_t *data, int size, int maxoutput, unsigned int space_break_flags, const char *separator, struct gc_arena *gc)
Definition: buffer.c:522
int openvpn_base64_encode(const void *data, int size, char **str)
Definition: base64.c:54
#define OPENSSL_VERSION
Get a tls_cipher_name_pair containing OpenSSL and IANA names for supplied TLS cipher name...
Definition: ssl_backend.h:62
#define D_HANDSHAKE_VERBOSE
Definition: errlevel.h:153
static int rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1166
#define TLS_VER_1_0
Definition: ssl_backend.h:114
const char * source
Definition: compat-lz4.h:433
#define TLS_VER_1_3
Definition: ssl_backend.h:117
void key_state_ssl_free(struct key_state_ssl *ks_ssl)
Free the SSL channel part of the given key state.
Definition: ssl_openssl.c:1952
#define X509_get0_notBefore
void tls_ctx_server_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context for a server.
Definition: ssl_openssl.c:108
#define BLEN(buf)
Definition: buffer.h:127
static void tls_ctx_add_extra_certs(struct tls_root_ctx *ctx, BIO *bio, bool optional)
Definition: ssl_openssl.c:903
#define X509_get0_notAfter
char * strsep(char **stringp, const char *delim)
Definition: compat-strsep.c:38
static int openssl_tls_version(int ver)
Convert internal version number to openssl version number.
Definition: ssl_openssl.c:261
static int DSA_bits(const DSA *dsa)
Number of significant DSA bits.
#define D_HANDSHAKE
Definition: errlevel.h:72
SSL_CTX * ctx
Definition: ssl_openssl.h:39
static int sk_x509_name_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
Definition: ssl_openssl.c:1525
static int get_sig_from_man(const unsigned char *dgst, unsigned int dgstlen, unsigned char *sig, unsigned int siglen, const char *algorithm)
Pass the input hash in &#39;dgst&#39; to management and get the signature back.
Definition: ssl_openssl.c:1224
void tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context for TLS 1.2 and below...
Definition: ssl_openssl.c:442
__int64 int64_t
Definition: config-msvc.h:160
unsigned __int8 uint8_t
Definition: config-msvc.h:159
#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc)
Definition: buffer.h:1072
Structure that wraps the TLS context.
Definition: ssl_mbedtls.h:91
#define SSLF_CLIENT_CERT_OPTIONAL
Definition: ssl_common.h:353
static void check_malloc_return(const void *p)
Definition: buffer.h:1093
Security parameter state of a single session within a VPN tunnel.
Definition: ssl_common.h:414
#define VALGRIND_MAKE_READABLE(addr, len)
Definition: memdbg.h:53
void tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
Check our certificate notBefore and notAfter fields, and warn if the cert is either not yet valid or ...
Definition: ssl_openssl.c:618
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
#define M_FATAL
Definition: error.h:94
int mydata_index
Allocate space in SSL objects in which to store a struct tls_session pointer back to parent...
Definition: ssl_openssl.c:74
static int SSL_CTX_get_min_proto_version(SSL_CTX *ctx)
Return the min SSL protocol version currently enabled in the context.
void tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
Set the (elliptic curve) group allowed for signatures and key exchange.
Definition: ssl_openssl.c:567
size_t ekm_label_size
Definition: ssl_common.h:379
#define D_TLS_DEBUG_MED
Definition: errlevel.h:154
static void info_callback(INFO_CALLBACK_SSL_CONST SSL *s, int where, int ret)
Definition: ssl_openssl.c:201
int key_state_write_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a ciphertext buffer into the TLS module.
Definition: ssl_openssl.c:2014
int get_num_elements(const char *string, char delimiter)
Returns the occurrences of &#39;delimiter&#39; in a string +1 This is typically used to find out the number e...
Definition: misc.c:767
static int constrain_int(int x, int min, int max)
Definition: integer.h:70
#define M_WARN
Definition: error.h:96
int tls_ctx_use_management_external_key(struct tls_root_ctx *ctx)
Tell the management interface to load the given certificate and the external private key matching the...
Definition: ssl_openssl.c:1469
#define free
Definition: cmocka.c:1850
static int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d)
Set the RSA parameters.
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
const char * openssl_name
Definition: ssl_backend.h:62
void tls_ctx_client_new(struct tls_root_ctx *ctx)
Initialises a library-specific TLS context for a client.
Definition: ssl_openssl.c:126
void key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
Initialise the SSL channel part of the given key state.
Definition: ssl_openssl.c:1912
void tls_free_lib(void)
Free any global SSL library-specific data structures.
Definition: ssl_openssl.c:91
#define UP_TYPE_PRIVATE_KEY
Definition: ssl_common.h:42
static int openvpn_extkey_rsa_finish(RSA *rsa)
Definition: ssl_openssl.c:1182
int key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf, int maxlen)
Extract ciphertext data from the TLS module.
Definition: ssl_openssl.c:1999
#define SSLF_TLS_VERSION_MAX_MASK
Definition: ssl_common.h:361
static int RSA_meth_set_init(RSA_METHOD *meth, int(*init)(RSA *rsa))
Set the init function of an RSA_METHOD object.
#define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT
static int bio_write(BIO *bio, const uint8_t *data, int size, const char *desc)
Definition: ssl_openssl.c:1791
#define SSLF_TLS_VERSION_MIN_SHIFT
Definition: ssl_common.h:358
#define OpenSSL_version
const tls_cipher_name_pair * tls_get_cipher_name_pair(const char *cipher_name, size_t len)
Definition: ssl.c:257
static int EC_GROUP_order_bits(const EC_GROUP *group)
Gets the number of bits of the order of an EC_GROUP.
void tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
Load Elliptic Curve Parameters, and load them into the library-specific TLS context.
Definition: ssl_openssl.c:698
struct env_set * es
Definition: ssl_common.h:342
static void RSA_set_flags(RSA *rsa, int flags)
Set the RSA flags.
static int X509_OBJECT_get_type(const X509_OBJECT *obj)
Get the type of an X509 object.
Container for unidirectional cipher and HMAC key material.
Definition: crypto.h:151
static int RSA_meth_set_finish(RSA_METHOD *meth, int(*finish)(RSA *rsa))
Set the finish function of an RSA_METHOD object.
static bool tls_ctx_set_tls_versions(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Definition: ssl_openssl.c:298
#define ptr_format
Definition: common.h:58
static int bio_read(BIO *bio, struct buffer *buf, int maxlen, const char *desc)
Definition: ssl_openssl.c:1856