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-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9 *  Copyright (C) 2010 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
21 *  along with this program (see the file COPYING included with this
22 *  distribution); if not, write to the Free Software Foundation, Inc.,
23 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24 */
25
26/**
27 * @file Control Channel OpenSSL Backend
28 */
29
30#ifdef HAVE_CONFIG_H
31#include "config.h"
32#elif defined(_MSC_VER)
33#include "config-msvc.h"
34#endif
35
36#include "syshead.h"
37
38#if defined(ENABLE_SSL) && defined(ENABLE_CRYPTO_OPENSSL)
39
40#include "errlevel.h"
41#include "buffer.h"
42#include "misc.h"
43#include "manage.h"
44#include "memdbg.h"
45#include "ssl_backend.h"
46#include "ssl_common.h"
47#include "base64.h"
48
49#ifdef ENABLE_CRYPTOAPI
50#include "cryptoapi.h"
51#endif
52
53#include "ssl_verify_openssl.h"
54
55#include <openssl/err.h>
56#include <openssl/pkcs12.h>
57#include <openssl/x509.h>
58#include <openssl/crypto.h>
59
60/*
61 * Allocate space in SSL objects in which to store a struct tls_session
62 * pointer back to parent.
63 *
64 */
65
66int mydata_index; /* GLOBAL */
67
68void
69tls_init_lib()
70{
71  SSL_library_init();
72#ifndef ENABLE_SMALL
73  SSL_load_error_strings();
74#endif
75  OpenSSL_add_all_algorithms ();
76
77  mydata_index = SSL_get_ex_new_index(0, "struct session *", NULL, NULL, NULL);
78  ASSERT (mydata_index >= 0);
79}
80
81void
82tls_free_lib()
83{
84  EVP_cleanup();
85#ifndef ENABLE_SMALL
86  ERR_free_strings();
87#endif
88}
89
90void
91tls_clear_error()
92{
93  ERR_clear_error ();
94}
95
96/*
97 * OpenSSL callback to get a temporary RSA key, mostly
98 * used for export ciphers.
99 */
100static RSA *
101tmp_rsa_cb (SSL * s, int is_export, int keylength)
102{
103  static RSA *rsa_tmp = NULL;
104  if (rsa_tmp == NULL)
105    {
106      msg (D_HANDSHAKE, "Generating temp (%d bit) RSA key", keylength);
107      rsa_tmp = RSA_generate_key (keylength, RSA_F4, NULL, NULL);
108    }
109  return (rsa_tmp);
110}
111
112void
113tls_ctx_server_new(struct tls_root_ctx *ctx)
114{
115  ASSERT(NULL != ctx);
116
117  ctx->ctx = SSL_CTX_new (TLSv1_server_method ());
118
119  if (ctx->ctx == NULL)
120    msg (M_SSLERR, "SSL_CTX_new TLSv1_server_method");
121
122  SSL_CTX_set_tmp_rsa_callback (ctx->ctx, tmp_rsa_cb);
123}
124
125void
126tls_ctx_client_new(struct tls_root_ctx *ctx)
127{
128  ASSERT(NULL != ctx);
129
130  ctx->ctx = SSL_CTX_new (TLSv1_client_method ());
131
132  if (ctx->ctx == NULL)
133    msg (M_SSLERR, "SSL_CTX_new TLSv1_client_method");
134}
135
136void
137tls_ctx_free(struct tls_root_ctx *ctx)
138{
139  ASSERT(NULL != ctx);
140  if (NULL != ctx->ctx)
141    SSL_CTX_free (ctx->ctx);
142  ctx->ctx = NULL;
143}
144
145bool tls_ctx_initialised(struct tls_root_ctx *ctx)
146{
147  ASSERT(NULL != ctx);
148  return NULL != ctx->ctx;
149}
150
151/*
152 * Print debugging information on SSL/TLS session negotiation.
153 */
154
155#ifndef INFO_CALLBACK_SSL_CONST
156#define INFO_CALLBACK_SSL_CONST const
157#endif
158static void
159info_callback (INFO_CALLBACK_SSL_CONST SSL * s, int where, int ret)
160{
161  if (where & SSL_CB_LOOP)
162    {
163      dmsg (D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
164	   where & SSL_ST_CONNECT ? "connect" :
165	   where & SSL_ST_ACCEPT ? "accept" :
166	   "undefined", SSL_state_string_long (s));
167    }
168  else if (where & SSL_CB_ALERT)
169    {
170      dmsg (D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
171	   where & SSL_CB_READ ? "read" : "write",
172	   SSL_alert_type_string_long (ret),
173	   SSL_alert_desc_string_long (ret));
174    }
175}
176
177void
178tls_ctx_set_options (struct tls_root_ctx *ctx, unsigned int ssl_flags)
179{
180  ASSERT(NULL != ctx);
181
182  SSL_CTX_set_session_cache_mode (ctx->ctx, SSL_SESS_CACHE_OFF);
183  SSL_CTX_set_options (ctx->ctx, SSL_OP_SINGLE_DH_USE);
184  SSL_CTX_set_default_passwd_cb (ctx->ctx, pem_password_callback);
185
186  /* Require peer certificate verification */
187#if P2MP_SERVER
188  if (ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED)
189    {
190      msg (M_WARN, "WARNING: POTENTIALLY DANGEROUS OPTION "
191	  "--client-cert-not-required may accept clients which do not present "
192	  "a certificate");
193    }
194  else
195#endif
196  SSL_CTX_set_verify (ctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
197		      verify_callback);
198
199  SSL_CTX_set_info_callback (ctx->ctx, info_callback);
200}
201
202void
203tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
204{
205  size_t begin_of_cipher, end_of_cipher;
206
207  const char *current_cipher;
208  size_t current_cipher_len;
209
210  const tls_cipher_name_pair *cipher_pair;
211
212  const size_t openssl_ciphers_size = 4096;
213  char openssl_ciphers[openssl_ciphers_size];
214  size_t openssl_ciphers_len = 0;
215  openssl_ciphers[0] = '\0';
216
217  ASSERT(NULL != ctx);
218
219  // Translate IANA cipher suite names to OpenSSL names
220  begin_of_cipher = end_of_cipher = 0;
221  for (; begin_of_cipher < strlen(ciphers); begin_of_cipher = end_of_cipher) {
222      end_of_cipher += strcspn(&ciphers[begin_of_cipher], ":");
223      cipher_pair = tls_get_cipher_name_pair(&ciphers[begin_of_cipher], end_of_cipher - begin_of_cipher);
224
225      if (NULL == cipher_pair)
226        {
227          // No translation found, use original
228          current_cipher = &ciphers[begin_of_cipher];
229          current_cipher_len = end_of_cipher - begin_of_cipher;
230
231          // Issue warning on missing translation
232          // %.*s format specifier expects length of type int, so guarantee
233          // that length is small enough and cast to int.
234          msg (M_WARN, "No valid translation found for TLS cipher '%.*s'",
235              (int) MIN(current_cipher_len, 256), current_cipher);
236        }
237      else
238	{
239	  // Use OpenSSL name
240          current_cipher = cipher_pair->openssl_name;
241          current_cipher_len = strlen(current_cipher);
242
243	  if (end_of_cipher - begin_of_cipher == current_cipher_len &&
244	      0 == memcmp (&ciphers[begin_of_cipher], cipher_pair->openssl_name, end_of_cipher - begin_of_cipher))
245	    {
246	      // Non-IANA name used, show warning
247	      msg (M_WARN, "Deprecated TLS cipher name '%s', please use IANA name '%s'", cipher_pair->openssl_name, cipher_pair->iana_name);
248	    }
249	}
250
251      // Make sure new cipher name fits in cipher string
252      if (((openssl_ciphers_size-1) - openssl_ciphers_len) < current_cipher_len) {
253	msg(M_SSLERR, "Failed to set restricted TLS cipher list, too long (>%zu).", openssl_ciphers_size-1);
254      }
255
256      // Concatenate cipher name to OpenSSL cipher string
257      memcpy(&openssl_ciphers[openssl_ciphers_len], current_cipher, current_cipher_len);
258      openssl_ciphers_len += current_cipher_len;
259      openssl_ciphers[openssl_ciphers_len] = ':';
260      openssl_ciphers_len++;
261
262      end_of_cipher++;
263  }
264
265  if (openssl_ciphers_len > 0)
266    openssl_ciphers[openssl_ciphers_len-1] = '\0';
267
268  // Set OpenSSL cipher list
269  if(!SSL_CTX_set_cipher_list(ctx->ctx, openssl_ciphers))
270    msg(M_SSLERR, "Failed to set restricted TLS cipher list: %s", openssl_ciphers);
271}
272
273void
274tls_ctx_load_dh_params (struct tls_root_ctx *ctx, const char *dh_file,
275    const char *dh_file_inline
276    )
277{
278  DH *dh;
279  BIO *bio;
280
281  ASSERT(NULL != ctx);
282
283  if (!strcmp (dh_file, INLINE_FILE_TAG) && dh_file_inline)
284    {
285      if (!(bio = BIO_new_mem_buf ((char *)dh_file_inline, -1)))
286	msg (M_SSLDHERR, "Cannot open memory BIO for inline DH parameters");
287    }
288  else
289    {
290      /* Get Diffie Hellman Parameters */
291      if (!(bio = BIO_new_file (dh_file, "r")))
292	msg (M_SSLDHERR, "Cannot open %s for DH parameters", dh_file);
293    }
294
295  dh = PEM_read_bio_DHparams (bio, NULL, NULL, NULL);
296  BIO_free (bio);
297
298  if (!dh)
299    msg (M_SSLDHERR, "Cannot load DH parameters from %s", dh_file);
300  if (!SSL_CTX_set_tmp_dh (ctx->ctx, dh))
301    msg (M_SSLDHERR, "SSL_CTX_set_tmp_dh");
302
303  msg (D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
304       8 * DH_size (dh));
305
306  DH_free (dh);
307}
308
309int
310tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,
311    const char *pkcs12_file_inline,
312    bool load_ca_file
313    )
314{
315  FILE *fp;
316  EVP_PKEY *pkey;
317  X509 *cert;
318  STACK_OF(X509) *ca = NULL;
319  PKCS12 *p12;
320  int i;
321  char password[256];
322
323  ASSERT(NULL != ctx);
324
325  if (!strcmp (pkcs12_file, INLINE_FILE_TAG) && pkcs12_file_inline)
326    {
327      BIO *b64 = BIO_new(BIO_f_base64());
328      BIO *bio = BIO_new_mem_buf((void *) pkcs12_file_inline,
329	  (int) strlen(pkcs12_file_inline));
330      ASSERT(b64 && bio);
331      BIO_push(b64, bio);
332      p12 = d2i_PKCS12_bio(b64, NULL);
333      if (!p12)
334	msg(M_SSLERR, "Error reading inline PKCS#12 file");
335      BIO_free(b64);
336      BIO_free(bio);
337    }
338  else
339    {
340      /* Load the PKCS #12 file */
341      if (!(fp = platform_fopen(pkcs12_file, "rb")))
342	msg(M_SSLERR, "Error opening file %s", pkcs12_file);
343      p12 = d2i_PKCS12_fp(fp, NULL);
344      fclose(fp);
345      if (!p12)
346	msg(M_SSLERR, "Error reading PKCS#12 file %s", pkcs12_file);
347    }
348
349  /* Parse the PKCS #12 file */
350  if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
351   {
352     pem_password_callback (password, sizeof(password) - 1, 0, NULL);
353     /* Reparse the PKCS #12 file with password */
354     ca = NULL;
355     if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
356      {
357#ifdef ENABLE_MANAGEMENT
358	      if (management && (ERR_GET_REASON (ERR_peek_error()) == PKCS12_R_MAC_VERIFY_FAILURE))
359		management_auth_failure (management, UP_TYPE_PRIVATE_KEY, NULL);
360#endif
361	PKCS12_free(p12);
362	return 1;
363      }
364   }
365  PKCS12_free(p12);
366
367  /* Load Certificate */
368  if (!SSL_CTX_use_certificate (ctx->ctx, cert))
369   msg (M_SSLERR, "Cannot use certificate");
370
371  /* Load Private Key */
372  if (!SSL_CTX_use_PrivateKey (ctx->ctx, pkey))
373   msg (M_SSLERR, "Cannot use private key");
374  warn_if_group_others_accessible (pkcs12_file);
375
376  /* Check Private Key */
377  if (!SSL_CTX_check_private_key (ctx->ctx))
378   msg (M_SSLERR, "Private key does not match the certificate");
379
380  /* Set Certificate Verification chain */
381  if (load_ca_file)
382   {
383     if (ca && sk_X509_num(ca))
384      {
385	for (i = 0; i < sk_X509_num(ca); i++)
386	  {
387	      if (!X509_STORE_add_cert(ctx->ctx->cert_store,sk_X509_value(ca, i)))
388	      msg (M_SSLERR, "Cannot add certificate to certificate chain (X509_STORE_add_cert)");
389	    if (!SSL_CTX_add_client_CA(ctx->ctx, sk_X509_value(ca, i)))
390	      msg (M_SSLERR, "Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
391	  }
392      }
393   }
394  return 0;
395}
396
397#ifdef ENABLE_CRYPTOAPI
398void
399tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
400{
401  ASSERT(NULL != ctx);
402
403  /* Load Certificate and Private Key */
404  if (!SSL_CTX_use_CryptoAPI_certificate (ctx->ctx, cryptoapi_cert))
405    msg (M_SSLERR, "Cannot load certificate \"%s\" from Microsoft Certificate Store",
406	   cryptoapi_cert);
407}
408#endif /* WIN32 */
409
410static void
411tls_ctx_add_extra_certs (struct tls_root_ctx *ctx, BIO *bio)
412{
413  X509 *cert;
414  for (;;)
415    {
416      cert = NULL;
417      if (!PEM_read_bio_X509 (bio, &cert, 0, NULL)) /* takes ownership of cert */
418        break;
419      if (!cert)
420        msg (M_SSLERR, "Error reading extra certificate");
421      if (SSL_CTX_add_extra_chain_cert(ctx->ctx, cert) != 1)
422        msg (M_SSLERR, "Error adding extra certificate");
423    }
424}
425
426void
427tls_ctx_load_cert_file (struct tls_root_ctx *ctx, const char *cert_file,
428    const char *cert_file_inline, X509 **x509
429    )
430{
431  BIO *in = NULL;
432  X509 *x = NULL;
433  int ret = 0;
434  bool inline_file = false;
435
436  ASSERT (NULL != ctx);
437  if (NULL != x509)
438    ASSERT (NULL == *x509);
439
440  inline_file = (strcmp (cert_file, INLINE_FILE_TAG) == 0);
441
442  if (inline_file && cert_file_inline)
443    in = BIO_new_mem_buf ((char *)cert_file_inline, -1);
444  else
445    in = BIO_new_file (cert_file, "r");
446
447  if (in == NULL)
448    {
449      SSLerr (SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
450      goto end;
451    }
452
453  x = PEM_read_bio_X509 (in, NULL, ctx->ctx->default_passwd_callback,
454                         ctx->ctx->default_passwd_callback_userdata);
455  if (x == NULL)
456    {
457      SSLerr (SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_PEM_LIB);
458      goto end;
459    }
460
461  ret = SSL_CTX_use_certificate (ctx->ctx, x);
462  if (ret)
463    tls_ctx_add_extra_certs (ctx, in);
464
465end:
466  if (!ret)
467    {
468      if (inline_file)
469        msg (M_SSLERR, "Cannot load inline certificate file");
470      else
471        msg (M_SSLERR, "Cannot load certificate file %s", cert_file);
472    }
473
474  if (in != NULL)
475    BIO_free(in);
476  if (x509)
477    *x509 = x;
478  else if (x)
479    X509_free (x);
480}
481
482void
483tls_ctx_free_cert_file (X509 *x509)
484{
485  X509_free(x509);
486}
487
488int
489tls_ctx_load_priv_file (struct tls_root_ctx *ctx, const char *priv_key_file,
490    const char *priv_key_file_inline
491    )
492{
493  int status;
494  SSL_CTX *ssl_ctx = NULL;
495  BIO *in = NULL;
496  EVP_PKEY *pkey = NULL;
497  int ret = 1;
498
499  ASSERT(NULL != ctx);
500
501  ssl_ctx = ctx->ctx;
502
503  if (!strcmp (priv_key_file, INLINE_FILE_TAG) && priv_key_file_inline)
504    in = BIO_new_mem_buf ((char *)priv_key_file_inline, -1);
505  else
506    in = BIO_new_file (priv_key_file, "r");
507
508  if (!in)
509    goto end;
510
511  pkey = PEM_read_bio_PrivateKey (in, NULL,
512                                  ssl_ctx->default_passwd_callback,
513                                  ssl_ctx->default_passwd_callback_userdata);
514  if (!pkey)
515    goto end;
516
517  if (!SSL_CTX_use_PrivateKey (ssl_ctx, pkey))
518    {
519#ifdef ENABLE_MANAGEMENT
520      if (management && (ERR_GET_REASON (ERR_peek_error()) == EVP_R_BAD_DECRYPT))
521          management_auth_failure (management, UP_TYPE_PRIVATE_KEY, NULL);
522#endif
523      msg (M_WARN|M_SSL, "Cannot load private key file %s", priv_key_file);
524      goto end;
525    }
526  warn_if_group_others_accessible (priv_key_file);
527
528  /* Check Private Key */
529  if (!SSL_CTX_check_private_key (ssl_ctx))
530    msg (M_SSLERR, "Private key does not match the certificate");
531  ret = 0;
532
533end:
534  if (pkey)
535    EVP_PKEY_free (pkey);
536  if (in)
537    BIO_free (in);
538  return ret;
539}
540
541#ifdef MANAGMENT_EXTERNAL_KEY
542
543/* encrypt */
544static int
545rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
546{
547  ASSERT(0);
548  return -1;
549}
550
551/* verify arbitrary data */
552static int
553rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
554{
555  ASSERT(0);
556  return -1;
557}
558
559/* decrypt */
560static int
561rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
562{
563  ASSERT(0);
564  return -1;
565}
566
567/* called at RSA_free */
568static int
569rsa_finish(RSA *rsa)
570{
571  free ((void*)rsa->meth);
572  rsa->meth = NULL;
573  return 1;
574}
575
576/* sign arbitrary data */
577static int
578rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
579{
580  /* optional app data in rsa->meth->app_data; */
581  char *in_b64 = NULL;
582  char *out_b64 = NULL;
583  int ret = -1;
584  int len;
585
586  if (padding != RSA_PKCS1_PADDING)
587    {
588      RSAerr (RSA_F_RSA_EAY_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
589      goto done;
590    }
591
592  /* convert 'from' to base64 */
593  if (openvpn_base64_encode (from, flen, &in_b64) <= 0)
594    goto done;
595
596  /* call MI for signature */
597  if (management)
598    out_b64 = management_query_rsa_sig (management, in_b64);
599  if (!out_b64)
600    goto done;
601
602  /* decode base64 signature to binary */
603  len = RSA_size(rsa);
604  ret = openvpn_base64_decode (out_b64, to, len);
605
606  /* verify length */
607  if (ret != len)
608    ret = -1;
609
610 done:
611  if (in_b64)
612    free (in_b64);
613  if (out_b64)
614    free (out_b64);
615  return ret;
616}
617
618int
619tls_ctx_use_external_private_key (struct tls_root_ctx *ctx, X509 *cert)
620{
621  RSA *rsa = NULL;
622  RSA *pub_rsa;
623  RSA_METHOD *rsa_meth;
624
625  ASSERT (NULL != ctx);
626  ASSERT (NULL != cert);
627
628  /* allocate custom RSA method object */
629  ALLOC_OBJ_CLEAR (rsa_meth, RSA_METHOD);
630  rsa_meth->name = "OpenVPN external private key RSA Method";
631  rsa_meth->rsa_pub_enc = rsa_pub_enc;
632  rsa_meth->rsa_pub_dec = rsa_pub_dec;
633  rsa_meth->rsa_priv_enc = rsa_priv_enc;
634  rsa_meth->rsa_priv_dec = rsa_priv_dec;
635  rsa_meth->init = NULL;
636  rsa_meth->finish = rsa_finish;
637  rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
638  rsa_meth->app_data = NULL;
639
640  /* allocate RSA object */
641  rsa = RSA_new();
642  if (rsa == NULL)
643    {
644      SSLerr(SSL_F_SSL_USE_PRIVATEKEY, ERR_R_MALLOC_FAILURE);
645      goto err;
646    }
647
648  /* get the public key */
649  ASSERT(cert->cert_info->key->pkey); /* NULL before SSL_CTX_use_certificate() is called */
650  pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
651
652  /* initialize RSA object */
653  rsa->n = BN_dup(pub_rsa->n);
654  rsa->flags |= RSA_FLAG_EXT_PKEY;
655  if (!RSA_set_method(rsa, rsa_meth))
656    goto err;
657
658  /* bind our custom RSA object to ssl_ctx */
659  if (!SSL_CTX_use_RSAPrivateKey(ctx->ctx, rsa))
660    goto err;
661
662  RSA_free(rsa); /* doesn't necessarily free, just decrements refcount */
663  return 1;
664
665 err:
666  if (rsa)
667    RSA_free(rsa);
668  else
669    {
670      if (rsa_meth)
671	free(rsa_meth);
672    }
673  msg (M_SSLERR, "Cannot enable SSL external private key capability");
674  return 0;
675}
676
677#endif
678
679static int
680sk_x509_name_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
681{
682  return X509_NAME_cmp (*a, *b);
683}
684
685void
686tls_ctx_load_ca (struct tls_root_ctx *ctx, const char *ca_file,
687    const char *ca_file_inline,
688    const char *ca_path, bool tls_server
689    )
690{
691  STACK_OF(X509_INFO) *info_stack = NULL;
692  STACK_OF(X509_NAME) *cert_names = NULL;
693  X509_LOOKUP *lookup = NULL;
694  X509_STORE *store = NULL;
695  X509_NAME *xn = NULL;
696  BIO *in = NULL;
697  int i, added = 0;
698
699  ASSERT(NULL != ctx);
700
701  store = SSL_CTX_get_cert_store(ctx->ctx);
702  if (!store)
703    msg(M_SSLERR, "Cannot get certificate store (SSL_CTX_get_cert_store)");
704
705  /* Try to add certificates and CRLs from ca_file */
706  if (ca_file)
707    {
708      if (!strcmp (ca_file, INLINE_FILE_TAG) && ca_file_inline)
709        in = BIO_new_mem_buf ((char *)ca_file_inline, -1);
710      else
711        in = BIO_new_file (ca_file, "r");
712
713      if (in)
714        info_stack = PEM_X509_INFO_read_bio (in, NULL, NULL, NULL);
715
716      if (info_stack)
717        {
718          for (i = 0; i < sk_X509_INFO_num (info_stack); i++)
719            {
720              X509_INFO *info = sk_X509_INFO_value (info_stack, i);
721              if (info->crl)
722                  X509_STORE_add_crl (store, info->crl);
723
724              if (info->x509)
725                {
726                  X509_STORE_add_cert (store, info->x509);
727                  added++;
728
729                  if (!tls_server)
730                    continue;
731
732                  /* Use names of CAs as a client CA list */
733                  if (cert_names == NULL)
734                    {
735                      cert_names = sk_X509_NAME_new (sk_x509_name_cmp);
736                      if (!cert_names)
737                        continue;
738                    }
739
740                  xn = X509_get_subject_name (info->x509);
741                  if (!xn)
742                    continue;
743
744                  /* Don't add duplicate CA names */
745                  if (sk_X509_NAME_find (cert_names, xn) == -1)
746                    {
747                      xn = X509_NAME_dup (xn);
748                      if (!xn)
749                        continue;
750                      sk_X509_NAME_push (cert_names, xn);
751                    }
752                }
753            }
754          sk_X509_INFO_pop_free (info_stack, X509_INFO_free);
755        }
756
757      if (tls_server)
758        SSL_CTX_set_client_CA_list (ctx->ctx, cert_names);
759
760      if (!added || (tls_server && sk_X509_NAME_num (cert_names) != added))
761        msg (M_SSLERR, "Cannot load CA certificate file %s", np(ca_file));
762      if (in)
763        BIO_free (in);
764    }
765
766  /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
767  if (ca_path)
768    {
769      lookup = X509_STORE_add_lookup (store, X509_LOOKUP_hash_dir ());
770      if (lookup && X509_LOOKUP_add_dir (lookup, ca_path, X509_FILETYPE_PEM))
771        msg(M_WARN, "WARNING: experimental option --capath %s", ca_path);
772      else
773        msg(M_SSLERR, "Cannot add lookup at --capath %s", ca_path);
774#if OPENSSL_VERSION_NUMBER >= 0x00907000L
775      X509_STORE_set_flags (store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
776#else
777      msg(M_WARN, "WARNING: this version of OpenSSL cannot handle CRL files in capath");
778#endif
779    }
780}
781
782void
783tls_ctx_load_extra_certs (struct tls_root_ctx *ctx, const char *extra_certs_file,
784    const char *extra_certs_file_inline
785    )
786{
787  BIO *in;
788  if (!strcmp (extra_certs_file, INLINE_FILE_TAG) && extra_certs_file_inline)
789    in = BIO_new_mem_buf ((char *)extra_certs_file_inline, -1);
790  else
791    in = BIO_new_file (extra_certs_file, "r");
792
793  if (in == NULL)
794    msg (M_SSLERR, "Cannot load extra-certs file: %s", extra_certs_file);
795  else
796    tls_ctx_add_extra_certs (ctx, in);
797
798  BIO_free (in);
799}
800
801/* **************************************
802 *
803 * Key-state specific functions
804 *
805 ***************************************/
806/*
807 *
808 * BIO functions
809 *
810 */
811
812#ifdef BIO_DEBUG
813
814#warning BIO_DEBUG defined
815
816static FILE *biofp;                            /* GLOBAL */
817static bool biofp_toggle;                      /* GLOBAL */
818static time_t biofp_last_open;                 /* GLOBAL */
819static const int biofp_reopen_interval = 600;  /* GLOBAL */
820
821static void
822close_biofp()
823{
824  if (biofp)
825    {
826      ASSERT (!fclose (biofp));
827      biofp = NULL;
828    }
829}
830
831static void
832open_biofp()
833{
834  const time_t current = time (NULL);
835  const pid_t pid = getpid ();
836
837  if (biofp_last_open + biofp_reopen_interval < current)
838    close_biofp();
839  if (!biofp)
840    {
841      char fn[256];
842      openvpn_snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
843      biofp = fopen (fn, "w");
844      ASSERT (biofp);
845      biofp_last_open = time (NULL);
846      biofp_toggle ^= 1;
847    }
848}
849
850static void
851bio_debug_data (const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
852{
853  struct gc_arena gc = gc_new ();
854  if (len > 0)
855    {
856      open_biofp();
857      fprintf(biofp, "BIO_%s %s time=" time_format " bio=" ptr_format " len=%d data=%s\n",
858	      mode, desc, time (NULL), (ptr_type)bio, len, format_hex (buf, len, 0, &gc));
859      fflush (biofp);
860    }
861  gc_free (&gc);
862}
863
864static void
865bio_debug_oc (const char *mode, BIO *bio)
866{
867  open_biofp();
868  fprintf(biofp, "BIO %s time=" time_format " bio=" ptr_format "\n",
869	  mode, time (NULL), (ptr_type)bio);
870  fflush (biofp);
871}
872
873#endif
874
875/*
876 * OpenVPN's interface to SSL/TLS authentication,
877 * encryption, and decryption is exclusively
878 * through "memory BIOs".
879 */
880static BIO *
881getbio (BIO_METHOD * type, const char *desc)
882{
883  BIO *ret;
884  ret = BIO_new (type);
885  if (!ret)
886    msg (M_SSLERR, "Error creating %s BIO", desc);
887  return ret;
888}
889
890/*
891 * Write to an OpenSSL BIO in non-blocking mode.
892 */
893static int
894bio_write (BIO *bio, const uint8_t *data, int size, const char *desc)
895{
896  int i;
897  int ret = 0;
898  ASSERT (size >= 0);
899  if (size)
900    {
901      /*
902       * Free the L_TLS lock prior to calling BIO routines
903       * so that foreground thread can still call
904       * tls_pre_decrypt or tls_pre_encrypt,
905       * allowing tunnel packet forwarding to continue.
906       */
907#ifdef BIO_DEBUG
908      bio_debug_data ("write", bio, data, size, desc);
909#endif
910      i = BIO_write (bio, data, size);
911
912      if (i < 0)
913	{
914	  if (BIO_should_retry (bio))
915	    {
916	      ;
917	    }
918	  else
919	    {
920	      msg (D_TLS_ERRORS | M_SSL, "TLS ERROR: BIO write %s error",
921		   desc);
922	      ret = -1;
923	      ERR_clear_error ();
924	    }
925	}
926      else if (i != size)
927	{
928	  msg (D_TLS_ERRORS | M_SSL,
929	       "TLS ERROR: BIO write %s incomplete %d/%d", desc, i, size);
930	  ret = -1;
931	  ERR_clear_error ();
932	}
933      else
934	{			/* successful write */
935	  dmsg (D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
936	  ret = 1;
937	}
938    }
939  return ret;
940}
941
942/*
943 * Inline functions for reading from and writing
944 * to BIOs.
945 */
946
947static void
948bio_write_post (const int status, struct buffer *buf)
949{
950  if (status == 1) /* success status return from bio_write? */
951    {
952      memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
953      buf->len = 0;
954    }
955}
956
957/*
958 * Read from an OpenSSL BIO in non-blocking mode.
959 */
960static int
961bio_read (BIO *bio, struct buffer *buf, int maxlen, const char *desc)
962{
963  int i;
964  int ret = 0;
965  ASSERT (buf->len >= 0);
966  if (buf->len)
967    {
968      ;
969    }
970  else
971    {
972      int len = buf_forward_capacity (buf);
973      if (maxlen < len)
974	len = maxlen;
975
976      /*
977       * BIO_read brackets most of the serious RSA
978       * key negotiation number crunching.
979       */
980      i = BIO_read (bio, BPTR (buf), len);
981
982      VALGRIND_MAKE_READABLE ((void *) &i, sizeof (i));
983
984#ifdef BIO_DEBUG
985      bio_debug_data ("read", bio, BPTR (buf), i, desc);
986#endif
987      if (i < 0)
988	{
989	  if (BIO_should_retry (bio))
990	    {
991	      ;
992	    }
993	  else
994	    {
995	      msg (D_TLS_ERRORS | M_SSL, "TLS_ERROR: BIO read %s error",
996		   desc);
997	      buf->len = 0;
998	      ret = -1;
999	      ERR_clear_error ();
1000	    }
1001	}
1002      else if (!i)
1003	{
1004	  buf->len = 0;
1005	}
1006      else
1007	{			/* successful read */
1008	  dmsg (D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
1009	  buf->len = i;
1010	  ret = 1;
1011	  VALGRIND_MAKE_READABLE ((void *) BPTR (buf), BLEN (buf));
1012	}
1013    }
1014  return ret;
1015}
1016
1017void
1018key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, void *session)
1019{
1020  ASSERT(NULL != ssl_ctx);
1021  ASSERT(ks_ssl);
1022  CLEAR (*ks_ssl);
1023
1024  ks_ssl->ssl = SSL_new (ssl_ctx->ctx);
1025  if (!ks_ssl->ssl)
1026    msg (M_SSLERR, "SSL_new failed");
1027
1028  /* put session * in ssl object so we can access it
1029     from verify callback*/
1030  SSL_set_ex_data (ks_ssl->ssl, mydata_index, session);
1031
1032  ks_ssl->ssl_bio = getbio (BIO_f_ssl (), "ssl_bio");
1033  ks_ssl->ct_in = getbio (BIO_s_mem (), "ct_in");
1034  ks_ssl->ct_out = getbio (BIO_s_mem (), "ct_out");
1035
1036#ifdef BIO_DEBUG
1037  bio_debug_oc ("open ssl_bio", ks_ssl->ssl_bio);
1038  bio_debug_oc ("open ct_in", ks_ssl->ct_in);
1039  bio_debug_oc ("open ct_out", ks_ssl->ct_out);
1040#endif
1041
1042  if (is_server)
1043    SSL_set_accept_state (ks_ssl->ssl);
1044  else
1045    SSL_set_connect_state (ks_ssl->ssl);
1046
1047  SSL_set_bio (ks_ssl->ssl, ks_ssl->ct_in, ks_ssl->ct_out);
1048  BIO_set_ssl (ks_ssl->ssl_bio, ks_ssl->ssl, BIO_NOCLOSE);
1049}
1050
1051void key_state_ssl_free(struct key_state_ssl *ks_ssl)
1052{
1053  if (ks_ssl->ssl) {
1054#ifdef BIO_DEBUG
1055    bio_debug_oc ("close ssl_bio", ks_ssl->ssl_bio);
1056    bio_debug_oc ("close ct_in", ks_ssl->ct_in);
1057    bio_debug_oc ("close ct_out", ks_ssl->ct_out);
1058#endif
1059    BIO_free_all(ks_ssl->ssl_bio);
1060    SSL_free (ks_ssl->ssl);
1061  }
1062}
1063
1064int
1065key_state_write_plaintext (struct key_state_ssl *ks_ssl, struct buffer *buf)
1066{
1067  int ret = 0;
1068  perf_push (PERF_BIO_WRITE_PLAINTEXT);
1069
1070#ifdef ENABLE_CRYPTO_OPENSSL
1071  ASSERT (NULL != ks_ssl);
1072
1073  ret = bio_write (ks_ssl->ssl_bio, BPTR(buf), BLEN(buf),
1074      "tls_write_plaintext");
1075  bio_write_post (ret, buf);
1076#endif /* ENABLE_CRYPTO_OPENSSL */
1077
1078  perf_pop ();
1079  return ret;
1080}
1081
1082int
1083key_state_write_plaintext_const (struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
1084{
1085  int ret = 0;
1086  perf_push (PERF_BIO_WRITE_PLAINTEXT);
1087
1088  ASSERT (NULL != ks_ssl);
1089
1090  ret = bio_write (ks_ssl->ssl_bio, data, len, "tls_write_plaintext_const");
1091
1092  perf_pop ();
1093  return ret;
1094}
1095
1096int
1097key_state_read_ciphertext (struct key_state_ssl *ks_ssl, struct buffer *buf,
1098    int maxlen)
1099{
1100  int ret = 0;
1101  perf_push (PERF_BIO_READ_CIPHERTEXT);
1102
1103  ASSERT (NULL != ks_ssl);
1104
1105  ret = bio_read (ks_ssl->ct_out, buf, maxlen, "tls_read_ciphertext");
1106
1107  perf_pop ();
1108  return ret;
1109}
1110
1111int
1112key_state_write_ciphertext (struct key_state_ssl *ks_ssl, struct buffer *buf)
1113{
1114  int ret = 0;
1115  perf_push (PERF_BIO_WRITE_CIPHERTEXT);
1116
1117  ASSERT (NULL != ks_ssl);
1118
1119  ret = bio_write (ks_ssl->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
1120  bio_write_post (ret, buf);
1121
1122  perf_pop ();
1123  return ret;
1124}
1125
1126int
1127key_state_read_plaintext (struct key_state_ssl *ks_ssl, struct buffer *buf,
1128    int maxlen)
1129{
1130  int ret = 0;
1131  perf_push (PERF_BIO_READ_PLAINTEXT);
1132
1133  ASSERT (NULL != ks_ssl);
1134
1135  ret = bio_read (ks_ssl->ssl_bio, buf, maxlen, "tls_read_plaintext");
1136
1137  perf_pop ();
1138  return ret;
1139}
1140
1141/* **************************************
1142 *
1143 * Information functions
1144 *
1145 * Print information for the end user.
1146 *
1147 ***************************************/
1148void
1149print_details (struct key_state_ssl * ks_ssl, const char *prefix)
1150{
1151  const SSL_CIPHER *ciph;
1152  X509 *cert;
1153  char s1[256];
1154  char s2[256];
1155
1156  s1[0] = s2[0] = 0;
1157  ciph = SSL_get_current_cipher (ks_ssl->ssl);
1158  openvpn_snprintf (s1, sizeof (s1), "%s %s, cipher %s %s",
1159		    prefix,
1160		    SSL_get_version (ks_ssl->ssl),
1161		    SSL_CIPHER_get_version (ciph),
1162		    SSL_CIPHER_get_name (ciph));
1163  cert = SSL_get_peer_certificate (ks_ssl->ssl);
1164  if (cert != NULL)
1165    {
1166      EVP_PKEY *pkey = X509_get_pubkey (cert);
1167      if (pkey != NULL)
1168	{
1169	  if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
1170	      && pkey->pkey.rsa->n != NULL)
1171	    {
1172	      openvpn_snprintf (s2, sizeof (s2), ", %d bit RSA",
1173				BN_num_bits (pkey->pkey.rsa->n));
1174	    }
1175	  else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
1176		   && pkey->pkey.dsa->p != NULL)
1177	    {
1178	      openvpn_snprintf (s2, sizeof (s2), ", %d bit DSA",
1179				BN_num_bits (pkey->pkey.dsa->p));
1180	    }
1181	  EVP_PKEY_free (pkey);
1182	}
1183      X509_free (cert);
1184    }
1185  /* The SSL API does not allow us to look at temporary RSA/DH keys,
1186   * otherwise we should print their lengths too */
1187  msg (D_HANDSHAKE, "%s%s", s1, s2);
1188}
1189
1190void
1191show_available_tls_ciphers ()
1192{
1193  SSL_CTX *ctx;
1194  SSL *ssl;
1195  const char *cipher_name;
1196  const char *print_name;
1197  const tls_cipher_name_pair *pair;
1198  int priority = 0;
1199
1200  ctx = SSL_CTX_new (TLSv1_method ());
1201  if (!ctx)
1202    msg (M_SSLERR, "Cannot create SSL_CTX object");
1203
1204  ssl = SSL_new (ctx);
1205  if (!ssl)
1206    msg (M_SSLERR, "Cannot create SSL object");
1207
1208  printf ("Available TLS Ciphers,\n");
1209  printf ("listed in order of preference:\n\n");
1210  while ((cipher_name = SSL_get_cipher_list (ssl, priority++)))
1211    {
1212      pair = tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
1213
1214      if (NULL == pair) {
1215          // No translation found, print warning
1216	  printf ("%s (No IANA name known to OpenVPN, use OpenSSL name.)\n", cipher_name);
1217      } else {
1218	  printf ("%s\n", pair->iana_name);
1219      }
1220
1221    }
1222  printf ("\n");
1223
1224  SSL_free (ssl);
1225  SSL_CTX_free (ctx);
1226}
1227
1228void
1229get_highest_preference_tls_cipher (char *buf, int size)
1230{
1231  SSL_CTX *ctx;
1232  SSL *ssl;
1233  const char *cipher_name;
1234
1235  ctx = SSL_CTX_new (TLSv1_method ());
1236  if (!ctx)
1237    msg (M_SSLERR, "Cannot create SSL_CTX object");
1238  ssl = SSL_new (ctx);
1239  if (!ssl)
1240    msg (M_SSLERR, "Cannot create SSL object");
1241
1242  cipher_name = SSL_get_cipher_list (ssl, 0);
1243  strncpynt (buf, cipher_name, size);
1244
1245  SSL_free (ssl);
1246  SSL_CTX_free (ctx);
1247}
1248
1249#endif /* defined(ENABLE_SSL) && defined(ENABLE_CRYPTO_OPENSSL) */
1250