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