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