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