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