OpenVPN: Update to version 2.3.2. Solves TLS security bug.
[tomato.git] / release / src / router / openvpn / src / openvpn / ssl_openssl.c
blob79cc056e5f92197d111042f43a5997b8a5627648
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.
8 * Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9 * Copyright (C) 2010 Fox Crypto B.V. <openvpn@fox-it.com>
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.
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.
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
26 /**
27 * @file Control Channel OpenSSL Backend
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #elif defined(_MSC_VER)
33 #include "config-msvc.h"
34 #endif
36 #include "syshead.h"
38 #if defined(ENABLE_SSL) && defined(ENABLE_CRYPTO_OPENSSL)
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"
49 #ifdef ENABLE_CRYPTOAPI
50 #include "cryptoapi.h"
51 #endif
53 #include "ssl_verify_openssl.h"
55 #include <openssl/err.h>
56 #include <openssl/pkcs12.h>
57 #include <openssl/x509.h>
58 #include <openssl/crypto.h>
61 * Allocate space in SSL objects in which to store a struct tls_session
62 * pointer back to parent.
66 int mydata_index; /* GLOBAL */
68 void
69 tls_init_lib()
71 SSL_library_init();
72 #ifndef ENABLE_SMALL
73 SSL_load_error_strings();
74 #endif
75 OpenSSL_add_all_algorithms ();
77 mydata_index = SSL_get_ex_new_index(0, "struct session *", NULL, NULL, NULL);
78 ASSERT (mydata_index >= 0);
81 void
82 tls_free_lib()
84 EVP_cleanup();
85 #ifndef ENABLE_SMALL
86 ERR_free_strings();
87 #endif
90 void
91 tls_clear_error()
93 ERR_clear_error ();
97 * OpenSSL callback to get a temporary RSA key, mostly
98 * used for export ciphers.
100 static RSA *
101 tmp_rsa_cb (SSL * s, int is_export, int keylength)
103 static RSA *rsa_tmp = NULL;
104 if (rsa_tmp == NULL)
106 msg (D_HANDSHAKE, "Generating temp (%d bit) RSA key", keylength);
107 rsa_tmp = RSA_generate_key (keylength, RSA_F4, NULL, NULL);
109 return (rsa_tmp);
112 void
113 tls_ctx_server_new(struct tls_root_ctx *ctx)
115 ASSERT(NULL != ctx);
117 ctx->ctx = SSL_CTX_new (TLSv1_server_method ());
119 if (ctx->ctx == NULL)
120 msg (M_SSLERR, "SSL_CTX_new TLSv1_server_method");
122 SSL_CTX_set_tmp_rsa_callback (ctx->ctx, tmp_rsa_cb);
125 void
126 tls_ctx_client_new(struct tls_root_ctx *ctx)
128 ASSERT(NULL != ctx);
130 ctx->ctx = SSL_CTX_new (TLSv1_client_method ());
132 if (ctx->ctx == NULL)
133 msg (M_SSLERR, "SSL_CTX_new TLSv1_client_method");
136 void
137 tls_ctx_free(struct tls_root_ctx *ctx)
139 ASSERT(NULL != ctx);
140 if (NULL != ctx->ctx)
141 SSL_CTX_free (ctx->ctx);
142 ctx->ctx = NULL;
145 bool tls_ctx_initialised(struct tls_root_ctx *ctx)
147 ASSERT(NULL != ctx);
148 return NULL != ctx->ctx;
152 * Print debugging information on SSL/TLS session negotiation.
155 #ifndef INFO_CALLBACK_SSL_CONST
156 #define INFO_CALLBACK_SSL_CONST const
157 #endif
158 static void
159 info_callback (INFO_CALLBACK_SSL_CONST SSL * s, int where, int ret)
161 if (where & SSL_CB_LOOP)
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));
168 else if (where & SSL_CB_ALERT)
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));
177 void
178 tls_ctx_set_options (struct tls_root_ctx *ctx, unsigned int ssl_flags)
180 ASSERT(NULL != ctx);
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);
186 /* Require peer certificate verification */
187 #if P2MP_SERVER
188 if (ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED)
190 msg (M_WARN, "WARNING: POTENTIALLY DANGEROUS OPTION "
191 "--client-cert-not-required may accept clients which do not present "
192 "a certificate");
194 else
195 #endif
196 SSL_CTX_set_verify (ctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
197 verify_callback);
199 SSL_CTX_set_info_callback (ctx->ctx, info_callback);
202 void
203 tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
205 size_t begin_of_cipher, end_of_cipher;
207 const char *current_cipher;
208 size_t current_cipher_len;
210 const tls_cipher_name_pair *cipher_pair;
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';
217 ASSERT(NULL != ctx);
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);
225 if (NULL == cipher_pair)
227 // No translation found, use original
228 current_cipher = &ciphers[begin_of_cipher];
229 current_cipher_len = end_of_cipher - begin_of_cipher;
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);
237 else
239 // Use OpenSSL name
240 current_cipher = cipher_pair->openssl_name;
241 current_cipher_len = strlen(current_cipher);
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))
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);
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);
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++;
262 end_of_cipher++;
265 if (openssl_ciphers_len > 0)
266 openssl_ciphers[openssl_ciphers_len-1] = '\0';
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);
273 void
274 tls_ctx_load_dh_params (struct tls_root_ctx *ctx, const char *dh_file,
275 const char *dh_file_inline
278 DH *dh;
279 BIO *bio;
281 ASSERT(NULL != ctx);
283 if (!strcmp (dh_file, INLINE_FILE_TAG) && dh_file_inline)
285 if (!(bio = BIO_new_mem_buf ((char *)dh_file_inline, -1)))
286 msg (M_SSLERR, "Cannot open memory BIO for inline DH parameters");
288 else
290 /* Get Diffie Hellman Parameters */
291 if (!(bio = BIO_new_file (dh_file, "r")))
292 msg (M_SSLERR, "Cannot open %s for DH parameters", dh_file);
295 dh = PEM_read_bio_DHparams (bio, NULL, NULL, NULL);
296 BIO_free (bio);
298 if (!dh)
299 msg (M_SSLERR, "Cannot load DH parameters from %s", dh_file);
300 if (!SSL_CTX_set_tmp_dh (ctx->ctx, dh))
301 msg (M_SSLERR, "SSL_CTX_set_tmp_dh");
303 msg (D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
304 8 * DH_size (dh));
306 DH_free (dh);
310 tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file,
311 const char *pkcs12_file_inline,
312 bool load_ca_file
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];
323 ASSERT(NULL != ctx);
325 if (!strcmp (pkcs12_file, INLINE_FILE_TAG) && pkcs12_file_inline)
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);
338 else
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);
349 /* Parse the PKCS #12 file */
350 if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
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))
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;
365 PKCS12_free(p12);
367 /* Load Certificate */
368 if (!SSL_CTX_use_certificate (ctx->ctx, cert))
369 msg (M_SSLERR, "Cannot use certificate");
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);
376 /* Check Private Key */
377 if (!SSL_CTX_check_private_key (ctx->ctx))
378 msg (M_SSLERR, "Private key does not match the certificate");
380 /* Set Certificate Verification chain */
381 if (load_ca_file)
383 if (ca && sk_X509_num(ca))
385 for (i = 0; i < sk_X509_num(ca); i++)
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)");
394 return 0;
397 #ifdef ENABLE_CRYPTOAPI
398 void
399 tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
401 ASSERT(NULL != ctx);
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);
408 #endif /* WIN32 */
410 static void
411 tls_ctx_add_extra_certs (struct tls_root_ctx *ctx, BIO *bio)
413 X509 *cert;
414 for (;;)
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");
426 void
427 tls_ctx_load_cert_file (struct tls_root_ctx *ctx, const char *cert_file,
428 const char *cert_file_inline, X509 **x509
431 BIO *in = NULL;
432 X509 *x = NULL;
433 int ret = 0;
434 bool inline_file = false;
436 ASSERT (NULL != ctx);
437 if (NULL != x509)
438 ASSERT (NULL == *x509);
440 inline_file = (strcmp (cert_file, INLINE_FILE_TAG) == 0);
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");
447 if (in == NULL)
449 SSLerr (SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_SYS_LIB);
450 goto end;
453 x = PEM_read_bio_X509 (in, NULL, ctx->ctx->default_passwd_callback,
454 ctx->ctx->default_passwd_callback_userdata);
455 if (x == NULL)
457 SSLerr (SSL_F_SSL_CTX_USE_CERTIFICATE_FILE, ERR_R_PEM_LIB);
458 goto end;
461 ret = SSL_CTX_use_certificate (ctx->ctx, x);
462 if (ret)
463 tls_ctx_add_extra_certs (ctx, in);
465 end:
466 if (!ret)
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);
474 if (in != NULL)
475 BIO_free(in);
476 if (x509)
477 *x509 = x;
478 else if (x)
479 X509_free (x);
482 void
483 tls_ctx_free_cert_file (X509 *x509)
485 X509_free(x509);
489 tls_ctx_load_priv_file (struct tls_root_ctx *ctx, const char *priv_key_file,
490 const char *priv_key_file_inline
493 int status;
494 SSL_CTX *ssl_ctx = NULL;
495 BIO *in = NULL;
496 EVP_PKEY *pkey = NULL;
497 int ret = 1;
499 ASSERT(NULL != ctx);
501 ssl_ctx = ctx->ctx;
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");
508 if (!in)
509 goto end;
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;
517 if (!SSL_CTX_use_PrivateKey (ssl_ctx, pkey))
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;
526 warn_if_group_others_accessible (priv_key_file);
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;
533 end:
534 if (pkey)
535 EVP_PKEY_free (pkey);
536 if (in)
537 BIO_free (in);
538 return ret;
541 #ifdef MANAGMENT_EXTERNAL_KEY
543 /* encrypt */
544 static int
545 rsa_pub_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
547 ASSERT(0);
548 return -1;
551 /* verify arbitrary data */
552 static int
553 rsa_pub_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
555 ASSERT(0);
556 return -1;
559 /* decrypt */
560 static int
561 rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
563 ASSERT(0);
564 return -1;
567 /* called at RSA_free */
568 static int
569 rsa_finish(RSA *rsa)
571 free ((void*)rsa->meth);
572 rsa->meth = NULL;
573 return 1;
576 /* sign arbitrary data */
577 static int
578 rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
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;
586 if (padding != RSA_PKCS1_PADDING)
588 RSAerr (RSA_F_RSA_EAY_PRIVATE_ENCRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
589 goto done;
592 /* convert 'from' to base64 */
593 if (openvpn_base64_encode (from, flen, &in_b64) <= 0)
594 goto done;
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;
602 /* decode base64 signature to binary */
603 len = RSA_size(rsa);
604 ret = openvpn_base64_decode (out_b64, to, len);
606 /* verify length */
607 if (ret != len)
608 ret = -1;
610 done:
611 if (in_b64)
612 free (in_b64);
613 if (out_b64)
614 free (out_b64);
615 return ret;
619 tls_ctx_use_external_private_key (struct tls_root_ctx *ctx, X509 *cert)
621 RSA *rsa = NULL;
622 RSA *pub_rsa;
623 RSA_METHOD *rsa_meth;
625 ASSERT (NULL != ctx);
626 ASSERT (NULL != cert);
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;
640 /* allocate RSA object */
641 rsa = RSA_new();
642 if (rsa == NULL)
644 SSLerr(SSL_F_SSL_USE_PRIVATEKEY, ERR_R_MALLOC_FAILURE);
645 goto err;
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;
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;
658 /* bind our custom RSA object to ssl_ctx */
659 if (!SSL_CTX_use_RSAPrivateKey(ctx->ctx, rsa))
660 goto err;
662 RSA_free(rsa); /* doesn't necessarily free, just decrements refcount */
663 return 1;
665 err:
666 if (rsa)
667 RSA_free(rsa);
668 else
670 if (rsa_meth)
671 free(rsa_meth);
673 msg (M_SSLERR, "Cannot enable SSL external private key capability");
674 return 0;
677 #endif
679 static int
680 sk_x509_name_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
682 return X509_NAME_cmp (*a, *b);
685 void
686 tls_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
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;
699 ASSERT(NULL != ctx);
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)");
705 /* Try to add certificates and CRLs from ca_file */
706 if (ca_file)
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");
713 if (in)
714 info_stack = PEM_X509_INFO_read_bio (in, NULL, NULL, NULL);
716 if (info_stack)
718 for (i = 0; i < sk_X509_INFO_num (info_stack); i++)
720 X509_INFO *info = sk_X509_INFO_value (info_stack, i);
721 if (info->crl)
722 X509_STORE_add_crl (store, info->crl);
724 if (info->x509)
726 X509_STORE_add_cert (store, info->x509);
727 added++;
729 if (!tls_server)
730 continue;
732 /* Use names of CAs as a client CA list */
733 if (cert_names == NULL)
735 cert_names = sk_X509_NAME_new (sk_x509_name_cmp);
736 if (!cert_names)
737 continue;
740 xn = X509_get_subject_name (info->x509);
741 if (!xn)
742 continue;
744 /* Don't add duplicate CA names */
745 if (sk_X509_NAME_find (cert_names, xn) == -1)
747 xn = X509_NAME_dup (xn);
748 if (!xn)
749 continue;
750 sk_X509_NAME_push (cert_names, xn);
754 sk_X509_INFO_pop_free (info_stack, X509_INFO_free);
757 if (tls_server)
758 SSL_CTX_set_client_CA_list (ctx->ctx, cert_names);
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);
766 /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
767 if (ca_path)
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
782 void
783 tls_ctx_load_extra_certs (struct tls_root_ctx *ctx, const char *extra_certs_file,
784 const char *extra_certs_file_inline
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");
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);
798 BIO_free (in);
801 /* **************************************
803 * Key-state specific functions
805 ***************************************/
808 * BIO functions
812 #ifdef BIO_DEBUG
814 #warning BIO_DEBUG defined
816 static FILE *biofp; /* GLOBAL */
817 static bool biofp_toggle; /* GLOBAL */
818 static time_t biofp_last_open; /* GLOBAL */
819 static const int biofp_reopen_interval = 600; /* GLOBAL */
821 static void
822 close_biofp()
824 if (biofp)
826 ASSERT (!fclose (biofp));
827 biofp = NULL;
831 static void
832 open_biofp()
834 const time_t current = time (NULL);
835 const pid_t pid = getpid ();
837 if (biofp_last_open + biofp_reopen_interval < current)
838 close_biofp();
839 if (!biofp)
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;
850 static void
851 bio_debug_data (const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
853 struct gc_arena gc = gc_new ();
854 if (len > 0)
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);
861 gc_free (&gc);
864 static void
865 bio_debug_oc (const char *mode, BIO *bio)
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);
873 #endif
876 * OpenVPN's interface to SSL/TLS authentication,
877 * encryption, and decryption is exclusively
878 * through "memory BIOs".
880 static BIO *
881 getbio (BIO_METHOD * type, const char *desc)
883 BIO *ret;
884 ret = BIO_new (type);
885 if (!ret)
886 msg (M_SSLERR, "Error creating %s BIO", desc);
887 return ret;
891 * Write to an OpenSSL BIO in non-blocking mode.
893 static int
894 bio_write (BIO *bio, const uint8_t *data, int size, const char *desc)
896 int i;
897 int ret = 0;
898 ASSERT (size >= 0);
899 if (size)
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.
907 #ifdef BIO_DEBUG
908 bio_debug_data ("write", bio, data, size, desc);
909 #endif
910 i = BIO_write (bio, data, size);
912 if (i < 0)
914 if (BIO_should_retry (bio))
918 else
920 msg (D_TLS_ERRORS | M_SSL, "TLS ERROR: BIO write %s error",
921 desc);
922 ret = -1;
923 ERR_clear_error ();
926 else if (i != size)
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 ();
933 else
934 { /* successful write */
935 dmsg (D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
936 ret = 1;
939 return ret;
943 * Inline functions for reading from and writing
944 * to BIOs.
947 static void
948 bio_write_post (const int status, struct buffer *buf)
950 if (status == 1) /* success status return from bio_write? */
952 memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
953 buf->len = 0;
958 * Read from an OpenSSL BIO in non-blocking mode.
960 static int
961 bio_read (BIO *bio, struct buffer *buf, int maxlen, const char *desc)
963 int i;
964 int ret = 0;
965 ASSERT (buf->len >= 0);
966 if (buf->len)
970 else
972 int len = buf_forward_capacity (buf);
973 if (maxlen < len)
974 len = maxlen;
977 * BIO_read brackets most of the serious RSA
978 * key negotiation number crunching.
980 i = BIO_read (bio, BPTR (buf), len);
982 VALGRIND_MAKE_READABLE ((void *) &i, sizeof (i));
984 #ifdef BIO_DEBUG
985 bio_debug_data ("read", bio, BPTR (buf), i, desc);
986 #endif
987 if (i < 0)
989 if (BIO_should_retry (bio))
993 else
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 ();
1002 else if (!i)
1004 buf->len = 0;
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));
1014 return ret;
1017 void
1018 key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, void *session)
1020 ASSERT(NULL != ssl_ctx);
1021 ASSERT(ks_ssl);
1022 CLEAR (*ks_ssl);
1024 ks_ssl->ssl = SSL_new (ssl_ctx->ctx);
1025 if (!ks_ssl->ssl)
1026 msg (M_SSLERR, "SSL_new failed");
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);
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");
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
1042 if (is_server)
1043 SSL_set_accept_state (ks_ssl->ssl);
1044 else
1045 SSL_set_connect_state (ks_ssl->ssl);
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);
1051 void key_state_ssl_free(struct key_state_ssl *ks_ssl)
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);
1065 key_state_write_plaintext (struct key_state_ssl *ks_ssl, struct buffer *buf)
1067 int ret = 0;
1068 perf_push (PERF_BIO_WRITE_PLAINTEXT);
1070 #ifdef ENABLE_CRYPTO_OPENSSL
1071 ASSERT (NULL != ks_ssl);
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 */
1078 perf_pop ();
1079 return ret;
1083 key_state_write_plaintext_const (struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
1085 int ret = 0;
1086 perf_push (PERF_BIO_WRITE_PLAINTEXT);
1088 ASSERT (NULL != ks_ssl);
1090 ret = bio_write (ks_ssl->ssl_bio, data, len, "tls_write_plaintext_const");
1092 perf_pop ();
1093 return ret;
1097 key_state_read_ciphertext (struct key_state_ssl *ks_ssl, struct buffer *buf,
1098 int maxlen)
1100 int ret = 0;
1101 perf_push (PERF_BIO_READ_CIPHERTEXT);
1103 ASSERT (NULL != ks_ssl);
1105 ret = bio_read (ks_ssl->ct_out, buf, maxlen, "tls_read_ciphertext");
1107 perf_pop ();
1108 return ret;
1112 key_state_write_ciphertext (struct key_state_ssl *ks_ssl, struct buffer *buf)
1114 int ret = 0;
1115 perf_push (PERF_BIO_WRITE_CIPHERTEXT);
1117 ASSERT (NULL != ks_ssl);
1119 ret = bio_write (ks_ssl->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
1120 bio_write_post (ret, buf);
1122 perf_pop ();
1123 return ret;
1127 key_state_read_plaintext (struct key_state_ssl *ks_ssl, struct buffer *buf,
1128 int maxlen)
1130 int ret = 0;
1131 perf_push (PERF_BIO_READ_PLAINTEXT);
1133 ASSERT (NULL != ks_ssl);
1135 ret = bio_read (ks_ssl->ssl_bio, buf, maxlen, "tls_read_plaintext");
1137 perf_pop ();
1138 return ret;
1141 /* **************************************
1143 * Information functions
1145 * Print information for the end user.
1147 ***************************************/
1148 void
1149 print_details (struct key_state_ssl * ks_ssl, const char *prefix)
1151 const SSL_CIPHER *ciph;
1152 X509 *cert;
1153 char s1[256];
1154 char s2[256];
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)
1166 EVP_PKEY *pkey = X509_get_pubkey (cert);
1167 if (pkey != NULL)
1169 if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
1170 && pkey->pkey.rsa->n != NULL)
1172 openvpn_snprintf (s2, sizeof (s2), ", %d bit RSA",
1173 BN_num_bits (pkey->pkey.rsa->n));
1175 else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
1176 && pkey->pkey.dsa->p != NULL)
1178 openvpn_snprintf (s2, sizeof (s2), ", %d bit DSA",
1179 BN_num_bits (pkey->pkey.dsa->p));
1181 EVP_PKEY_free (pkey);
1183 X509_free (cert);
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);
1190 void
1191 show_available_tls_ciphers ()
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;
1200 ctx = SSL_CTX_new (TLSv1_method ());
1201 if (!ctx)
1202 msg (M_SSLERR, "Cannot create SSL_CTX object");
1204 ssl = SSL_new (ctx);
1205 if (!ssl)
1206 msg (M_SSLERR, "Cannot create SSL object");
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++)))
1212 pair = tls_get_cipher_name_pair(cipher_name, strlen(cipher_name));
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);
1222 printf ("\n");
1224 SSL_free (ssl);
1225 SSL_CTX_free (ctx);
1228 void
1229 get_highest_preference_tls_cipher (char *buf, int size)
1231 SSL_CTX *ctx;
1232 SSL *ssl;
1233 const char *cipher_name;
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");
1242 cipher_name = SSL_get_cipher_list (ssl, 0);
1243 strncpynt (buf, cipher_name, size);
1245 SSL_free (ssl);
1246 SSL_CTX_free (ctx);
1249 #endif /* defined(ENABLE_SSL) && defined(ENABLE_CRYPTO_OPENSSL) */