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-2024 OpenVPN Inc <sales@openvpn.net>
9  * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.com>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2
13  * as published by the Free Software Foundation.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24 
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33 
34 #include "syshead.h"
35 
36 #if defined(ENABLE_CRYPTO_OPENSSL)
37 
38 #include "errlevel.h"
39 #include "buffer.h"
40 #include "misc.h"
41 #include "manage.h"
42 #include "memdbg.h"
43 #include "ssl_backend.h"
44 #include "ssl_common.h"
45 #include "base64.h"
46 #include "openssl_compat.h"
47 #include "xkey_common.h"
48 
49 #ifdef ENABLE_CRYPTOAPI
50 #include "cryptoapi.h"
51 #endif
52 
53 #include "ssl_verify_openssl.h"
54 #include "ssl_util.h"
55 
56 #include <openssl/bn.h>
57 #include <openssl/crypto.h>
58 #include <openssl/dh.h>
59 #include <openssl/dsa.h>
60 #include <openssl/err.h>
61 #include <openssl/pkcs12.h>
62 #include <openssl/rsa.h>
63 #include <openssl/x509.h>
64 #include <openssl/ssl.h>
65 #ifndef OPENSSL_NO_EC
66 #include <openssl/ec.h>
67 #endif
68 
69 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
70 #define HAVE_OPENSSL_STORE_API
71 #include <openssl/ui.h>
72 #include <openssl/store.h>
73 #endif
74 
75 #if defined(_MSC_VER) && !defined(_M_ARM64)
76 #include <openssl/applink.c>
77 #endif
78 
79 OSSL_LIB_CTX *tls_libctx; /* Global */
80 
81 static void unload_xkey_provider(void);
82 
83 /*
84  * Allocate space in SSL objects in which to store a struct tls_session
85  * pointer back to parent.
86  *
87  */
88 
89 int mydata_index; /* GLOBAL */
90 
91 void
93 {
94  mydata_index = SSL_get_ex_new_index(0, "struct session *", NULL, NULL, NULL);
95  ASSERT(mydata_index >= 0);
96 }
97 
98 void
100 {
101 }
102 
103 void
105 {
106  ASSERT(NULL != ctx);
107 
108  ctx->ctx = SSL_CTX_new_ex(tls_libctx, NULL, SSLv23_server_method());
109 
110  if (ctx->ctx == NULL)
111  {
112  crypto_msg(M_FATAL, "SSL_CTX_new SSLv23_server_method");
113  }
114  if (ERR_peek_error() != 0)
115  {
116  crypto_msg(M_WARN, "Warning: TLS server context initialisation "
117  "has warnings.");
118  }
119 }
120 
121 void
123 {
124  ASSERT(NULL != ctx);
125 
126  ctx->ctx = SSL_CTX_new_ex(tls_libctx, NULL, SSLv23_client_method());
127 
128  if (ctx->ctx == NULL)
129  {
130  crypto_msg(M_FATAL, "SSL_CTX_new SSLv23_client_method");
131  }
132  if (ERR_peek_error() != 0)
133  {
134  crypto_msg(M_WARN, "Warning: TLS client context initialisation "
135  "has warnings.");
136  }
137 }
138 
139 void
141 {
142  ASSERT(NULL != ctx);
143  SSL_CTX_free(ctx->ctx);
144  ctx->ctx = NULL;
145  unload_xkey_provider(); /* in case it is loaded */
146 }
147 
148 bool
150 {
151  ASSERT(NULL != ctx);
152  return NULL != ctx->ctx;
153 }
154 
155 bool
157  const char *label, size_t label_size,
158  void *ekm, size_t ekm_size)
159 
160 {
161  SSL *ssl = session->key[KS_PRIMARY].ks_ssl.ssl;
162 
163  if (SSL_export_keying_material(ssl, ekm, ekm_size, label,
164  label_size, NULL, 0, 0) == 1)
165  {
166  return true;
167  }
168  else
169  {
170  secure_memzero(ekm, ekm_size);
171  return false;
172  }
173 }
174 
175 /*
176  * Print debugging information on SSL/TLS session negotiation.
177  */
178 
179 #ifndef INFO_CALLBACK_SSL_CONST
180 #define INFO_CALLBACK_SSL_CONST const
181 #endif
182 static void
183 info_callback(INFO_CALLBACK_SSL_CONST SSL *s, int where, int ret)
184 {
185  if (where & SSL_CB_LOOP)
186  {
187  dmsg(D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
188  where & SSL_ST_CONNECT ? "connect" :
189  where &SSL_ST_ACCEPT ? "accept" :
190  "undefined", SSL_state_string_long(s));
191  }
192  else if (where & SSL_CB_ALERT)
193  {
194  dmsg(D_TLS_DEBUG_LOW, "%s %s SSL alert: %s",
195  where & SSL_CB_READ ? "Received" : "Sent",
196  SSL_alert_type_string_long(ret),
197  SSL_alert_desc_string_long(ret));
198  }
199 }
200 
201 /*
202  * Return maximum TLS version supported by local OpenSSL library.
203  * Assume that presence of SSL_OP_NO_TLSvX macro indicates that
204  * TLSvX is supported.
205  */
206 int
208 {
209 #if defined(TLS1_3_VERSION)
210  /* If this is defined we can safely assume TLS 1.3 support */
211  return TLS_VER_1_3;
212 #elif OPENSSL_VERSION_NUMBER >= 0x10100000L
213  /*
214  * If TLS_VER_1_3 is not defined, we were compiled against a version that
215  * did not support TLS 1.3.
216  *
217  * However, the library we are *linked* against might be OpenSSL 1.1.1
218  * and therefore supports TLS 1.3. This needs to be checked at runtime
219  * since we can be compiled against 1.1.0 and then the library can be
220  * upgraded to 1.1.1.
221  * We only need to check this for OpenSSL versions that can be
222  * upgraded to 1.1.1 without recompile (>= 1.1.0)
223  */
224  if (OpenSSL_version_num() >= 0x1010100fL)
225  {
226  return TLS_VER_1_3;
227  }
228  else
229  {
230  return TLS_VER_1_2;
231  }
232 #elif defined(TLS1_2_VERSION) || defined(SSL_OP_NO_TLSv1_2)
233  return TLS_VER_1_2;
234 #elif defined(TLS1_1_VERSION) || defined(SSL_OP_NO_TLSv1_1)
235  return TLS_VER_1_1;
236 #else /* if defined(TLS1_3_VERSION) */
237  return TLS_VER_1_0;
238 #endif
239 }
240 
242 static int
244 {
245  if (ver == TLS_VER_1_0)
246  {
247  return TLS1_VERSION;
248  }
249  else if (ver == TLS_VER_1_1)
250  {
251  return TLS1_1_VERSION;
252  }
253  else if (ver == TLS_VER_1_2)
254  {
255  return TLS1_2_VERSION;
256  }
257  else if (ver == TLS_VER_1_3)
258  {
259  /*
260  * Supporting the library upgraded to TLS1.3 without recompile
261  * is enough to support here with a simple constant that the same
262  * as in the TLS 1.3, so spec it is very unlikely that OpenSSL
263  * will change this constant
264  */
265 #ifndef TLS1_3_VERSION
266  /*
267  * We do not want to define TLS_VER_1_3 if not defined
268  * since other parts of the code use the existance of this macro
269  * as proxy for TLS 1.3 support
270  */
271  return 0x0304;
272 #else
273  return TLS1_3_VERSION;
274 #endif
275  }
276  return 0;
277 }
278 
279 static bool
280 tls_ctx_set_tls_versions(struct tls_root_ctx *ctx, unsigned int ssl_flags)
281 {
282  int tls_ver_min = openssl_tls_version(
284  int tls_ver_max = openssl_tls_version(
286 
287  if (!tls_ver_min)
288  {
289  /* Enforce at least TLS 1.0 */
290  int cur_min = SSL_CTX_get_min_proto_version(ctx->ctx);
291  tls_ver_min = cur_min < TLS1_VERSION ? TLS1_VERSION : cur_min;
292  }
293 
294  if (!SSL_CTX_set_min_proto_version(ctx->ctx, tls_ver_min))
295  {
296  msg(D_TLS_ERRORS, "%s: failed to set minimum TLS version", __func__);
297  return false;
298  }
299 
300  if (tls_ver_max && !SSL_CTX_set_max_proto_version(ctx->ctx, tls_ver_max))
301  {
302  msg(D_TLS_ERRORS, "%s: failed to set maximum TLS version", __func__);
303  return false;
304  }
305 
306  return true;
307 }
308 
309 bool
310 tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
311 {
312  ASSERT(NULL != ctx);
313 
314  /* process SSL options */
315  long sslopt = SSL_OP_SINGLE_DH_USE | SSL_OP_NO_TICKET;
316 #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
317  sslopt |= SSL_OP_CIPHER_SERVER_PREFERENCE;
318 #endif
319  sslopt |= SSL_OP_NO_COMPRESSION;
320  /* Disable TLS renegotiations. OpenVPN's renegotiation creates new SSL
321  * session and does not depend on this feature. And TLS renegotiations have
322  * been problematic in the past */
323 #ifdef SSL_OP_NO_RENEGOTIATION
324  sslopt |= SSL_OP_NO_RENEGOTIATION;
325 #endif
326 
327  SSL_CTX_set_options(ctx->ctx, sslopt);
328 
329  if (!tls_ctx_set_tls_versions(ctx, ssl_flags))
330  {
331  return false;
332  }
333 
334 #ifdef SSL_MODE_RELEASE_BUFFERS
335  SSL_CTX_set_mode(ctx->ctx, SSL_MODE_RELEASE_BUFFERS);
336 #endif
337  SSL_CTX_set_session_cache_mode(ctx->ctx, SSL_SESS_CACHE_OFF);
338  SSL_CTX_set_default_passwd_cb(ctx->ctx, pem_password_callback);
339 
340  /* Require peer certificate verification */
341  int verify_flags = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
342  if (ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED)
343  {
344  verify_flags = 0;
345  }
346  else if (ssl_flags & SSLF_CLIENT_CERT_OPTIONAL)
347  {
348  verify_flags = SSL_VERIFY_PEER;
349  }
350  SSL_CTX_set_verify(ctx->ctx, verify_flags, verify_callback);
351 
352  SSL_CTX_set_info_callback(ctx->ctx, info_callback);
353 
354  return true;
355 }
356 
357 static void
358 convert_tls_list_to_openssl(char *openssl_ciphers, size_t len, const char *ciphers)
359 {
360  /* Parse supplied cipher list and pass on to OpenSSL */
361  size_t begin_of_cipher, end_of_cipher;
362 
363  const char *current_cipher;
364  size_t current_cipher_len;
365 
366  const tls_cipher_name_pair *cipher_pair;
367 
368  size_t openssl_ciphers_len = 0;
369  openssl_ciphers[0] = '\0';
370 
371  /* Translate IANA cipher suite names to OpenSSL names */
372  begin_of_cipher = end_of_cipher = 0;
373  for (; begin_of_cipher < strlen(ciphers); begin_of_cipher = end_of_cipher)
374  {
375  end_of_cipher += strcspn(&ciphers[begin_of_cipher], ":");
376  cipher_pair = tls_get_cipher_name_pair(&ciphers[begin_of_cipher], end_of_cipher - begin_of_cipher);
377 
378  if (NULL == cipher_pair)
379  {
380  /* No translation found, use original */
381  current_cipher = &ciphers[begin_of_cipher];
382  current_cipher_len = end_of_cipher - begin_of_cipher;
383 
384  /* Issue warning on missing translation */
385  /* %.*s format specifier expects length of type int, so guarantee */
386  /* that length is small enough and cast to int. */
387  msg(D_LOW, "No valid translation found for TLS cipher '%.*s'",
388  constrain_int(current_cipher_len, 0, 256), current_cipher);
389  }
390  else
391  {
392  /* Use OpenSSL name */
393  current_cipher = cipher_pair->openssl_name;
394  current_cipher_len = strlen(current_cipher);
395 
396  if (end_of_cipher - begin_of_cipher == current_cipher_len
397  && 0 != memcmp(&ciphers[begin_of_cipher], cipher_pair->iana_name,
398  end_of_cipher - begin_of_cipher))
399  {
400  /* Non-IANA name used, show warning */
401  msg(M_WARN, "Deprecated TLS cipher name '%s', please use IANA name '%s'", cipher_pair->openssl_name, cipher_pair->iana_name);
402  }
403  }
404 
405  /* Make sure new cipher name fits in cipher string */
406  if ((SIZE_MAX - openssl_ciphers_len) < current_cipher_len
407  || (len - 1) < (openssl_ciphers_len + current_cipher_len))
408  {
409  msg(M_FATAL,
410  "Failed to set restricted TLS cipher list, too long (>%d).",
411  (int)(len - 1));
412  }
413 
414  /* Concatenate cipher name to OpenSSL cipher string */
415  memcpy(&openssl_ciphers[openssl_ciphers_len], current_cipher, current_cipher_len);
416  openssl_ciphers_len += current_cipher_len;
417  openssl_ciphers[openssl_ciphers_len] = ':';
418  openssl_ciphers_len++;
419 
420  end_of_cipher++;
421  }
422 
423  if (openssl_ciphers_len > 0)
424  {
425  openssl_ciphers[openssl_ciphers_len-1] = '\0';
426  }
427 }
428 
429 void
430 tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
431 {
432  if (ciphers == NULL)
433  {
434  /* Use sane default TLS cipher list */
435  if (!SSL_CTX_set_cipher_list(ctx->ctx,
436  /* Use openssl's default list as a basis */
437  "DEFAULT"
438  /* Disable export ciphers and openssl's 'low' and 'medium' ciphers */
439  ":!EXP:!LOW:!MEDIUM"
440  /* Disable static (EC)DH keys (no forward secrecy) */
441  ":!kDH:!kECDH"
442  /* Disable DSA private keys */
443  ":!DSS"
444  /* Disable unsupported TLS modes */
445  ":!PSK:!SRP:!kRSA"))
446  {
447  crypto_msg(M_FATAL, "Failed to set default TLS cipher list.");
448  }
449  return;
450  }
451 
452  char openssl_ciphers[4096];
453  convert_tls_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers), ciphers);
454 
455  ASSERT(NULL != ctx);
456 
457  /* Set OpenSSL cipher list */
458  if (!SSL_CTX_set_cipher_list(ctx->ctx, openssl_ciphers))
459  {
460  crypto_msg(M_FATAL, "Failed to set restricted TLS cipher list: %s", openssl_ciphers);
461  }
462 }
463 
464 static void
465 convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len,
466  const char *ciphers)
467 {
468  /*
469  * OpenSSL (and official IANA) cipher names have _ in them. We
470  * historically used names with - in them. Silently convert names
471  * with - to names with _ to support both
472  */
473  if (strlen(ciphers) >= (len - 1))
474  {
475  msg(M_FATAL,
476  "Failed to set restricted TLS 1.3 cipher list, too long (>%d).",
477  (int) (len - 1));
478  }
479 
480  strncpy(openssl_ciphers, ciphers, len);
481 
482  for (size_t i = 0; i < strlen(openssl_ciphers); i++)
483  {
484  if (openssl_ciphers[i] == '-')
485  {
486  openssl_ciphers[i] = '_';
487  }
488  }
489 }
490 
491 void
492 tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
493 {
494  if (ciphers == NULL)
495  {
496  /* default cipher list of OpenSSL 1.1.1 is sane, do not set own
497  * default as we do with tls-cipher */
498  return;
499  }
500 
501 #if !defined(TLS1_3_VERSION)
502  crypto_msg(M_WARN, "Not compiled with OpenSSL 1.1.1 or higher. "
503  "Ignoring TLS 1.3 only tls-ciphersuites '%s' setting.",
504  ciphers);
505 #else
506  ASSERT(NULL != ctx);
507 
508  char openssl_ciphers[4096];
509  convert_tls13_list_to_openssl(openssl_ciphers, sizeof(openssl_ciphers),
510  ciphers);
511 
512  if (!SSL_CTX_set_ciphersuites(ctx->ctx, openssl_ciphers))
513  {
514  crypto_msg(M_FATAL, "Failed to set restricted TLS 1.3 cipher list: %s",
515  openssl_ciphers);
516  }
517 #endif
518 }
519 
520 void
521 tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
522 {
523 #if OPENSSL_VERSION_NUMBER > 0x10100000L \
524  && (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER > 0x3060000fL)
525  /* OpenSSL does not have certificate profiles, but a complex set of
526  * callbacks that we could try to implement to achieve something similar.
527  * For now, use OpenSSL's security levels to achieve similar (but not equal)
528  * behaviour. */
529  if (!profile || 0 == strcmp(profile, "legacy"))
530  {
531  SSL_CTX_set_security_level(ctx->ctx, 1);
532  }
533  else if (0 == strcmp(profile, "insecure"))
534  {
535  SSL_CTX_set_security_level(ctx->ctx, 0);
536  }
537  else if (0 == strcmp(profile, "preferred"))
538  {
539  SSL_CTX_set_security_level(ctx->ctx, 2);
540  }
541  else if (0 == strcmp(profile, "suiteb"))
542  {
543  SSL_CTX_set_security_level(ctx->ctx, 3);
544  SSL_CTX_set_cipher_list(ctx->ctx, "SUITEB128");
545  }
546  else
547  {
548  msg(M_FATAL, "ERROR: Invalid cert profile: %s", profile);
549  }
550 #else /* if OPENSSL_VERSION_NUMBER > 0x10100000L */
551  if (profile)
552  {
553  msg(M_WARN, "WARNING: OpenSSL 1.1.0 and LibreSSL do not support "
554  "--tls-cert-profile, ignoring user-set profile: '%s'", profile);
555  }
556 #endif /* if OPENSSL_VERSION_NUMBER > 0x10100000L */
557 }
558 
559 void
560 tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
561 {
562  ASSERT(ctx);
563 #if OPENSSL_VERSION_NUMBER < 0x30000000L
564  struct gc_arena gc = gc_new();
565  /* This method could be as easy as
566  * SSL_CTX_set1_groups_list(ctx->ctx, groups)
567  * but OpenSSL (< 3.0) does not like the name secp256r1 for prime256v1
568  * This is one of the important curves.
569  * To support the same name for OpenSSL and mbedTLS, we do
570  * this dance.
571  * Also note that the code is wrong in the presence of OpenSSL3 providers.
572  */
573 
574  int groups_count = get_num_elements(groups, ':');
575 
576  int *glist;
577  /* Allocate an array for them */
578  ALLOC_ARRAY_CLEAR_GC(glist, int, groups_count, &gc);
579 
580  /* Parse allowed ciphers, getting IDs */
581  int glistlen = 0;
582  char *tmp_groups = string_alloc(groups, &gc);
583 
584  const char *token;
585  while ((token = strsep(&tmp_groups, ":")))
586  {
587  if (streq(token, "secp256r1"))
588  {
589  token = "prime256v1";
590  }
591  int nid = OBJ_sn2nid(token);
592 
593  if (nid == 0)
594  {
595  msg(M_WARN, "Warning unknown curve/group specified: %s", token);
596  }
597  else
598  {
599  glist[glistlen] = nid;
600  glistlen++;
601  }
602  }
603 
604  if (!SSL_CTX_set1_groups(ctx->ctx, glist, glistlen))
605  {
606  crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s",
607  groups);
608  }
609  gc_free(&gc);
610 #else /* if OPENSSL_VERSION_NUMBER < 0x30000000L */
611  if (!SSL_CTX_set1_groups_list(ctx->ctx, groups))
612  {
613  crypto_msg(M_FATAL, "Failed to set allowed TLS group list: %s",
614  groups);
615  }
616 #endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L */
617 }
618 
619 void
621 {
622  int ret;
623  const X509 *cert;
624 
625  ASSERT(ctx);
626 
627  cert = SSL_CTX_get0_certificate(ctx->ctx);
628 
629  if (cert == NULL)
630  {
631  return; /* Nothing to check if there is no certificate */
632  }
633 
634  ret = X509_cmp_time(X509_get0_notBefore(cert), NULL);
635  if (ret == 0)
636  {
637  msg(D_TLS_DEBUG_MED, "Failed to read certificate notBefore field.");
638  }
639  if (ret > 0)
640  {
641  msg(M_WARN, "WARNING: Your certificate is not yet valid!");
642  }
643 
644  ret = X509_cmp_time(X509_get0_notAfter(cert), NULL);
645  if (ret == 0)
646  {
647  msg(D_TLS_DEBUG_MED, "Failed to read certificate notAfter field.");
648  }
649  if (ret < 0)
650  {
651  msg(M_WARN, "WARNING: Your certificate has expired!");
652  }
653 }
654 
655 void
656 tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file,
657  bool dh_file_inline)
658 {
659  BIO *bio;
660 
661  ASSERT(NULL != ctx);
662 
663  if (dh_file_inline)
664  {
665  if (!(bio = BIO_new_mem_buf((char *)dh_file, -1)))
666  {
667  crypto_msg(M_FATAL, "Cannot open memory BIO for inline DH parameters");
668  }
669  }
670  else
671  {
672  /* Get Diffie Hellman Parameters */
673  if (!(bio = BIO_new_file(dh_file, "r")))
674  {
675  crypto_msg(M_FATAL, "Cannot open %s for DH parameters", dh_file);
676  }
677  }
678 
679 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
680  EVP_PKEY *dh = PEM_read_bio_Parameters(bio, NULL);
681  BIO_free(bio);
682 
683  if (!dh)
684  {
685  crypto_msg(M_FATAL, "Cannot load DH parameters from %s",
686  print_key_filename(dh_file, dh_file_inline));
687  }
688  if (!SSL_CTX_set0_tmp_dh_pkey(ctx->ctx, dh))
689  {
690  crypto_msg(M_FATAL, "SSL_CTX_set0_tmp_dh_pkey");
691  }
692 
693  msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
694  8 * EVP_PKEY_get_size(dh));
695 #else /* if OPENSSL_VERSION_NUMBER >= 0x30000000L */
696  DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
697  BIO_free(bio);
698 
699  if (!dh)
700  {
701  crypto_msg(M_FATAL, "Cannot load DH parameters from %s",
702  print_key_filename(dh_file, dh_file_inline));
703  }
704  if (!SSL_CTX_set_tmp_dh(ctx->ctx, dh))
705  {
706  crypto_msg(M_FATAL, "SSL_CTX_set_tmp_dh");
707  }
708 
709  msg(D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
710  8 * DH_size(dh));
711 
712  DH_free(dh);
713 #endif /* if OPENSSL_VERSION_NUMBER >= 0x30000000L */
714 }
715 
716 void
717 tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
718 {
719 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
720  if (curve_name != NULL)
721  {
722  msg(M_WARN, "WARNING: OpenSSL 3.0+ builds do not support specifying an "
723  "ECDH curve with --ecdh-curve, using default curves. Use "
724  "--tls-groups to specify groups.");
725  }
726 #elif !defined(OPENSSL_NO_EC)
727  int nid = NID_undef;
728  EC_KEY *ecdh = NULL;
729  const char *sname = NULL;
730 
731  /* Generate a new ECDH key for each SSL session (for non-ephemeral ECDH) */
732  SSL_CTX_set_options(ctx->ctx, SSL_OP_SINGLE_ECDH_USE);
733 
734  if (curve_name != NULL)
735  {
736  /* Use user supplied curve if given */
737  msg(D_TLS_DEBUG, "Using user specified ECDH curve (%s)", curve_name);
738  nid = OBJ_sn2nid(curve_name);
739  }
740  else
741  {
742  return;
743  }
744 
745  /* Translate NID back to name , just for kicks */
746  sname = OBJ_nid2sn(nid);
747  if (sname == NULL)
748  {
749  sname = "(Unknown)";
750  }
751 
752  /* Create new EC key and set as ECDH key */
753  if (NID_undef == nid || NULL == (ecdh = EC_KEY_new_by_curve_name(nid)))
754  {
755  /* Creating key failed, fall back on sane default */
756  ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
757  const char *source = (NULL == curve_name) ?
758  "extract curve from certificate" : "use supplied curve";
760  "Failed to %s (%s), using secp384r1 instead.", source, sname);
761  sname = OBJ_nid2sn(NID_secp384r1);
762  }
763 
764  if (!SSL_CTX_set_tmp_ecdh(ctx->ctx, ecdh))
765  {
766  crypto_msg(M_FATAL, "SSL_CTX_set_tmp_ecdh: cannot add curve");
767  }
768 
769  msg(D_TLS_DEBUG_LOW, "ECDH curve %s added", sname);
770 
771  EC_KEY_free(ecdh);
772 #else /* ifndef OPENSSL_NO_EC */
773  msg(D_LOW, "Your OpenSSL library was built without elliptic curve support."
774  " Skipping ECDH parameter loading.");
775 #endif /* OPENSSL_NO_EC */
776 }
777 
778 #if defined(HAVE_OPENSSL_STORE_API)
779 
784 static int
785 ui_reader(UI *ui, UI_STRING *uis)
786 {
787  SSL_CTX *ctx = UI_get0_user_data(ui);
788 
789  if (UI_get_string_type(uis) == UIT_PROMPT)
790  {
791  const char *prompt = UI_get0_output_string(uis);
792 
793  /* If pkcs#11 Use custom prompt similar to pkcs11-helper */
794  if (strstr(prompt, "PKCS#11"))
795  {
796  struct user_pass up;
797  CLEAR(up);
799  UI_set_result(ui, uis, up.password);
800  purge_user_pass(&up, true);
801  }
802  else /* use our generic 'Private Key' passphrase callback */
803  {
804  char password[64];
805  pem_password_cb *cb = SSL_CTX_get_default_passwd_cb(ctx);
806  void *d = SSL_CTX_get_default_passwd_cb_userdata(ctx);
807 
808  cb(password, sizeof(password), 0, d);
809  UI_set_result(ui, uis, password);
810  secure_memzero(password, sizeof(password));
811  }
812 
813  return 1;
814  }
815  return 0;
816 }
817 
818 static void
819 clear_ossl_store_error(OSSL_STORE_CTX *store_ctx)
820 {
821  if (OSSL_STORE_error(store_ctx))
822  {
823  ERR_clear_error();
824  }
825 }
826 #endif /* defined(HAVE_OPENSSL_STORE_API) */
827 
836 static void *
837 load_pkey_from_uri(const char *uri, SSL_CTX *ssl_ctx)
838 {
839  EVP_PKEY *pkey = NULL;
840 
841 #if !defined(HAVE_OPENSSL_STORE_API)
842 
843  /* Treat the uri as file name */
844  BIO *in = BIO_new_file(uri, "r");
845  if (!in)
846  {
847  return NULL;
848  }
849  pkey = PEM_read_bio_PrivateKey(in, NULL,
850  SSL_CTX_get_default_passwd_cb(ssl_ctx),
851  SSL_CTX_get_default_passwd_cb_userdata(ssl_ctx));
852  BIO_free(in);
853 
854 #else /* defined(HAVE_OPENSSL_STORE_API) */
855 
856  OSSL_STORE_CTX *store_ctx = NULL;
857  OSSL_STORE_INFO *info = NULL;
858 
859  UI_METHOD *ui_method = UI_create_method("openvpn");
860  if (!ui_method)
861  {
862  msg(M_WARN, "OpenSSL UI creation failed");
863  return NULL;
864  }
865  UI_method_set_reader(ui_method, ui_reader);
866 
867  store_ctx = OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui_method, ssl_ctx,
868  NULL, NULL, NULL);
869  if (!store_ctx)
870  {
871  goto end;
872  }
873  if (OSSL_STORE_expect(store_ctx, OSSL_STORE_INFO_PKEY) != 1)
874  {
875  goto end;
876  }
877  while (1)
878  {
879  info = OSSL_STORE_load(store_ctx);
880  if (info || OSSL_STORE_eof(store_ctx))
881  {
882  break;
883  }
884  /* OPENSSL_STORE_load can return error and still have usable objects to follow.
885  * ref: man OPENSSL_STORE_open
886  * Clear error and recurse through the file if info = NULL and eof not reached
887  */
888  clear_ossl_store_error(store_ctx);
889  }
890  if (!info)
891  {
892  goto end;
893  }
894  pkey = OSSL_STORE_INFO_get1_PKEY(info);
895  OSSL_STORE_INFO_free(info);
896  msg(D_TLS_DEBUG_MED, "Found pkey in store using URI: %s", uri);
897 
898 end:
899  OSSL_STORE_close(store_ctx);
900  UI_destroy_method(ui_method);
901 
902 #endif /* defined(HAVE_OPENSSL_STORE_API) */
903 
904  return pkey;
905 }
906 
907 int
908 tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,
909  bool pkcs12_file_inline, bool load_ca_file)
910 {
911  FILE *fp;
912  EVP_PKEY *pkey;
913  X509 *cert;
914  STACK_OF(X509) *ca = NULL;
915  PKCS12 *p12;
916  int i;
917  char password[256];
918 
919  ASSERT(NULL != ctx);
920 
921  if (pkcs12_file_inline)
922  {
923  BIO *b64 = BIO_new(BIO_f_base64());
924  BIO *bio = BIO_new_mem_buf((void *) pkcs12_file,
925  (int) strlen(pkcs12_file));
926  ASSERT(b64 && bio);
927  BIO_push(b64, bio);
928  p12 = d2i_PKCS12_bio(b64, NULL);
929  if (!p12)
930  {
931  crypto_msg(M_FATAL, "Error reading inline PKCS#12 file");
932  }
933  BIO_free(b64);
934  BIO_free(bio);
935  }
936  else
937  {
938  /* Load the PKCS #12 file */
939  if (!(fp = platform_fopen(pkcs12_file, "rb")))
940  {
941  crypto_msg(M_FATAL, "Error opening file %s", pkcs12_file);
942  }
943  p12 = d2i_PKCS12_fp(fp, NULL);
944  fclose(fp);
945  if (!p12)
946  {
947  crypto_msg(M_FATAL, "Error reading PKCS#12 file %s", pkcs12_file);
948  }
949  }
950 
951  /* Parse the PKCS #12 file */
952  if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
953  {
954  pem_password_callback(password, sizeof(password) - 1, 0, NULL);
955  /* Reparse the PKCS #12 file with password */
956  ca = NULL;
957  if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
958  {
959  crypto_msg(M_WARN, "Decoding PKCS12 failed. Probably wrong password "
960  "or unsupported/legacy encryption");
961 #ifdef ENABLE_MANAGEMENT
962  if (management && (ERR_GET_REASON(ERR_peek_error()) == PKCS12_R_MAC_VERIFY_FAILURE))
963  {
965  }
966 #endif
967  PKCS12_free(p12);
968  return 1;
969  }
970  }
971  PKCS12_free(p12);
972 
973  /* Load Certificate */
974  if (!SSL_CTX_use_certificate(ctx->ctx, cert))
975  {
977  crypto_msg(M_FATAL, "Cannot use certificate");
978  }
979 
980  /* Load Private Key */
981  if (!SSL_CTX_use_PrivateKey(ctx->ctx, pkey))
982  {
983  crypto_msg(M_FATAL, "Cannot use private key");
984  }
985 
986  /* Check Private Key */
987  if (!SSL_CTX_check_private_key(ctx->ctx))
988  {
989  crypto_msg(M_FATAL, "Private key does not match the certificate");
990  }
991 
992  /* Set Certificate Verification chain */
993  if (load_ca_file)
994  {
995  /* Add CAs from PKCS12 to the cert store and mark them as trusted.
996  * They're also used to fill in the chain of intermediate certs as
997  * necessary.
998  */
999  if (ca && sk_X509_num(ca))
1000  {
1001  for (i = 0; i < sk_X509_num(ca); i++)
1002  {
1003  X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx->ctx);
1004  if (!X509_STORE_add_cert(cert_store, sk_X509_value(ca, i)))
1005  {
1006  crypto_msg(M_FATAL, "Cannot add certificate to certificate chain (X509_STORE_add_cert)");
1007  }
1008  if (!SSL_CTX_add_client_CA(ctx->ctx, sk_X509_value(ca, i)))
1009  {
1010  crypto_msg(M_FATAL, "Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
1011  }
1012  }
1013  }
1014  }
1015  else
1016  {
1017  /* If trusted CA certs were loaded from a PEM file, and we ignore the
1018  * ones in PKCS12, do load PKCS12-provided certs to the client extra
1019  * certs chain just in case they include intermediate CAs needed to
1020  * prove my identity to the other end. This does not make them trusted.
1021  */
1022  if (ca && sk_X509_num(ca))
1023  {
1024  for (i = 0; i < sk_X509_num(ca); i++)
1025  {
1026  if (!SSL_CTX_add_extra_chain_cert(ctx->ctx, sk_X509_value(ca, i)))
1027  {
1028  crypto_msg(M_FATAL, "Cannot add extra certificate to chain (SSL_CTX_add_extra_chain_cert)");
1029  }
1030  }
1031  }
1032  }
1033  return 0;
1034 }
1035 
1036 #ifdef ENABLE_CRYPTOAPI
1037 void
1038 tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
1039 {
1040  ASSERT(NULL != ctx);
1041 
1042  /* Load Certificate and Private Key */
1043  if (!SSL_CTX_use_CryptoAPI_certificate(ctx->ctx, cryptoapi_cert))
1044  {
1045  crypto_msg(M_FATAL, "Cannot load certificate \"%s\" from Microsoft Certificate Store", cryptoapi_cert);
1046  }
1047 }
1048 #endif /* ENABLE_CRYPTOAPI */
1049 
1050 static void
1051 tls_ctx_add_extra_certs(struct tls_root_ctx *ctx, BIO *bio, bool optional)
1052 {
1053  X509 *cert;
1054  while (true)
1055  {
1056  cert = NULL;
1057  if (!PEM_read_bio_X509(bio, &cert, NULL, NULL))
1058  {
1059  /* a PEM_R_NO_START_LINE "Error" indicates that no certificate
1060  * is found in the buffer. If loading more certificates is
1061  * optional, break without raising an error
1062  */
1063  if (optional
1064  && ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
1065  {
1066  /* remove that error from error stack */
1067  (void)ERR_get_error();
1068  break;
1069  }
1070 
1071  /* Otherwise, bail out with error */
1072  crypto_msg(M_FATAL, "Error reading extra certificate");
1073  }
1074  /* takes ownership of cert like a set1 method */
1075  if (SSL_CTX_add_extra_chain_cert(ctx->ctx, cert) != 1)
1076  {
1077  crypto_msg(M_FATAL, "Error adding extra certificate");
1078  }
1079  /* We loaded at least one certificate, so loading more is optional */
1080  optional = true;
1081  }
1082 }
1083 
1084 static bool
1086 {
1087 #if defined(HAVE_OPENSSL_STORE_API)
1088  return 1;
1089 #else
1090  return 0;
1091 #endif
1092 }
1093 
1094 static void
1095 tls_ctx_load_cert_uri(struct tls_root_ctx *tls_ctx, const char *uri)
1096 {
1097 #if defined(HAVE_OPENSSL_STORE_API)
1098  X509 *x = NULL;
1099  int ret = 0;
1100  OSSL_STORE_CTX *store_ctx = NULL;
1101  OSSL_STORE_INFO *info = NULL;
1102 
1103  ASSERT(NULL != tls_ctx);
1104 
1105  UI_METHOD *ui_method = UI_create_method("openvpn");
1106  if (!ui_method)
1107  {
1108  msg(M_WARN, "OpenSSL UI method creation failed");
1109  goto end;
1110  }
1111  UI_method_set_reader(ui_method, ui_reader);
1112 
1113  store_ctx = OSSL_STORE_open_ex(uri, tls_libctx, NULL, ui_method, tls_ctx->ctx,
1114  NULL, NULL, NULL);
1115  if (!store_ctx)
1116  {
1117  goto end;
1118  }
1119  if (OSSL_STORE_expect(store_ctx, OSSL_STORE_INFO_CERT) != 1)
1120  {
1121  goto end;
1122  }
1123 
1124  while (1)
1125  {
1126  info = OSSL_STORE_load(store_ctx);
1127  if (info || OSSL_STORE_eof(store_ctx))
1128  {
1129  break;
1130  }
1131  /* OPENSSL_STORE_load can return error and still have usable objects to follow.
1132  * ref: man OPENSSL_STORE_open
1133  * Clear error and recurse through the file if info = NULL and eof not reached.
1134  */
1135  clear_ossl_store_error(store_ctx);
1136  }
1137  if (!info)
1138  {
1139  goto end;
1140  }
1141 
1142  x = OSSL_STORE_INFO_get0_CERT(info);
1143  if (x == NULL)
1144  {
1145  goto end;
1146  }
1147  msg(D_TLS_DEBUG_MED, "Found cert in store using URI: %s", uri);
1148 
1149  ret = SSL_CTX_use_certificate(tls_ctx->ctx, x);
1150  if (!ret)
1151  {
1152  goto end;
1153  }
1154  OSSL_STORE_INFO_free(info);
1155 
1156  /* iterate through the store and add extra certificates if any to the chain */
1157  while (!OSSL_STORE_eof(store_ctx))
1158  {
1159  info = OSSL_STORE_load(store_ctx);
1160  if (!info)
1161  {
1162  clear_ossl_store_error(store_ctx);
1163  continue;
1164  }
1165  x = OSSL_STORE_INFO_get1_CERT(info);
1166  if (x && SSL_CTX_add_extra_chain_cert(tls_ctx->ctx, x) != 1)
1167  {
1168  X509_free(x);
1169  crypto_msg(M_FATAL, "Error adding extra certificate");
1170  break;
1171  }
1172  OSSL_STORE_INFO_free(info);
1173  }
1174 
1175 end:
1176  if (!ret)
1177  {
1179  crypto_msg(M_FATAL, "Cannot load certificate from URI <%s>", uri);
1180  }
1181  else
1182  {
1184  }
1185 
1186  UI_destroy_method(ui_method);
1187  OSSL_STORE_INFO_free(info);
1188  OSSL_STORE_close(store_ctx);
1189 #else /* defined(HAVE_OPENSSL_STORE_API */
1190  ASSERT(0);
1191 #endif /* defined(HAVE_OPENSSL_STORE_API */
1192 }
1193 
1194 static void
1195 tls_ctx_load_cert_pem_file(struct tls_root_ctx *ctx, const char *cert_file,
1196  bool cert_file_inline)
1197 {
1198  BIO *in = NULL;
1199  X509 *x = NULL;
1200  int ret = 0;
1201 
1202  ASSERT(NULL != ctx);
1203 
1204  if (cert_file_inline)
1205  {
1206  in = BIO_new_mem_buf((char *) cert_file, -1);
1207  }
1208  else
1209  {
1210  in = BIO_new_file((char *) cert_file, "r");
1211  }
1212 
1213  if (in == NULL)
1214  {
1215  SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
1216  goto end;
1217  }
1218 
1219  x = PEM_read_bio_X509(in, NULL,
1220  SSL_CTX_get_default_passwd_cb(ctx->ctx),
1221  SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx));
1222  if (x == NULL)
1223  {
1224  SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_PEM_LIB);
1225  goto end;
1226  }
1227 
1228  ret = SSL_CTX_use_certificate(ctx->ctx, x);
1229  if (ret)
1230  {
1231  tls_ctx_add_extra_certs(ctx, in, true);
1232  }
1233 
1234 end:
1235  if (!ret)
1236  {
1238  if (cert_file_inline)
1239  {
1240  crypto_msg(M_FATAL, "Cannot load inline certificate file");
1241  }
1242  else
1243  {
1244  crypto_msg(M_FATAL, "Cannot load certificate file %s", cert_file);
1245  }
1246  }
1247  else
1248  {
1250  }
1251 
1252  BIO_free(in);
1253  X509_free(x);
1254 }
1255 
1256 void
1257 tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file,
1258  bool cert_file_inline)
1259 {
1260  if (cert_uri_supported() && !cert_file_inline)
1261  {
1262  tls_ctx_load_cert_uri(ctx, cert_file);
1263  }
1264  else
1265  {
1266  tls_ctx_load_cert_pem_file(ctx, cert_file, cert_file_inline);
1267  }
1268 }
1269 
1270 int
1271 tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file,
1272  bool priv_key_file_inline)
1273 {
1274  SSL_CTX *ssl_ctx = NULL;
1275  BIO *in = NULL;
1276  EVP_PKEY *pkey = NULL;
1277  int ret = 1;
1278 
1279  ASSERT(NULL != ctx);
1280 
1281  ssl_ctx = ctx->ctx;
1282 
1283  if (priv_key_file_inline)
1284  {
1285  in = BIO_new_mem_buf((char *) priv_key_file, -1);
1286  if (in == NULL)
1287  {
1288  goto end;
1289  }
1290  pkey = PEM_read_bio_PrivateKey(in, NULL,
1291  SSL_CTX_get_default_passwd_cb(ctx->ctx),
1292  SSL_CTX_get_default_passwd_cb_userdata(ctx->ctx));
1293  }
1294  else
1295  {
1296  pkey = load_pkey_from_uri(priv_key_file, ssl_ctx);
1297  }
1298 
1299  if (!pkey || !SSL_CTX_use_PrivateKey(ssl_ctx, pkey))
1300  {
1301 #ifdef ENABLE_MANAGEMENT
1302  if (management && (ERR_GET_REASON(ERR_peek_error()) == EVP_R_BAD_DECRYPT))
1303  {
1305  }
1306 #endif
1307  crypto_msg(M_WARN, "Cannot load private key file %s",
1308  print_key_filename(priv_key_file, priv_key_file_inline));
1309  goto end;
1310  }
1311 
1312  /* Check Private Key */
1313  if (!SSL_CTX_check_private_key(ssl_ctx))
1314  {
1315  crypto_msg(M_FATAL, "Private key does not match the certificate");
1316  }
1317  ret = 0;
1318 
1319 end:
1320  EVP_PKEY_free(pkey);
1321  BIO_free(in);
1322  return ret;
1323 }
1324 
1325 void
1326 backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file,
1327  bool crl_inline)
1328 {
1329  BIO *in = NULL;
1330 
1331  X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx->ctx);
1332  if (!store)
1333  {
1334  crypto_msg(M_FATAL, "Cannot get certificate store");
1335  }
1336 
1337  /* Always start with a cleared CRL list, for that we
1338  * we need to manually find the CRL object from the stack
1339  * and remove it */
1340  STACK_OF(X509_OBJECT) *objs = X509_STORE_get0_objects(store);
1341  for (int i = 0; i < sk_X509_OBJECT_num(objs); i++)
1342  {
1343  X509_OBJECT *obj = sk_X509_OBJECT_value(objs, i);
1344  ASSERT(obj);
1345  if (X509_OBJECT_get_type(obj) == X509_LU_CRL)
1346  {
1347  sk_X509_OBJECT_delete(objs, i);
1348  X509_OBJECT_free(obj);
1349  }
1350  }
1351 
1352  X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1353 
1354  if (crl_inline)
1355  {
1356  in = BIO_new_mem_buf((char *) crl_file, -1);
1357  }
1358  else
1359  {
1360  in = BIO_new_file(crl_file, "r");
1361  }
1362 
1363  if (in == NULL)
1364  {
1365  msg(M_WARN, "CRL: cannot read: %s",
1366  print_key_filename(crl_file, crl_inline));
1367  goto end;
1368  }
1369 
1370  int num_crls_loaded = 0;
1371  while (true)
1372  {
1373  X509_CRL *crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL);
1374  if (crl == NULL)
1375  {
1376  /*
1377  * PEM_R_NO_START_LINE can be considered equivalent to EOF.
1378  */
1379  bool eof = ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE;
1380  /* but warn if no CRLs have been loaded */
1381  if (num_crls_loaded > 0 && eof)
1382  {
1383  /* remove that error from error stack */
1384  (void)ERR_get_error();
1385  break;
1386  }
1387 
1388  crypto_msg(M_WARN, "CRL: cannot read CRL from file %s",
1389  print_key_filename(crl_file, crl_inline));
1390  break;
1391  }
1392 
1393  if (!X509_STORE_add_crl(store, crl))
1394  {
1395  X509_CRL_free(crl);
1396  crypto_msg(M_WARN, "CRL: cannot add %s to store",
1397  print_key_filename(crl_file, crl_inline));
1398  break;
1399  }
1400  X509_CRL_free(crl);
1401  num_crls_loaded++;
1402  }
1403  msg(M_INFO, "CRL: loaded %d CRLs from file %s", num_crls_loaded, crl_file);
1404 end:
1405  BIO_free(in);
1406 }
1407 
1408 
1409 #if defined(ENABLE_MANAGEMENT) && !defined(HAVE_XKEY_PROVIDER)
1410 
1411 /* encrypt */
1412 static int
1413 rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1414 {
1415  ASSERT(0);
1416  return -1;
1417 }
1418 
1419 /* verify arbitrary data */
1420 static int
1421 rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1422 {
1423  ASSERT(0);
1424  return -1;
1425 }
1426 
1427 /* decrypt */
1428 static int
1429 rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
1430 {
1431  ASSERT(0);
1432  return -1;
1433 }
1434 
1435 /* called at RSA_free */
1436 static int
1438 {
1439  /* meth was allocated in tls_ctx_use_management_external_key() ; since
1440  * this function is called when the parent RSA object is destroyed,
1441  * it is no longer used after this point so kill it. */
1442  const RSA_METHOD *meth = RSA_get_method(rsa);
1443  RSA_meth_free((RSA_METHOD *)meth);
1444  return 1;
1445 }
1446 
1447 /*
1448  * Convert OpenSSL's constant to the strings used in the management
1449  * interface query
1450  */
1451 const char *
1452 get_rsa_padding_name(const int padding)
1453 {
1454  switch (padding)
1455  {
1456  case RSA_PKCS1_PADDING:
1457  return "RSA_PKCS1_PADDING";
1458 
1459  case RSA_NO_PADDING:
1460  return "RSA_NO_PADDING";
1461 
1462  default:
1463  return "UNKNOWN";
1464  }
1465 }
1466 
1478 static int
1479 get_sig_from_man(const unsigned char *dgst, unsigned int dgstlen,
1480  unsigned char *sig, unsigned int siglen,
1481  const char *algorithm)
1482 {
1483  char *in_b64 = NULL;
1484  char *out_b64 = NULL;
1485  int len = -1;
1486 
1487  int bencret = openvpn_base64_encode(dgst, dgstlen, &in_b64);
1488 
1489  if (management && bencret > 0)
1490  {
1491  out_b64 = management_query_pk_sig(management, in_b64, algorithm);
1492 
1493  }
1494  if (out_b64)
1495  {
1496  len = openvpn_base64_decode(out_b64, sig, siglen);
1497  }
1498 
1499  free(in_b64);
1500  free(out_b64);
1501  return len;
1502 }
1503 
1504 /* sign arbitrary data */
1505 static int
1506 rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa,
1507  int padding)
1508 {
1509  unsigned int len = RSA_size(rsa);
1510  int ret = -1;
1511 
1512  if (padding != RSA_PKCS1_PADDING && padding != RSA_NO_PADDING)
1513  {
1514  RSAerr(RSA_F_RSA_OSSL_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
1515  return -1;
1516  }
1517 
1518  ret = get_sig_from_man(from, flen, to, len, get_rsa_padding_name(padding));
1519 
1520  return (ret == len) ? ret : -1;
1521 }
1522 
1523 static int
1524 tls_ctx_use_external_rsa_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
1525 {
1526  RSA *rsa = NULL;
1527  RSA_METHOD *rsa_meth;
1528 
1529  ASSERT(NULL != ctx);
1530 
1531  const RSA *pub_rsa = EVP_PKEY_get0_RSA(pkey);
1532  ASSERT(NULL != pub_rsa);
1533 
1534  /* allocate custom RSA method object */
1535  rsa_meth = RSA_meth_new("OpenVPN external private key RSA Method",
1536  RSA_METHOD_FLAG_NO_CHECK);
1537  check_malloc_return(rsa_meth);
1538  RSA_meth_set_pub_enc(rsa_meth, rsa_pub_enc);
1539  RSA_meth_set_pub_dec(rsa_meth, rsa_pub_dec);
1540  RSA_meth_set_priv_enc(rsa_meth, rsa_priv_enc);
1541  RSA_meth_set_priv_dec(rsa_meth, rsa_priv_dec);
1542  RSA_meth_set_init(rsa_meth, NULL);
1543  RSA_meth_set_finish(rsa_meth, openvpn_extkey_rsa_finish);
1544  RSA_meth_set0_app_data(rsa_meth, NULL);
1545 
1546  /* allocate RSA object */
1547  rsa = RSA_new();
1548  if (rsa == NULL)
1549  {
1550  SSLerr(SSL_F_SSL_USE_PRIVATEKEY, ERR_R_MALLOC_FAILURE);
1551  goto err;
1552  }
1553 
1554  /* initialize RSA object */
1555  const BIGNUM *n = NULL;
1556  const BIGNUM *e = NULL;
1557  RSA_get0_key(pub_rsa, &n, &e, NULL);
1558  RSA_set0_key(rsa, BN_dup(n), BN_dup(e), NULL);
1559  RSA_set_flags(rsa, RSA_flags(rsa) | RSA_FLAG_EXT_PKEY);
1560  if (!RSA_set_method(rsa, rsa_meth))
1561  {
1562  RSA_meth_free(rsa_meth);
1563  goto err;
1564  }
1565  /* from this point rsa_meth will get freed with rsa */
1566 
1567  /* bind our custom RSA object to ssl_ctx */
1568  if (!SSL_CTX_use_RSAPrivateKey(ctx->ctx, rsa))
1569  {
1570  goto err;
1571  }
1572 
1573  RSA_free(rsa); /* doesn't necessarily free, just decrements refcount */
1574  return 1;
1575 
1576 err:
1577  if (rsa)
1578  {
1579  RSA_free(rsa);
1580  }
1581  else if (rsa_meth)
1582  {
1583  RSA_meth_free(rsa_meth);
1584  }
1585  return 0;
1586 }
1587 
1588 #if !defined(OPENSSL_NO_EC)
1589 
1590 /* called when EC_KEY is destroyed */
1591 static void
1593 {
1594  /* release the method structure */
1595  const EC_KEY_METHOD *ec_meth = EC_KEY_get_method(ec);
1596  EC_KEY_METHOD_free((EC_KEY_METHOD *) ec_meth);
1597 }
1598 
1599 /* EC_KEY_METHOD callback: sign().
1600  * Sign the hash using EC key and return DER encoded signature in sig,
1601  * its length in siglen. Return value is 1 on success, 0 on error.
1602  */
1603 static int
1604 ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig,
1605  unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *ec)
1606 {
1607  int capacity = ECDSA_size(ec);
1608  /*
1609  * ECDSA does not seem to have proper constants for paddings since
1610  * there are only signatures without padding at the moment, use
1611  * a generic ECDSA for the moment
1612  */
1613  int len = get_sig_from_man(dgst, dgstlen, sig, capacity, "ECDSA");
1614 
1615  if (len > 0)
1616  {
1617  *siglen = len;
1618  return 1;
1619  }
1620  return 0;
1621 }
1622 
1623 /* EC_KEY_METHOD callback: sign_setup(). We do no precomputations */
1624 static int
1625 ecdsa_sign_setup(EC_KEY *ec, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
1626 {
1627  return 1;
1628 }
1629 
1630 /* EC_KEY_METHOD callback: sign_sig().
1631  * Sign the hash and return the result as a newly allocated ECDS_SIG
1632  * struct or NULL on error.
1633  */
1634 static ECDSA_SIG *
1635 ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_kinv,
1636  const BIGNUM *in_r, EC_KEY *ec)
1637 {
1638  ECDSA_SIG *ecsig = NULL;
1639  unsigned int len = ECDSA_size(ec);
1640  struct gc_arena gc = gc_new();
1641 
1642  unsigned char *buf = gc_malloc(len, false, &gc);
1643  if (ecdsa_sign(0, dgst, dgstlen, buf, &len, NULL, NULL, ec) != 1)
1644  {
1645  goto out;
1646  }
1647  /* const char ** should be avoided: not up to us, so we cast our way through */
1648  ecsig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&buf, len);
1649 
1650 out:
1651  gc_free(&gc);
1652  return ecsig;
1653 }
1654 
1655 static int
1656 tls_ctx_use_external_ec_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
1657 {
1658  EC_KEY *ec = NULL;
1659  EVP_PKEY *privkey = NULL;
1660  EC_KEY_METHOD *ec_method;
1661 
1662  ASSERT(ctx);
1663 
1664  ec_method = EC_KEY_METHOD_new(EC_KEY_OpenSSL());
1665  if (!ec_method)
1666  {
1667  goto err;
1668  }
1669 
1670  /* Among init methods, we only need the finish method */
1671  EC_KEY_METHOD_set_init(ec_method, NULL, openvpn_extkey_ec_finish, NULL, NULL, NULL, NULL);
1672 #ifdef OPENSSL_IS_AWSLC
1673  EC_KEY_METHOD_set_sign(ec_method, ecdsa_sign, NULL, ecdsa_sign_sig);
1674 #else
1675  EC_KEY_METHOD_set_sign(ec_method, ecdsa_sign, ecdsa_sign_setup, ecdsa_sign_sig);
1676 #endif
1677 
1678  ec = EC_KEY_dup(EVP_PKEY_get0_EC_KEY(pkey));
1679  if (!ec)
1680  {
1681  EC_KEY_METHOD_free(ec_method);
1682  goto err;
1683  }
1684  if (!EC_KEY_set_method(ec, ec_method))
1685  {
1686  EC_KEY_METHOD_free(ec_method);
1687  goto err;
1688  }
1689  /* from this point ec_method will get freed when ec is freed */
1690 
1691  privkey = EVP_PKEY_new();
1692  if (!EVP_PKEY_assign_EC_KEY(privkey, ec))
1693  {
1694  goto err;
1695  }
1696  /* from this point ec will get freed when privkey is freed */
1697 
1698  if (!SSL_CTX_use_PrivateKey(ctx->ctx, privkey))
1699  {
1700  ec = NULL; /* avoid double freeing it below */
1701  goto err;
1702  }
1703 
1704  EVP_PKEY_free(privkey); /* this will down ref privkey and ec */
1705  return 1;
1706 
1707 err:
1708  /* Reach here only when ec and privkey can be independenly freed */
1709  EVP_PKEY_free(privkey);
1710  EC_KEY_free(ec);
1711  return 0;
1712 }
1713 #endif /* !defined(OPENSSL_NO_EC) */
1714 #endif /* ENABLE_MANAGEMENT && !HAVE_XKEY_PROVIDER */
1715 
1716 #ifdef ENABLE_MANAGEMENT
1717 int
1719 {
1720  int ret = 1;
1721 
1722  ASSERT(NULL != ctx);
1723 
1724  X509 *cert = SSL_CTX_get0_certificate(ctx->ctx);
1725 
1726  ASSERT(NULL != cert);
1727 
1728  /* get the public key */
1729  EVP_PKEY *pkey = X509_get0_pubkey(cert);
1730  ASSERT(pkey); /* NULL before SSL_CTX_use_certificate() is called */
1731 
1732 #ifdef HAVE_XKEY_PROVIDER
1733  EVP_PKEY *privkey = xkey_load_management_key(tls_libctx, pkey);
1734  if (!privkey
1735  || !SSL_CTX_use_PrivateKey(ctx->ctx, privkey))
1736  {
1737  EVP_PKEY_free(privkey);
1738  goto cleanup;
1739  }
1740  EVP_PKEY_free(privkey);
1741 #else /* ifdef HAVE_XKEY_PROVIDER */
1742 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1743  if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA)
1744 #else /* OPENSSL_VERSION_NUMBER < 0x30000000L */
1745  if (EVP_PKEY_is_a(pkey, "RSA"))
1746 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */
1747  {
1748  if (!tls_ctx_use_external_rsa_key(ctx, pkey))
1749  {
1750  goto cleanup;
1751  }
1752  }
1753 #if !defined(OPENSSL_NO_EC)
1754 #if OPENSSL_VERSION_NUMBER < 0x30000000L
1755  else if (EVP_PKEY_id(pkey) == EVP_PKEY_EC)
1756 #else /* OPENSSL_VERSION_NUMBER < 0x30000000L */
1757  else if (EVP_PKEY_is_a(pkey, "EC"))
1758 #endif /* OPENSSL_VERSION_NUMBER < 0x30000000L */
1759  {
1760  if (!tls_ctx_use_external_ec_key(ctx, pkey))
1761  {
1762  goto cleanup;
1763  }
1764  }
1765  else
1766  {
1767  crypto_msg(M_WARN, "management-external-key requires an RSA or EC certificate");
1768  goto cleanup;
1769  }
1770 #else /* !defined(OPENSSL_NO_EC) */
1771  else
1772  {
1773  crypto_msg(M_WARN, "management-external-key requires an RSA certificate");
1774  goto cleanup;
1775  }
1776 #endif /* !defined(OPENSSL_NO_EC) */
1777 
1778 #endif /* HAVE_XKEY_PROVIDER */
1779 
1780  ret = 0;
1781 cleanup:
1782  if (ret)
1783  {
1784  crypto_msg(M_FATAL, "Cannot enable SSL external private key capability");
1785  }
1786  return ret;
1787 }
1788 
1789 #endif /* ifdef ENABLE_MANAGEMENT */
1790 
1791 static int
1792 sk_x509_name_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
1793 {
1794  return X509_NAME_cmp(*a, *b);
1795 }
1796 
1797 void
1798 tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file,
1799  bool ca_file_inline, const char *ca_path, bool tls_server)
1800 {
1801  STACK_OF(X509_INFO) *info_stack = NULL;
1802  STACK_OF(X509_NAME) *cert_names = NULL;
1803  X509_LOOKUP *lookup = NULL;
1804  X509_STORE *store = NULL;
1805  X509_NAME *xn = NULL;
1806  BIO *in = NULL;
1807  int i, added = 0, prev = 0;
1808 
1809  ASSERT(NULL != ctx);
1810 
1811  store = SSL_CTX_get_cert_store(ctx->ctx);
1812  if (!store)
1813  {
1814  crypto_msg(M_FATAL, "Cannot get certificate store");
1815  }
1816 
1817  /* Try to add certificates and CRLs from ca_file */
1818  if (ca_file)
1819  {
1820  if (ca_file_inline)
1821  {
1822  in = BIO_new_mem_buf((char *)ca_file, -1);
1823  }
1824  else
1825  {
1826  in = BIO_new_file(ca_file, "r");
1827  }
1828 
1829  if (in)
1830  {
1831  info_stack = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
1832  }
1833 
1834  if (info_stack)
1835  {
1836  for (i = 0; i < sk_X509_INFO_num(info_stack); i++)
1837  {
1838  X509_INFO *info = sk_X509_INFO_value(info_stack, i);
1839  if (info->crl)
1840  {
1841  X509_STORE_add_crl(store, info->crl);
1842  }
1843 
1844  if (tls_server && !info->x509)
1845  {
1846  crypto_msg(M_FATAL, "X509 name was missing in TLS mode");
1847  }
1848 
1849  if (info->x509)
1850  {
1851  X509_STORE_add_cert(store, info->x509);
1852  added++;
1853 
1854  if (!tls_server)
1855  {
1856  continue;
1857  }
1858 
1859  /* Use names of CAs as a client CA list */
1860  if (cert_names == NULL)
1861  {
1862  cert_names = sk_X509_NAME_new(sk_x509_name_cmp);
1863  if (!cert_names)
1864  {
1865  continue;
1866  }
1867  }
1868 
1869  xn = X509_get_subject_name(info->x509);
1870  if (!xn)
1871  {
1872  continue;
1873  }
1874 
1875  /* Don't add duplicate CA names */
1876  if (sk_X509_NAME_find(cert_names, xn) == -1)
1877  {
1878  xn = X509_NAME_dup(xn);
1879  if (!xn)
1880  {
1881  continue;
1882  }
1883  sk_X509_NAME_push(cert_names, xn);
1884  }
1885  }
1886 
1887  if (tls_server)
1888  {
1889  int cnum = sk_X509_NAME_num(cert_names);
1890  if (cnum != (prev + 1))
1891  {
1893  "Cannot load CA certificate file %s (entry %d did not validate)",
1894  print_key_filename(ca_file, ca_file_inline),
1895  added);
1896  }
1897  prev = cnum;
1898  }
1899  }
1900  sk_X509_INFO_pop_free(info_stack, X509_INFO_free);
1901  }
1902  int cnum;
1903  if (tls_server)
1904  {
1905  cnum = sk_X509_NAME_num(cert_names);
1906  SSL_CTX_set_client_CA_list(ctx->ctx, cert_names);
1907  }
1908 
1909  if (!added)
1910  {
1912  "Cannot load CA certificate file %s (no entries were read)",
1913  print_key_filename(ca_file, ca_file_inline));
1914  }
1915 
1916  if (tls_server)
1917  {
1918  if (cnum != added)
1919  {
1920  crypto_msg(M_FATAL, "Cannot load CA certificate file %s (only %d "
1921  "of %d entries were valid X509 names)",
1922  print_key_filename(ca_file, ca_file_inline), cnum,
1923  added);
1924  }
1925  }
1926 
1927  BIO_free(in);
1928  }
1929 
1930  /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
1931  if (ca_path)
1932  {
1933  lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1934  if (lookup && X509_LOOKUP_add_dir(lookup, ca_path, X509_FILETYPE_PEM))
1935  {
1936  msg(M_WARN, "WARNING: experimental option --capath %s", ca_path);
1937  }
1938  else
1939  {
1940  crypto_msg(M_FATAL, "Cannot add lookup at --capath %s", ca_path);
1941  }
1942  X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1943  }
1944 }
1945 
1946 void
1947 tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file,
1948  bool extra_certs_file_inline)
1949 {
1950  BIO *in;
1951  if (extra_certs_file_inline)
1952  {
1953  in = BIO_new_mem_buf((char *)extra_certs_file, -1);
1954  }
1955  else
1956  {
1957  in = BIO_new_file(extra_certs_file, "r");
1958  }
1959 
1960  if (in == NULL)
1961  {
1962  crypto_msg(M_FATAL, "Cannot load extra-certs file: %s",
1963  print_key_filename(extra_certs_file,
1964  extra_certs_file_inline));
1965 
1966  }
1967  else
1968  {
1969  tls_ctx_add_extra_certs(ctx, in, false);
1970  }
1971 
1972  BIO_free(in);
1973 }
1974 
1975 /* **************************************
1976  *
1977  * Key-state specific functions
1978  *
1979  ***************************************/
1980 /*
1981  *
1982  * BIO functions
1983  *
1984  */
1985 
1986 #ifdef BIO_DEBUG
1987 
1988 #warning BIO_DEBUG defined
1989 
1990 static FILE *biofp; /* GLOBAL */
1991 static bool biofp_toggle; /* GLOBAL */
1992 static time_t biofp_last_open; /* GLOBAL */
1993 static const int biofp_reopen_interval = 600; /* GLOBAL */
1994 
1995 static void
1996 close_biofp(void)
1997 {
1998  if (biofp)
1999  {
2000  ASSERT(!fclose(biofp));
2001  biofp = NULL;
2002  }
2003 }
2004 
2005 static void
2006 open_biofp(void)
2007 {
2008  const time_t current = time(NULL);
2009  const pid_t pid = getpid();
2010 
2011  if (biofp_last_open + biofp_reopen_interval < current)
2012  {
2013  close_biofp();
2014  }
2015  if (!biofp)
2016  {
2017  char fn[256];
2018  snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
2019  biofp = fopen(fn, "w");
2020  ASSERT(biofp);
2021  biofp_last_open = time(NULL);
2022  biofp_toggle ^= 1;
2023  }
2024 }
2025 
2026 static void
2027 bio_debug_data(const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
2028 {
2029  struct gc_arena gc = gc_new();
2030  if (len > 0)
2031  {
2032  open_biofp();
2033  fprintf(biofp, "BIO_%s %s time=%" PRIi64 " bio=" ptr_format " len=%d data=%s\n",
2034  mode, desc, (int64_t)time(NULL), (ptr_type)bio, len, format_hex(buf, len, 0, &gc));
2035  fflush(biofp);
2036  }
2037  gc_free(&gc);
2038 }
2039 
2040 static void
2041 bio_debug_oc(const char *mode, BIO *bio)
2042 {
2043  open_biofp();
2044  fprintf(biofp, "BIO %s time=%" PRIi64 " bio=" ptr_format "\n",
2045  mode, (int64_t)time(NULL), (ptr_type)bio);
2046  fflush(biofp);
2047 }
2048 
2049 #endif /* ifdef BIO_DEBUG */
2050 
2051 /*
2052  * Write to an OpenSSL BIO in non-blocking mode.
2053  */
2054 static int
2055 bio_write(BIO *bio, const uint8_t *data, int size, const char *desc)
2056 {
2057  int i;
2058  int ret = 0;
2059  ASSERT(size >= 0);
2060  if (size)
2061  {
2062  /*
2063  * Free the L_TLS lock prior to calling BIO routines
2064  * so that foreground thread can still call
2065  * tls_pre_decrypt or tls_pre_encrypt,
2066  * allowing tunnel packet forwarding to continue.
2067  */
2068 #ifdef BIO_DEBUG
2069  bio_debug_data("write", bio, data, size, desc);
2070 #endif
2071  i = BIO_write(bio, data, size);
2072 
2073  if (i < 0)
2074  {
2075  if (!BIO_should_retry(bio))
2076  {
2077  crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s error", desc);
2078  ret = -1;
2079  ERR_clear_error();
2080  }
2081  }
2082  else if (i != size)
2083  {
2084  crypto_msg(D_TLS_ERRORS, "TLS ERROR: BIO write %s incomplete %d/%d",
2085  desc, i, size);
2086  ret = -1;
2087  ERR_clear_error();
2088  }
2089  else
2090  { /* successful write */
2091  dmsg(D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
2092  ret = 1;
2093  }
2094  }
2095  return ret;
2096 }
2097 
2098 /*
2099  * Inline functions for reading from and writing
2100  * to BIOs.
2101  */
2102 
2103 static void
2104 bio_write_post(const int status, struct buffer *buf)
2105 {
2106  if (status == 1) /* success status return from bio_write? */
2107  {
2108  memset(BPTR(buf), 0, BLEN(buf)); /* erase data just written */
2109  buf->len = 0;
2110  }
2111 }
2112 
2113 /*
2114  * Read from an OpenSSL BIO in non-blocking mode.
2115  */
2116 static int
2117 bio_read(BIO *bio, struct buffer *buf, const char *desc)
2118 {
2119  ASSERT(buf->len >= 0);
2120  if (buf->len)
2121  {
2122  /* we only want to write empty buffers, ignore read request
2123  * if the buffer is not empty */
2124  return 0;
2125  }
2126  int len = buf_forward_capacity(buf);
2127 
2128  /*
2129  * BIO_read brackets most of the serious RSA
2130  * key negotiation number crunching.
2131  */
2132  int i = BIO_read(bio, BPTR(buf), len);
2133 
2134  VALGRIND_MAKE_READABLE((void *) &i, sizeof(i));
2135 
2136 #ifdef BIO_DEBUG
2137  bio_debug_data("read", bio, BPTR(buf), i, desc);
2138 #endif
2139 
2140  int ret = 0;
2141  if (i < 0)
2142  {
2143  if (!BIO_should_retry(bio))
2144  {
2145  crypto_msg(D_TLS_ERRORS, "TLS_ERROR: BIO read %s error", desc);
2146  buf->len = 0;
2147  ret = -1;
2148  ERR_clear_error();
2149  }
2150  }
2151  else if (!i)
2152  {
2153  buf->len = 0;
2154  }
2155  else
2156  { /* successful read */
2157  dmsg(D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
2158  buf->len = i;
2159  ret = 1;
2160  VALGRIND_MAKE_READABLE((void *) BPTR(buf), BLEN(buf));
2161  }
2162  return ret;
2163 }
2164 
2165 void
2166 key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
2167 {
2168  ASSERT(NULL != ssl_ctx);
2169  ASSERT(ks_ssl);
2170  CLEAR(*ks_ssl);
2171 
2172  ks_ssl->ssl = SSL_new(ssl_ctx->ctx);
2173  if (!ks_ssl->ssl)
2174  {
2175  crypto_msg(M_FATAL, "SSL_new failed");
2176  }
2177 
2178  /* put session * in ssl object so we can access it
2179  * from verify callback*/
2180  SSL_set_ex_data(ks_ssl->ssl, mydata_index, session);
2181 
2182  ASSERT((ks_ssl->ssl_bio = BIO_new(BIO_f_ssl())));
2183  ASSERT((ks_ssl->ct_in = BIO_new(BIO_s_mem())));
2184  ASSERT((ks_ssl->ct_out = BIO_new(BIO_s_mem())));
2185 
2186 #ifdef BIO_DEBUG
2187  bio_debug_oc("open ssl_bio", ks_ssl->ssl_bio);
2188  bio_debug_oc("open ct_in", ks_ssl->ct_in);
2189  bio_debug_oc("open ct_out", ks_ssl->ct_out);
2190 #endif
2191 
2192  if (is_server)
2193  {
2194  SSL_set_accept_state(ks_ssl->ssl);
2195  }
2196  else
2197  {
2198  SSL_set_connect_state(ks_ssl->ssl);
2199  }
2200 
2201  SSL_set_bio(ks_ssl->ssl, ks_ssl->ct_in, ks_ssl->ct_out);
2202  BIO_set_ssl(ks_ssl->ssl_bio, ks_ssl->ssl, BIO_NOCLOSE);
2203 }
2204 
2205 void
2207 {
2208  SSL_set_shutdown(ks_ssl->ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
2209 }
2210 
2211 void
2213 {
2214  if (ks_ssl->ssl)
2215  {
2216 #ifdef BIO_DEBUG
2217  bio_debug_oc("close ssl_bio", ks_ssl->ssl_bio);
2218  bio_debug_oc("close ct_in", ks_ssl->ct_in);
2219  bio_debug_oc("close ct_out", ks_ssl->ct_out);
2220 #endif
2221  BIO_free_all(ks_ssl->ssl_bio);
2222  SSL_free(ks_ssl->ssl);
2223  }
2224 }
2225 
2226 int
2227 key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
2228 {
2229  int ret = 0;
2231 
2232  ASSERT(NULL != ks_ssl);
2233 
2234  ret = bio_write(ks_ssl->ssl_bio, BPTR(buf), BLEN(buf),
2235  "tls_write_plaintext");
2236  bio_write_post(ret, buf);
2237 
2238  perf_pop();
2239  return ret;
2240 }
2241 
2242 int
2243 key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
2244 {
2245  int ret = 0;
2247 
2248  ASSERT(NULL != ks_ssl);
2249 
2250  ret = bio_write(ks_ssl->ssl_bio, data, len, "tls_write_plaintext_const");
2251 
2252  perf_pop();
2253  return ret;
2254 }
2255 
2256 int
2257 key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
2258 {
2259  int ret = 0;
2261 
2262  ASSERT(NULL != ks_ssl);
2263 
2264  ret = bio_read(ks_ssl->ct_out, buf, "tls_read_ciphertext");
2265 
2266  perf_pop();
2267  return ret;
2268 }
2269 
2270 int
2272 {
2273  int ret = 0;
2275 
2276  ASSERT(NULL != ks_ssl);
2277 
2278  ret = bio_write(ks_ssl->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
2279  bio_write_post(ret, buf);
2280 
2281  perf_pop();
2282  return ret;
2283 }
2284 
2285 int
2286 key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
2287 {
2288  int ret = 0;
2290 
2291  ASSERT(NULL != ks_ssl);
2292 
2293  ret = bio_read(ks_ssl->ssl_bio, buf, "tls_read_plaintext");
2294 
2295  perf_pop();
2296  return ret;
2297 }
2298 
2299 static void
2300 print_pkey_details(EVP_PKEY *pkey, char *buf, size_t buflen)
2301 {
2302  const char *curve = "";
2303  const char *type = "(error getting type)";
2304 
2305  if (pkey == NULL)
2306  {
2307  buf[0] = 0;
2308  return;
2309  }
2310 
2311  int typeid = EVP_PKEY_id(pkey);
2312 #if OPENSSL_VERSION_NUMBER < 0x30000000L
2313  bool is_ec = typeid == EVP_PKEY_EC;
2314 #else
2315  bool is_ec = EVP_PKEY_is_a(pkey, "EC");
2316 #endif
2317 
2318 #ifndef OPENSSL_NO_EC
2319  char groupname[64];
2320  if (is_ec)
2321  {
2322  size_t len;
2323  if (EVP_PKEY_get_group_name(pkey, groupname, sizeof(groupname), &len))
2324  {
2325  curve = groupname;
2326  }
2327  else
2328  {
2329  curve = "(error getting curve name)";
2330  }
2331  }
2332 #endif
2333  if (typeid != 0)
2334  {
2335 #if OPENSSL_VERSION_NUMBER < 0x30000000L
2336  type = OBJ_nid2sn(typeid);
2337 
2338  /* OpenSSL reports rsaEncryption, dsaEncryption and
2339  * id-ecPublicKey, map these values to nicer ones */
2340  if (typeid == EVP_PKEY_RSA)
2341  {
2342  type = "RSA";
2343  }
2344  else if (typeid == EVP_PKEY_DSA)
2345  {
2346  type = "DSA";
2347  }
2348  else if (typeid == EVP_PKEY_EC)
2349  {
2350  /* EC gets the curve appended after the type */
2351  type = "EC, curve ";
2352  }
2353  else if (type == NULL)
2354  {
2355  type = "unknown type";
2356  }
2357 #else /* OpenSSL >= 3 */
2358  type = EVP_PKEY_get0_type_name(pkey);
2359  if (type == NULL)
2360  {
2361  type = "(error getting public key type)";
2362  }
2363 #endif /* if OPENSSL_VERSION_NUMBER < 0x30000000L */
2364  }
2365 
2366  snprintf(buf, buflen, "%d bits %s%s",
2367  EVP_PKEY_bits(pkey), type, curve);
2368 }
2369 
2376 static void
2377 print_cert_details(X509 *cert, char *buf, size_t buflen)
2378 {
2379  EVP_PKEY *pkey = X509_get_pubkey(cert);
2380  char pkeybuf[64] = { 0 };
2381  print_pkey_details(pkey, pkeybuf, sizeof(pkeybuf));
2382 
2383  char sig[128] = { 0 };
2384  int signature_nid = X509_get_signature_nid(cert);
2385  if (signature_nid != 0)
2386  {
2387  snprintf(sig, sizeof(sig), ", signature: %s",
2388  OBJ_nid2sn(signature_nid));
2389  }
2390 
2391  snprintf(buf, buflen, ", peer certificate: %s%s",
2392  pkeybuf, sig);
2393 
2394  EVP_PKEY_free(pkey);
2395 }
2396 
2397 static void
2398 print_server_tempkey(SSL *ssl, char *buf, size_t buflen)
2399 {
2400  EVP_PKEY *pkey = NULL;
2401  SSL_get_peer_tmp_key(ssl, &pkey);
2402  if (!pkey)
2403  {
2404  return;
2405  }
2406 
2407  char pkeybuf[128] = { 0 };
2408  print_pkey_details(pkey, pkeybuf, sizeof(pkeybuf));
2409 
2410  snprintf(buf, buflen, ", peer temporary key: %s",
2411  pkeybuf);
2412 
2413  EVP_PKEY_free(pkey);
2414 }
2415 
2416 #if !defined(LIBRESSL_VERSION_NUMBER) \
2417  || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x3090000fL)
2418 
2423 static const char *
2424 get_sigtype(int nid)
2425 {
2426  /* Fix a few OpenSSL names to be better understandable */
2427  switch (nid)
2428  {
2429  case EVP_PKEY_RSA:
2430  /* will otherwise say rsaEncryption */
2431  return "RSA";
2432 
2433  case EVP_PKEY_DSA:
2434  /* dsaEncryption otherwise */
2435  return "DSA";
2436 
2437  case EVP_PKEY_EC:
2438  /* will say id-ecPublicKey */
2439  return "ECDSA";
2440 
2441  case -1:
2442  return "(error getting name)";
2443 
2444  default:
2445  return OBJ_nid2sn(nid);
2446  }
2447 }
2448 #endif /* ifndef LIBRESSL_VERSION_NUMBER */
2449 
2454 static void
2455 print_peer_signature(SSL *ssl, char *buf, size_t buflen)
2456 {
2457  int peer_sig_nid = NID_undef, peer_sig_type_nid = NID_undef;
2458  const char *peer_sig = "unknown";
2459  const char *peer_sig_type = "unknown type";
2460 
2461  /* Even though these methods use the deprecated NIDs instead of using
2462  * string as new OpenSSL APIs do, there seem to be no API that replaces
2463  * it yet */
2464 #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER > 0x3050400fL
2465  if (SSL_get_peer_signature_nid(ssl, &peer_sig_nid)
2466  && peer_sig_nid != NID_undef)
2467  {
2468  peer_sig = OBJ_nid2sn(peer_sig_nid);
2469  }
2470 #endif
2471 
2472 #if !defined(LIBRESSL_VERSION_NUMBER) \
2473  || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x3090000fL)
2474  /* LibreSSL 3.7.x and 3.8.x implement this function but do not export it
2475  * and fail linking with an unresolved symbol */
2476  if (SSL_get_peer_signature_type_nid(ssl, &peer_sig_type_nid)
2477  && peer_sig_type_nid != NID_undef)
2478  {
2479  peer_sig_type = get_sigtype(peer_sig_type_nid);
2480  }
2481 #endif
2482 
2483  if (peer_sig_nid == NID_undef && peer_sig_type_nid == NID_undef)
2484  {
2485  return;
2486  }
2487 
2488  snprintf(buf, buflen, ", peer signing digest/type: %s %s",
2489  peer_sig, peer_sig_type);
2490 }
2491 
2492 
2493 
2494 /* **************************************
2495  *
2496  * Information functions
2497  *
2498  * Print information for the end user.
2499  *
2500  ***************************************/
2501 void
2502 print_details(struct key_state_ssl *ks_ssl, const char *prefix)
2503 {
2504  const SSL_CIPHER *ciph;
2505  char s1[256];
2506  char s2[256];
2507  char s3[256];
2508  char s4[256];
2509 
2510  s1[0] = s2[0] = s3[0] = s4[0] = 0;
2511  ciph = SSL_get_current_cipher(ks_ssl->ssl);
2512  snprintf(s1, sizeof(s1), "%s %s, cipher %s %s",
2513  prefix,
2514  SSL_get_version(ks_ssl->ssl),
2515  SSL_CIPHER_get_version(ciph),
2516  SSL_CIPHER_get_name(ciph));
2517  X509 *cert = SSL_get_peer_certificate(ks_ssl->ssl);
2518 
2519  if (cert)
2520  {
2521  print_cert_details(cert, s2, sizeof(s2));
2522  X509_free(cert);
2523  }
2524  print_server_tempkey(ks_ssl->ssl, s3, sizeof(s3));
2525  print_peer_signature(ks_ssl->ssl, s4, sizeof(s4));
2526 
2527  msg(D_HANDSHAKE, "%s%s%s%s", s1, s2, s3, s4);
2528 }
2529 
2530 void
2531 show_available_tls_ciphers_list(const char *cipher_list,
2532  const char *tls_cert_profile,
2533  bool tls13)
2534 {
2535  struct tls_root_ctx tls_ctx;
2536 
2537  tls_ctx.ctx = SSL_CTX_new(SSLv23_method());
2538  if (!tls_ctx.ctx)
2539  {
2540  crypto_msg(M_FATAL, "Cannot create SSL_CTX object");
2541  }
2542 
2543 #if defined(TLS1_3_VERSION)
2544  if (tls13)
2545  {
2546  SSL_CTX_set_min_proto_version(tls_ctx.ctx,
2548  tls_ctx_restrict_ciphers_tls13(&tls_ctx, cipher_list);
2549  }
2550  else
2551 #endif
2552  {
2553  SSL_CTX_set_max_proto_version(tls_ctx.ctx, TLS1_2_VERSION);
2554  tls_ctx_restrict_ciphers(&tls_ctx, cipher_list);
2555  }
2556 
2557  tls_ctx_set_cert_profile(&tls_ctx, tls_cert_profile);
2558 
2559  SSL *ssl = SSL_new(tls_ctx.ctx);
2560  if (!ssl)
2561  {
2562  crypto_msg(M_FATAL, "Cannot create SSL object");
2563  }
2564 
2565 #if OPENSSL_VERSION_NUMBER < 0x1010000fL || defined(OPENSSL_IS_AWSLC)
2566  STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
2567 #else
2568  STACK_OF(SSL_CIPHER) *sk = SSL_get1_supported_ciphers(ssl);
2569 #endif
2570  for (int i = 0; i < sk_SSL_CIPHER_num(sk); i++)
2571  {
2572  const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i);
2573 
2574  const char *cipher_name = SSL_CIPHER_get_name(c);
2575 
2576  const tls_cipher_name_pair *pair =
2577  tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
2578 
2579  if (tls13)
2580  {
2581  printf("%s\n", cipher_name);
2582  }
2583  else if (NULL == pair)
2584  {
2585  /* No translation found, print warning */
2586  printf("%s (No IANA name known to OpenVPN, use OpenSSL name.)\n",
2587  cipher_name);
2588  }
2589  else
2590  {
2591  printf("%s\n", pair->iana_name);
2592  }
2593  }
2594 #if (OPENSSL_VERSION_NUMBER >= 0x1010000fL)
2595  sk_SSL_CIPHER_free(sk);
2596 #endif
2597  SSL_free(ssl);
2598  SSL_CTX_free(tls_ctx.ctx);
2599 }
2600 
2601 /*
2602  * Show the Elliptic curves that are available for us to use
2603  * in the OpenSSL library.
2604  */
2605 void
2607 {
2608  printf("Consider using 'openssl ecparam -list_curves' as alternative to running\n"
2609  "this command.\n"
2610  "Note this output does only list curves/groups that OpenSSL considers as\n"
2611  "builtin EC curves. It does not list additional curves nor X448 or X25519\n");
2612 #ifndef OPENSSL_NO_EC
2613  EC_builtin_curve *curves = NULL;
2614  size_t crv_len = 0;
2615  size_t n = 0;
2616 
2617  crv_len = EC_get_builtin_curves(NULL, 0);
2618  ALLOC_ARRAY(curves, EC_builtin_curve, crv_len);
2619  if (EC_get_builtin_curves(curves, crv_len))
2620  {
2621  printf("\nAvailable Elliptic curves/groups:\n");
2622  for (n = 0; n < crv_len; n++)
2623  {
2624  const char *sname;
2625  sname = OBJ_nid2sn(curves[n].nid);
2626  if (sname == NULL)
2627  {
2628  sname = "";
2629  }
2630 
2631  printf("%s\n", sname);
2632  }
2633  }
2634  else
2635  {
2636  crypto_msg(M_FATAL, "Cannot get list of builtin curves");
2637  }
2638  free(curves);
2639 #else /* ifndef OPENSSL_NO_EC */
2640  msg(M_WARN, "Your OpenSSL library was built without elliptic curve support. "
2641  "No curves available.");
2642 #endif /* ifndef OPENSSL_NO_EC */
2643 }
2644 
2645 const char *
2647 {
2648  return OpenSSL_version(OPENSSL_VERSION);
2649 }
2650 
2651 
2653 #ifdef HAVE_XKEY_PROVIDER
2654 static int
2655 provider_load(OSSL_PROVIDER *prov, void *dest_libctx)
2656 {
2657  const char *name = OSSL_PROVIDER_get0_name(prov);
2658  OSSL_PROVIDER_load(dest_libctx, name);
2659  return 1;
2660 }
2661 
2662 static int
2663 provider_unload(OSSL_PROVIDER *prov, void *unused)
2664 {
2665  (void) unused;
2666  OSSL_PROVIDER_unload(prov);
2667  return 1;
2668 }
2669 #endif /* HAVE_XKEY_PROVIDER */
2670 
2678 void
2680 {
2681 #ifdef HAVE_XKEY_PROVIDER
2682 
2683  /* Make a new library context for use in TLS context */
2684  if (!tls_libctx)
2685  {
2686  tls_libctx = OSSL_LIB_CTX_new();
2688 
2689  /* Load all providers in default LIBCTX into this libctx.
2690  * OpenSSL has a child libctx functionality to automate this,
2691  * but currently that is usable only from within providers.
2692  * So we do something close to it manually here.
2693  */
2694  OSSL_PROVIDER_do_all(NULL, provider_load, tls_libctx);
2695  }
2696 
2697  if (!OSSL_PROVIDER_available(tls_libctx, "ovpn.xkey"))
2698  {
2699  OSSL_PROVIDER_add_builtin(tls_libctx, "ovpn.xkey", xkey_provider_init);
2700  if (!OSSL_PROVIDER_load(tls_libctx, "ovpn.xkey"))
2701  {
2702  msg(M_NONFATAL, "ERROR: failed loading external key provider: "
2703  "Signing with external keys will not work.");
2704  }
2705  }
2706 
2707  /* We only implement minimal functionality in ovpn.xkey, so we do not want
2708  * methods in xkey to be picked unless absolutely required (i.e, when the key
2709  * is external). Ensure this by setting a default propquery for the custom
2710  * libctx that unprefers, but does not forbid, ovpn.xkey. See also man page
2711  * of "property" in OpenSSL 3.0.
2712  */
2713  EVP_set_default_properties(tls_libctx, "?provider!=ovpn.xkey");
2714 
2715 #endif /* HAVE_XKEY_PROVIDER */
2716 }
2717 
2721 static void
2723 {
2724 #ifdef HAVE_XKEY_PROVIDER
2725  if (tls_libctx)
2726  {
2727  OSSL_PROVIDER_do_all(tls_libctx, provider_unload, NULL);
2728  OSSL_LIB_CTX_free(tls_libctx);
2729  }
2730 #endif /* HAVE_XKEY_PROVIDER */
2731  tls_libctx = NULL;
2732 }
2733 
2734 #endif /* defined(ENABLE_CRYPTO_OPENSSL) */
SSLF_TLS_VERSION_MIN_SHIFT
#define SSLF_TLS_VERSION_MIN_SHIFT
Definition: ssl_common.h:421
tls_ctx_add_extra_certs
static void tls_ctx_add_extra_certs(struct tls_root_ctx *ctx, BIO *bio, bool optional)
Definition: ssl_openssl.c:1051
openvpn_base64_decode
int openvpn_base64_decode(const char *str, void *data, int size)
Definition: base64.c:158
D_TLS_DEBUG
#define D_TLS_DEBUG
Definition: errlevel.h:165
tls_ctx_set_options
bool tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Set any library specific options.
Definition: ssl_openssl.c:310
key_state_export_keying_material
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:156
get_rsa_padding_name
const char * get_rsa_padding_name(const int padding)
Definition: ssl_openssl.c:1452
M_INFO
#define M_INFO
Definition: errlevel.h:55
key_state_ssl
Definition: ssl_mbedtls.h:128
rsa_priv_dec
static int rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1429
tls_ctx_client_new
void tls_ctx_client_new(struct tls_root_ctx *ctx)
Initialises a library-specific TLS context for a client.
Definition: ssl_openssl.c:122
key_state_ssl::ct_in
BIO * ct_in
Definition: ssl_openssl.h:49
sk_x509_name_cmp
static int sk_x509_name_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
Definition: ssl_openssl.c:1792
ssl_backend.h
gc_new
static struct gc_arena gc_new(void)
Definition: buffer.h:1025
PERF_BIO_READ_PLAINTEXT
#define PERF_BIO_READ_PLAINTEXT
Definition: perf.h:38
tls_ctx_restrict_ciphers_tls13
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:492
SSLF_TLS_VERSION_MAX_MASK
#define SSLF_TLS_VERSION_MAX_MASK
Definition: ssl_common.h:424
convert_tls_list_to_openssl
static void convert_tls_list_to_openssl(char *openssl_ciphers, size_t len, const char *ciphers)
Definition: ssl_openssl.c:358
key_state_ssl_free
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:2212
buffer::len
int len
Length in bytes of the actual content within the allocated memory.
Definition: buffer.h:66
M_FATAL
#define M_FATAL
Definition: error.h:89
info_callback
static void info_callback(INFO_CALLBACK_SSL_CONST SSL *s, int where, int ret)
Definition: ssl_openssl.c:183
mydata_index
int mydata_index
Allocate space in SSL objects in which to store a struct tls_session pointer back to parent.
Definition: ssl_openssl.c:89
streq
#define streq(x, y)
Definition: options.h:726
management_auth_failure
void management_auth_failure(struct management *man, const char *type, const char *reason)
Definition: manage.c:3092
M_NONFATAL
#define M_NONFATAL
Definition: error.h:90
manage.h
D_HANDSHAKE_VERBOSE
#define D_HANDSHAKE_VERBOSE
Definition: errlevel.h:156
KS_PRIMARY
#define KS_PRIMARY
Primary key state index.
Definition: ssl_common.h:456
D_TLS_DEBUG_LOW
#define D_TLS_DEBUG_LOW
Definition: errlevel.h:77
print_details
void print_details(struct key_state_ssl *ks_ssl, const char *prefix)
Print a one line summary of SSL/TLS session handshake.
Definition: ssl_openssl.c:2502
ecdsa_sign
static int ecdsa_sign(int type, const unsigned char *dgst, int dgstlen, unsigned char *sig, unsigned int *siglen, const BIGNUM *kinv, const BIGNUM *r, EC_KEY *ec)
Definition: ssl_openssl.c:1604
tls_ctx_load_ca
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:1798
key_state_ssl::ssl_bio
BIO * ssl_bio
Definition: ssl_openssl.h:48
D_HANDSHAKE
#define D_HANDSHAKE
Definition: errlevel.h:72
key_state_ssl::ct_out
BIO * ct_out
Definition: ssl_openssl.h:50
TLS_VER_1_1
#define TLS_VER_1_1
Definition: ssl_backend.h:107
print_cert_details
static void print_cert_details(X509 *cert, char *buf, size_t buflen)
Print human readable information about the certificate into buf.
Definition: ssl_openssl.c:2377
get_num_elements
int get_num_elements(const char *string, char delimiter)
Returns the occurrences of 'delimiter' in a string +1 This is typically used to find out the number e...
Definition: ssl_util.c:284
session::key
char key[48]
Definition: keyingmaterialexporter.c:58
get_ssl_library_version
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:2646
tls_init_lib
void tls_init_lib(void)
Perform any static initialisation necessary by the library.
Definition: ssl_openssl.c:92
xkey_common.h
openvpn_base64_encode
int openvpn_base64_encode(const void *data, int size, char **str)
Definition: base64.c:52
get_sig_from_man
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 'dgst' to management and get the signature back.
Definition: ssl_openssl.c:1479
ssl_verify_openssl.h
VALGRIND_MAKE_READABLE
#define VALGRIND_MAKE_READABLE(addr, len)
Definition: memdbg.h:53
print_key_filename
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:1310
dmsg
#define dmsg(flags,...)
Definition: error.h:148
PERF_BIO_WRITE_PLAINTEXT
#define PERF_BIO_WRITE_PLAINTEXT
Definition: perf.h:39
D_LOW
#define D_LOW
Definition: errlevel.h:97
tls_ctx_load_dh_params
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:656
key_state_ssl::ssl
SSL * ssl
Definition: ssl_openssl.h:47
load_xkey_provider
void load_xkey_provider(void)
Some helper routines for provider load/unload.
Definition: ssl_openssl.c:2679
TLS_VER_1_0
#define TLS_VER_1_0
Definition: ssl_backend.h:106
get_sigtype
static const char * get_sigtype(int nid)
Translate an OpenSSL NID into a more human readable name.
Definition: ssl_openssl.c:2424
GET_USER_PASS_MANAGEMENT
#define GET_USER_PASS_MANAGEMENT
Definition: misc.h:109
key_state_write_ciphertext
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:2271
openvpn_extkey_rsa_finish
static int openvpn_extkey_rsa_finish(RSA *rsa)
Definition: ssl_openssl.c:1437
tls_ctx_set_tls_versions
static bool tls_ctx_set_tls_versions(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Definition: ssl_openssl.c:280
tls_ctx_use_external_rsa_key
static int tls_ctx_use_external_rsa_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
Definition: ssl_openssl.c:1524
CLEAR
#define CLEAR(x)
Definition: basic.h:33
tls_ctx_load_cert_file
void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_inline)
Load certificate file into the given TLS context.
Definition: ssl_openssl.c:1257
ssl_util.h
print_peer_signature
static void print_peer_signature(SSL *ssl, char *buf, size_t buflen)
Get the type of the signature that is used by the peer during the TLS handshake.
Definition: ssl_openssl.c:2455
key_state_read_plaintext
int key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Extract plaintext data from the TLS module.
Definition: ssl_openssl.c:2286
string_alloc
char * string_alloc(const char *str, struct gc_arena *gc)
Definition: buffer.c:649
secure_memzero
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition: buffer.h:414
ASSERT
#define ASSERT(x)
Definition: error.h:195
tls_get_cipher_name_pair
const tls_cipher_name_pair * tls_get_cipher_name_pair(const char *cipher_name, size_t len)
Definition: ssl_util.c:265
SSLF_TLS_VERSION_MIN_MASK
#define SSLF_TLS_VERSION_MIN_MASK
Definition: ssl_common.h:422
tls_ctx_load_cert_pem_file
static void tls_ctx_load_cert_pem_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_inline)
Definition: ssl_openssl.c:1195
key_state_ssl_init
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:2166
ecdsa_sign_setup
static int ecdsa_sign_setup(EC_KEY *ec, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
Definition: ssl_openssl.c:1625
tls_ctx_server_new
void tls_ctx_server_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context for a server.
Definition: ssl_openssl.c:104
BLEN
#define BLEN(buf)
Definition: buffer.h:127
SSL_CTX_new_ex
#define SSL_CTX_new_ex(libctx, propq, method)
Reduce SSL_CTX_new_ex() to SSL_CTX_new() for OpenSSL < 3.
Definition: openssl_compat.h:126
purge_user_pass
void purge_user_pass(struct user_pass *up, const bool force)
Definition: misc.c:485
tls_version_max
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:207
cryptoapi.h
PERF_BIO_WRITE_CIPHERTEXT
#define PERF_BIO_WRITE_CIPHERTEXT
Definition: perf.h:41
tls_ctx_use_management_external_key
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:1718
tls_ctx_load_priv_file
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:1271
ALLOC_ARRAY_CLEAR_GC
#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc)
Definition: buffer.h:1082
misc.h
unload_xkey_provider
static void unload_xkey_provider(void)
Undo steps in load_xkey_provider.
Definition: ssl_openssl.c:2722
load_pkey_from_uri
static void * load_pkey_from_uri(const char *uri, SSL_CTX *ssl_ctx)
Load private key from OSSL_STORE URI or file uri : URI of object or filename ssl_ctx : SSL_CTX for UI...
Definition: ssl_openssl.c:837
SSL_CTX_set1_groups
#define SSL_CTX_set1_groups
Definition: openssl_compat.h:51
M_WARN
#define M_WARN
Definition: error.h:91
perf_pop
static void perf_pop(void)
Definition: perf.h:82
tls_ctx_load_extra_certs
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:1947
base64.h
errlevel.h
SSLF_CLIENT_CERT_NOT_REQUIRED
#define SSLF_CLIENT_CERT_NOT_REQUIRED
Definition: ssl_common.h:415
get_user_pass
static bool get_user_pass(struct user_pass *up, const char *auth_file, const char *prefix, const unsigned int flags)
Retrieves the user credentials from various sources depending on the flags.
Definition: misc.h:150
management_query_pk_sig
char * management_query_pk_sig(struct management *man, const char *b64_data, const char *algorithm)
Definition: manage.c:3760
bio_write
static int bio_write(BIO *bio, const uint8_t *data, int size, const char *desc)
Definition: ssl_openssl.c:2055
INFO_CALLBACK_SSL_CONST
#define INFO_CALLBACK_SSL_CONST
Definition: ssl_openssl.c:180
buffer
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
print_pkey_details
static void print_pkey_details(EVP_PKEY *pkey, char *buf, size_t buflen)
Definition: ssl_openssl.c:2300
show_available_curves
void show_available_curves(void)
Show the available elliptic curves in the crypto library.
Definition: ssl_openssl.c:2606
key_state_write_plaintext
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:2227
tls_ctx_load_pkcs12
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:908
show_available_tls_ciphers_list
void show_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert_profile, bool tls13)
Show the TLS ciphers that are available for us to use in the library depending on the TLS version.
Definition: ssl_openssl.c:2531
D_TLS_ERRORS
#define D_TLS_ERRORS
Definition: errlevel.h:59
tls_ctx_load_cryptoapi
void tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
Use Windows cryptoapi for key and cert, and add to library-specific TLS context.
Definition: ssl_openssl.c:1038
TLS_VER_1_2
#define TLS_VER_1_2
Definition: ssl_backend.h:108
rsa_pub_dec
static int rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1421
tls_free_lib
void tls_free_lib(void)
Free any global SSL library-specific data structures.
Definition: ssl_openssl.c:99
openssl_compat.h
tls_session
Security parameter state of a single session within a VPN tunnel.
Definition: ssl_common.h:479
openssl_tls_version
static int openssl_tls_version(int ver)
Convert internal version number to openssl version number.
Definition: ssl_openssl.c:243
buffer.h
syshead.h
tls_ctx_initialised
bool tls_ctx_initialised(struct tls_root_ctx *ctx)
Checks whether the given TLS context is initialised.
Definition: ssl_openssl.c:149
platform_fopen
FILE * platform_fopen(const char *path, const char *mode)
Definition: platform.c:501
BPTR
#define BPTR(buf)
Definition: buffer.h:124
tls_ctx_check_cert_time
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:620
cert_uri_supported
static bool cert_uri_supported(void)
Definition: ssl_openssl.c:1085
SSLF_TLS_VERSION_MAX_SHIFT
#define SSLF_TLS_VERSION_MAX_SHIFT
Definition: ssl_common.h:423
gc_arena
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
bio_read
static int bio_read(BIO *bio, struct buffer *buf, const char *desc)
Definition: ssl_openssl.c:2117
tls_ctx_load_cert_uri
static void tls_ctx_load_cert_uri(struct tls_root_ctx *tls_ctx, const char *uri)
Definition: ssl_openssl.c:1095
rsa_priv_enc
static int rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1506
crypto_print_openssl_errors
void crypto_print_openssl_errors(const unsigned int flags)
Retrieve any occurred OpenSSL errors and print those errors.
Definition: crypto_openssl.c:236
tls_ctx_restrict_ciphers
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:430
EVP_PKEY_get_group_name
static int EVP_PKEY_get_group_name(EVP_PKEY *pkey, char *gname, size_t gname_sz, size_t *gname_len)
Definition: openssl_compat.h:91
tls_ctx_free
void tls_ctx_free(struct tls_root_ctx *ctx)
Frees the library-specific TLSv1 context.
Definition: ssl_openssl.c:140
M_DEBUG
#define M_DEBUG
Definition: error.h:92
PERF_BIO_READ_CIPHERTEXT
#define PERF_BIO_READ_CIPHERTEXT
Definition: perf.h:40
backend_tls_ctx_reload_crl
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:1326
tls_cipher_name_pair::openssl_name
const char * openssl_name
Definition: ssl_util.h:77
tls_ctx_set_tls_groups
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:560
crypto_msg
#define crypto_msg(flags,...)
Retrieve any OpenSSL errors, then print the supplied error message.
Definition: crypto_openssl.h:116
rsa_pub_enc
static int rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
Definition: ssl_openssl.c:1413
gc_malloc
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Definition: buffer.c:336
verify_callback
int verify_callback(void *session_obj, mbedtls_x509_crt *cert, int cert_depth, uint32_t *flags)
Verify that the remote OpenVPN peer's certificate allows setting up a VPN tunnel.
D_TLS_DEBUG_MED
#define D_TLS_DEBUG_MED
Definition: errlevel.h:157
tls_root_ctx
Structure that wraps the TLS context.
Definition: ssl_mbedtls.h:107
key_state_ssl_shutdown
void key_state_ssl_shutdown(struct key_state_ssl *ks_ssl)
Sets a TLS session to be shutdown state, so the TLS library will generate a shutdown alert.
Definition: ssl_openssl.c:2206
status
static SERVICE_STATUS status
Definition: interactive.c:53
SSL_CTX_use_CryptoAPI_certificate
int SSL_CTX_use_CryptoAPI_certificate(SSL_CTX *ssl_ctx, const char *cert_prop)
Definition: cryptoapi.c:59
tls_ctx_set_cert_profile
void tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
Set the TLS certificate profile.
Definition: ssl_openssl.c:521
ptr_type
unsigned long ptr_type
Definition: common.h:58
management
Definition: manage.h:335
gc_free
static void gc_free(struct gc_arena *a)
Definition: buffer.h:1033
tls_ctx_load_ecdh_params
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:717
print_server_tempkey
static void print_server_tempkey(SSL *ssl, char *buf, size_t buflen)
Definition: ssl_openssl.c:2398
GET_USER_PASS_PASSWORD_ONLY
#define GET_USER_PASS_PASSWORD_ONLY
Definition: misc.h:111
TLS_VER_1_3
#define TLS_VER_1_3
Definition: ssl_backend.h:109
strsep
char * strsep(char **stringp, const char *delim)
Definition: compat-strsep.c:36
OSSL_PROVIDER
void OSSL_PROVIDER
Definition: openssl_compat.h:131
config.h
pem_password_callback
int pem_password_callback(char *buf, int size, int rwflag, void *u)
Callback to retrieve the user's password.
Definition: ssl.c:261
ssl_common.h
tls_root_ctx::ctx
SSL_CTX * ctx
Definition: ssl_openssl.h:41
tls_libctx
OSSL_LIB_CTX * tls_libctx
Definition: ssl_openssl.c:79
format_hex
static char * format_hex(const uint8_t *data, int size, int maxoutput, struct gc_arena *gc)
Definition: buffer.h:505
bio_write_post
static void bio_write_post(const int status, struct buffer *buf)
Definition: ssl_openssl.c:2104
check_malloc_return
static void check_malloc_return(void *p)
Definition: buffer.h:1103
user_pass::password
char password[USER_PASS_LEN]
Definition: misc.h:73
session
Definition: keyingmaterialexporter.c:56
constrain_int
static int constrain_int(int x, int min, int max)
Definition: integer.h:115
buf_forward_capacity
static int buf_forward_capacity(const struct buffer *buf)
Definition: buffer.h:541
convert_tls13_list_to_openssl
static void convert_tls13_list_to_openssl(char *openssl_ciphers, size_t len, const char *ciphers)
Definition: ssl_openssl.c:465
key_state_write_plaintext_const
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:2243
user_pass
Definition: misc.h:56
tls_ctx_use_external_ec_key
static int tls_ctx_use_external_ec_key(struct tls_root_ctx *ctx, EVP_PKEY *pkey)
Definition: ssl_openssl.c:1656
memdbg.h
ALLOC_ARRAY
#define ALLOC_ARRAY(dptr, type, n)
Definition: buffer.h:1066
tls_cipher_name_pair::iana_name
const char * iana_name
Definition: ssl_util.h:77
UP_TYPE_PRIVATE_KEY
#define UP_TYPE_PRIVATE_KEY
Definition: ssl_common.h:43
msg
#define msg(flags,...)
Definition: error.h:144
openvpn_extkey_ec_finish
static void openvpn_extkey_ec_finish(EC_KEY *ec)
Definition: ssl_openssl.c:1592
OSSL_LIB_CTX
void OSSL_LIB_CTX
Definition: openssl_compat.h:130
SSLF_CLIENT_CERT_OPTIONAL
#define SSLF_CLIENT_CERT_OPTIONAL
Definition: ssl_common.h:416
perf_push
static void perf_push(int type)
Definition: perf.h:78
ptr_format
#define ptr_format
Definition: common.h:49
key_state_read_ciphertext
int key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Extract ciphertext data from the TLS module.
Definition: ssl_openssl.c:2257
ecdsa_sign_sig
static ECDSA_SIG * ecdsa_sign_sig(const unsigned char *dgst, int dgstlen, const BIGNUM *in_kinv, const BIGNUM *in_r, EC_KEY *ec)
Definition: ssl_openssl.c:1635
tls_cipher_name_pair
Get a tls_cipher_name_pair containing OpenSSL and IANA names for supplied TLS cipher name.
Definition: ssl_util.h:77
gc
struct gc_arena gc
Definition: test_ssl.c:155
cleanup
static int cleanup(void **state)
Definition: test_pkcs11.c:290