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