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