2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2013, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
11 #ifndef CONFIG_SMARTCARD
12 #ifndef OPENSSL_NO_ENGINE
14 #define OPENSSL_NO_ENGINE
19 #include <openssl/ssl.h>
20 #include <openssl/err.h>
21 #include <openssl/pkcs12.h>
22 #include <openssl/x509v3.h>
23 #ifndef OPENSSL_NO_ENGINE
24 #include <openssl/engine.h>
25 #endif /* OPENSSL_NO_ENGINE */
31 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
32 #define OPENSSL_d2i_TYPE const unsigned char **
34 #define OPENSSL_d2i_TYPE unsigned char **
37 #if defined(SSL_CTX_get_app_data) && defined(SSL_CTX_set_app_data)
38 #define OPENSSL_SUPPORTS_CTX_APP_DATA
41 #if OPENSSL_VERSION_NUMBER < 0x10000000L
42 /* ERR_remove_thread_state replaces ERR_remove_state and the latter is
43 * deprecated. However, OpenSSL 0.9.8 doesn't include
44 * ERR_remove_thread_state. */
45 #define ERR_remove_thread_state(tid) ERR_remove_state(0)
48 #if defined(OPENSSL_IS_BORINGSSL)
49 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
50 typedef size_t stack_index_t;
52 typedef int stack_index_t;
55 #ifdef SSL_set_tlsext_status_type
56 #ifndef OPENSSL_NO_TLSEXT
58 #include <openssl/ocsp.h>
59 #endif /* OPENSSL_NO_TLSEXT */
60 #endif /* SSL_set_tlsext_status_type */
63 #include <openssl/pem.h>
64 #include <keystore/keystore_get.h>
66 static BIO * BIO_from_keystore(const char *key)
69 uint8_t *value = NULL;
70 int length = keystore_get(key, strlen(key), &value);
71 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
72 BIO_write(bio, value, length);
78 static int tls_openssl_ref_count = 0;
81 void (*event_cb)(void *ctx, enum tls_event ev,
82 union tls_event_data *data);
85 char *ocsp_stapling_response;
88 static struct tls_context *tls_global = NULL;
91 struct tls_connection {
92 struct tls_context *context;
94 BIO *ssl_in, *ssl_out;
95 #ifndef OPENSSL_NO_ENGINE
96 ENGINE *engine; /* functional reference to the engine */
97 EVP_PKEY *private_key; /* the private key if using engine */
98 #endif /* OPENSSL_NO_ENGINE */
99 char *subject_match, *altsubject_match, *suffix_match;
100 int read_alerts, write_alerts, failed;
102 tls_session_ticket_cb session_ticket_cb;
103 void *session_ticket_cb_ctx;
105 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
107 size_t session_ticket_len;
109 unsigned int ca_cert_verify:1;
110 unsigned int cert_probe:1;
111 unsigned int server_cert_only:1;
112 unsigned int invalid_hb_used:1;
114 u8 srv_cert_hash[32];
120 X509 *peer_issuer_issuer;
124 static struct tls_context * tls_context_new(const struct tls_config *conf)
126 struct tls_context *context = os_zalloc(sizeof(*context));
130 context->event_cb = conf->event_cb;
131 context->cb_ctx = conf->cb_ctx;
132 context->cert_in_cb = conf->cert_in_cb;
138 #ifdef CONFIG_NO_STDOUT_DEBUG
140 static void _tls_show_errors(void)
144 while ((err = ERR_get_error())) {
145 /* Just ignore the errors, since stdout is disabled */
148 #define tls_show_errors(l, f, t) _tls_show_errors()
150 #else /* CONFIG_NO_STDOUT_DEBUG */
152 static void tls_show_errors(int level, const char *func, const char *txt)
156 wpa_printf(level, "OpenSSL: %s - %s %s",
157 func, txt, ERR_error_string(ERR_get_error(), NULL));
159 while ((err = ERR_get_error())) {
160 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
161 ERR_error_string(err, NULL));
165 #endif /* CONFIG_NO_STDOUT_DEBUG */
168 #ifdef CONFIG_NATIVE_WINDOWS
170 /* Windows CryptoAPI and access to certificate stores */
171 #include <wincrypt.h>
173 #ifdef __MINGW32_VERSION
175 * MinGW does not yet include all the needed definitions for CryptoAPI, so
176 * define here whatever extra is needed.
178 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
179 #define CERT_STORE_READONLY_FLAG 0x00008000
180 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
182 #endif /* __MINGW32_VERSION */
185 struct cryptoapi_rsa_data {
186 const CERT_CONTEXT *cert;
187 HCRYPTPROV crypt_prov;
189 BOOL free_crypt_prov;
193 static void cryptoapi_error(const char *msg)
195 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
196 msg, (unsigned int) GetLastError());
200 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
201 unsigned char *to, RSA *rsa, int padding)
203 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
208 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
209 unsigned char *to, RSA *rsa, int padding)
211 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
216 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
217 unsigned char *to, RSA *rsa, int padding)
219 struct cryptoapi_rsa_data *priv =
220 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
222 DWORD hash_size, len, i;
223 unsigned char *buf = NULL;
227 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
228 ERR_R_PASSED_NULL_PARAMETER);
232 if (padding != RSA_PKCS1_PADDING) {
233 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
234 RSA_R_UNKNOWN_PADDING_TYPE);
238 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
239 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
241 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
242 RSA_R_INVALID_MESSAGE_LENGTH);
246 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
248 cryptoapi_error("CryptCreateHash failed");
252 len = sizeof(hash_size);
253 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
255 cryptoapi_error("CryptGetHashParam failed");
259 if ((int) hash_size != flen) {
260 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
261 (unsigned) hash_size, flen);
262 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
263 RSA_R_INVALID_MESSAGE_LENGTH);
266 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
267 cryptoapi_error("CryptSetHashParam failed");
272 buf = os_malloc(len);
274 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
278 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
279 cryptoapi_error("CryptSignHash failed");
283 for (i = 0; i < len; i++)
284 to[i] = buf[len - i - 1];
289 CryptDestroyHash(hash);
295 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
296 unsigned char *to, RSA *rsa, int padding)
298 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
303 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
307 if (priv->crypt_prov && priv->free_crypt_prov)
308 CryptReleaseContext(priv->crypt_prov, 0);
310 CertFreeCertificateContext(priv->cert);
315 static int cryptoapi_finish(RSA *rsa)
317 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
318 os_free((void *) rsa->meth);
324 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
327 const CERT_CONTEXT *ret = NULL;
329 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
330 store | CERT_STORE_OPEN_EXISTING_FLAG |
331 CERT_STORE_READONLY_FLAG, L"MY");
333 cryptoapi_error("Failed to open 'My system store'");
337 if (strncmp(name, "cert://", 7) == 0) {
338 unsigned short wbuf[255];
339 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
340 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
342 0, CERT_FIND_SUBJECT_STR,
344 } else if (strncmp(name, "hash://", 7) == 0) {
345 CRYPT_HASH_BLOB blob;
347 const char *hash = name + 7;
350 len = os_strlen(hash) / 2;
351 buf = os_malloc(len);
352 if (buf && hexstr2bin(hash, buf, len) == 0) {
355 ret = CertFindCertificateInStore(cs,
364 CertCloseStore(cs, 0);
370 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
373 RSA *rsa = NULL, *pub_rsa;
374 struct cryptoapi_rsa_data *priv;
375 RSA_METHOD *rsa_meth;
378 (strncmp(name, "cert://", 7) != 0 &&
379 strncmp(name, "hash://", 7) != 0))
382 priv = os_zalloc(sizeof(*priv));
383 rsa_meth = os_zalloc(sizeof(*rsa_meth));
384 if (priv == NULL || rsa_meth == NULL) {
385 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
386 "for CryptoAPI RSA method");
392 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
393 if (priv->cert == NULL) {
394 priv->cert = cryptoapi_find_cert(
395 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
397 if (priv->cert == NULL) {
398 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
403 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
404 priv->cert->cbCertEncoded);
406 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
411 if (!CryptAcquireCertificatePrivateKey(priv->cert,
412 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
413 NULL, &priv->crypt_prov,
415 &priv->free_crypt_prov)) {
416 cryptoapi_error("Failed to acquire a private key for the "
421 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
422 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
423 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
424 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
425 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
426 rsa_meth->finish = cryptoapi_finish;
427 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
428 rsa_meth->app_data = (char *) priv;
432 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
433 ERR_R_MALLOC_FAILURE);
437 if (!SSL_use_certificate(ssl, cert)) {
442 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
446 rsa->n = BN_dup(pub_rsa->n);
447 rsa->e = BN_dup(pub_rsa->e);
448 if (!RSA_set_method(rsa, rsa_meth))
451 if (!SSL_use_RSAPrivateKey(ssl, rsa))
464 cryptoapi_free_data(priv);
470 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
473 PCCERT_CONTEXT ctx = NULL;
481 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
486 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
489 wsprintf(wstore, L"%S", store);
490 cs = CertOpenSystemStore(0, wstore);
493 cs = CertOpenSystemStore(0, store);
496 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
497 "'%s': error=%d", __func__, store,
498 (int) GetLastError());
502 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
503 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
506 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
507 "X509 DER encoding for CA cert");
511 X509_NAME_oneline(X509_get_subject_name(cert), buf,
513 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
514 "system certificate store: subject='%s'", buf);
516 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
517 tls_show_errors(MSG_WARNING, __func__,
518 "Failed to add ca_cert to OpenSSL "
519 "certificate store");
525 if (!CertCloseStore(cs, 0)) {
526 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
527 "'%s': error=%d", __func__, name + 13,
528 (int) GetLastError());
535 #else /* CONFIG_NATIVE_WINDOWS */
537 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
542 #endif /* CONFIG_NATIVE_WINDOWS */
545 static void ssl_info_cb(const SSL *ssl, int where, int ret)
550 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
551 w = where & ~SSL_ST_MASK;
552 if (w & SSL_ST_CONNECT)
554 else if (w & SSL_ST_ACCEPT)
559 if (where & SSL_CB_LOOP) {
560 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
561 str, SSL_state_string_long(ssl));
562 } else if (where & SSL_CB_ALERT) {
563 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
564 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
565 where & SSL_CB_READ ?
566 "read (remote end reported an error)" :
567 "write (local SSL3 detected an error)",
568 SSL_alert_type_string_long(ret),
569 SSL_alert_desc_string_long(ret));
570 if ((ret >> 8) == SSL3_AL_FATAL) {
571 if (where & SSL_CB_READ)
574 conn->write_alerts++;
576 if (conn->context->event_cb != NULL) {
577 union tls_event_data ev;
578 struct tls_context *context = conn->context;
579 os_memset(&ev, 0, sizeof(ev));
580 ev.alert.is_local = !(where & SSL_CB_READ);
581 ev.alert.type = SSL_alert_type_string_long(ret);
582 ev.alert.description = SSL_alert_desc_string_long(ret);
583 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
585 } else if (where & SSL_CB_EXIT && ret <= 0) {
586 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
587 str, ret == 0 ? "failed" : "error",
588 SSL_state_string_long(ssl));
593 #ifndef OPENSSL_NO_ENGINE
595 * tls_engine_load_dynamic_generic - load any openssl engine
596 * @pre: an array of commands and values that load an engine initialized
597 * in the engine specific function
598 * @post: an array of commands and values that initialize an already loaded
599 * engine (or %NULL if not required)
600 * @id: the engine id of the engine to load (only required if post is not %NULL
602 * This function is a generic function that loads any openssl engine.
604 * Returns: 0 on success, -1 on failure
606 static int tls_engine_load_dynamic_generic(const char *pre[],
607 const char *post[], const char *id)
610 const char *dynamic_id = "dynamic";
612 engine = ENGINE_by_id(id);
615 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
621 engine = ENGINE_by_id(dynamic_id);
622 if (engine == NULL) {
623 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
625 ERR_error_string(ERR_get_error(), NULL));
629 /* Perform the pre commands. This will load the engine. */
630 while (pre && pre[0]) {
631 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
632 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
633 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
634 "%s %s [%s]", pre[0], pre[1],
635 ERR_error_string(ERR_get_error(), NULL));
643 * Free the reference to the "dynamic" engine. The loaded engine can
644 * now be looked up using ENGINE_by_id().
648 engine = ENGINE_by_id(id);
649 if (engine == NULL) {
650 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
651 id, ERR_error_string(ERR_get_error(), NULL));
655 while (post && post[0]) {
656 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
657 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
658 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
659 " %s %s [%s]", post[0], post[1],
660 ERR_error_string(ERR_get_error(), NULL));
661 ENGINE_remove(engine);
674 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
675 * @pkcs11_so_path: pksc11_so_path from the configuration
676 * @pcks11_module_path: pkcs11_module_path from the configuration
678 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
679 const char *pkcs11_module_path)
681 char *engine_id = "pkcs11";
682 const char *pre_cmd[] = {
683 "SO_PATH", NULL /* pkcs11_so_path */,
684 "ID", NULL /* engine_id */,
686 /* "NO_VCHECK", "1", */
690 const char *post_cmd[] = {
691 "MODULE_PATH", NULL /* pkcs11_module_path */,
698 pre_cmd[1] = pkcs11_so_path;
699 pre_cmd[3] = engine_id;
700 if (pkcs11_module_path)
701 post_cmd[1] = pkcs11_module_path;
705 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
708 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
713 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
714 * @opensc_so_path: opensc_so_path from the configuration
716 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
718 char *engine_id = "opensc";
719 const char *pre_cmd[] = {
720 "SO_PATH", NULL /* opensc_so_path */,
721 "ID", NULL /* engine_id */,
730 pre_cmd[1] = opensc_so_path;
731 pre_cmd[3] = engine_id;
733 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
736 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
738 #endif /* OPENSSL_NO_ENGINE */
741 void * tls_init(const struct tls_config *conf)
744 struct tls_context *context;
747 if (tls_openssl_ref_count == 0) {
748 tls_global = context = tls_context_new(conf);
753 if (conf && conf->fips_mode) {
754 if (!FIPS_mode_set(1)) {
755 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
757 ERR_load_crypto_strings();
758 ERR_print_errors_fp(stderr);
763 wpa_printf(MSG_INFO, "Running in FIPS mode");
765 #else /* OPENSSL_FIPS */
766 if (conf && conf->fips_mode) {
767 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
773 #endif /* OPENSSL_FIPS */
774 #endif /* CONFIG_FIPS */
775 SSL_load_error_strings();
777 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
778 EVP_add_digest(EVP_sha256());
779 #endif /* OPENSSL_NO_SHA256 */
780 /* TODO: if /dev/urandom is available, PRNG is seeded
781 * automatically. If this is not the case, random data should
785 #ifndef OPENSSL_NO_RC2
787 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
788 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
789 * versions, but it looks like OpenSSL 1.0.0 does not do that
792 EVP_add_cipher(EVP_rc2_40_cbc());
793 #endif /* OPENSSL_NO_RC2 */
795 #endif /* PKCS12_FUNCS */
797 #ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
798 /* Newer OpenSSL can store app-data per-SSL */
799 context = tls_context_new(conf);
802 #else /* OPENSSL_SUPPORTS_CTX_APP_DATA */
803 context = tls_global;
804 #endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
806 tls_openssl_ref_count++;
808 ssl = SSL_CTX_new(SSLv23_method());
810 tls_openssl_ref_count--;
811 #ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
812 if (context != tls_global)
814 #endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
815 if (tls_openssl_ref_count == 0) {
822 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
823 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
825 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
826 #ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
827 SSL_CTX_set_app_data(ssl, context);
828 #endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
830 #ifndef OPENSSL_NO_ENGINE
831 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
832 ERR_load_ENGINE_strings();
833 ENGINE_load_dynamic();
836 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
837 conf->pkcs11_module_path)) {
838 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
839 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
840 conf->pkcs11_module_path)) {
845 #endif /* OPENSSL_NO_ENGINE */
847 if (conf && conf->openssl_ciphers)
848 ciphers = conf->openssl_ciphers;
850 ciphers = "DEFAULT:!EXP:!LOW";
851 if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
852 wpa_printf(MSG_ERROR,
853 "OpenSSL: Failed to set cipher string '%s'",
863 void tls_deinit(void *ssl_ctx)
865 SSL_CTX *ssl = ssl_ctx;
866 #ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
867 struct tls_context *context = SSL_CTX_get_app_data(ssl);
868 if (context != tls_global)
870 #endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
873 tls_openssl_ref_count--;
874 if (tls_openssl_ref_count == 0) {
875 #ifndef OPENSSL_NO_ENGINE
877 #endif /* OPENSSL_NO_ENGINE */
878 CRYPTO_cleanup_all_ex_data();
879 ERR_remove_thread_state(NULL);
882 os_free(tls_global->ocsp_stapling_response);
883 tls_global->ocsp_stapling_response = NULL;
890 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
891 const char *pin, const char *key_id,
892 const char *cert_id, const char *ca_cert_id)
894 #ifndef OPENSSL_NO_ENGINE
896 if (engine_id == NULL) {
897 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
903 ENGINE_load_dynamic();
905 conn->engine = ENGINE_by_id(engine_id);
907 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
908 engine_id, ERR_error_string(ERR_get_error(), NULL));
911 if (ENGINE_init(conn->engine) != 1) {
912 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
913 "(engine: %s) [%s]", engine_id,
914 ERR_error_string(ERR_get_error(), NULL));
917 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
920 if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
921 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
922 ERR_error_string(ERR_get_error(), NULL));
928 * Ensure that the ENGINE does not attempt to use the OpenSSL
929 * UI system to obtain a PIN, if we didn't provide one.
932 const void *password;
933 const char *prompt_info;
934 } key_cb = { "", NULL };
936 /* load private key first in-case PIN is required for cert */
937 conn->private_key = ENGINE_load_private_key(conn->engine,
940 if (!conn->private_key) {
941 wpa_printf(MSG_ERROR,
942 "ENGINE: cannot load private key with id '%s' [%s]",
944 ERR_error_string(ERR_get_error(), NULL));
945 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
950 /* handle a certificate and/or CA certificate */
951 if (cert_id || ca_cert_id) {
952 const char *cmd_name = "LOAD_CERT_CTRL";
954 /* test if the engine supports a LOAD_CERT_CTRL */
955 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
956 0, (void *)cmd_name, NULL)) {
957 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
958 " loading certificates");
959 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
968 ENGINE_free(conn->engine);
972 if (conn->private_key) {
973 EVP_PKEY_free(conn->private_key);
974 conn->private_key = NULL;
978 #else /* OPENSSL_NO_ENGINE */
980 #endif /* OPENSSL_NO_ENGINE */
984 static void tls_engine_deinit(struct tls_connection *conn)
986 #ifndef OPENSSL_NO_ENGINE
987 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
988 if (conn->private_key) {
989 EVP_PKEY_free(conn->private_key);
990 conn->private_key = NULL;
993 ENGINE_finish(conn->engine);
996 #endif /* OPENSSL_NO_ENGINE */
1000 int tls_get_errors(void *ssl_ctx)
1005 while ((err = ERR_get_error())) {
1006 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1007 ERR_error_string(err, NULL));
1015 static void tls_msg_cb(int write_p, int version, int content_type,
1016 const void *buf, size_t len, SSL *ssl, void *arg)
1018 struct tls_connection *conn = arg;
1019 const u8 *pos = buf;
1021 wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
1022 write_p ? "TX" : "RX", version, content_type);
1023 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1024 if (content_type == 24 && len >= 3 && pos[0] == 1) {
1025 size_t payload_len = WPA_GET_BE16(pos + 1);
1026 if (payload_len + 3 > len) {
1027 wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1028 conn->invalid_hb_used = 1;
1034 struct tls_connection * tls_connection_init(void *ssl_ctx)
1036 SSL_CTX *ssl = ssl_ctx;
1037 struct tls_connection *conn;
1039 #ifdef OPENSSL_SUPPORTS_CTX_APP_DATA
1040 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1041 #else /* OPENSSL_SUPPORTS_CTX_APP_DATA */
1042 struct tls_context *context = tls_global;
1043 #endif /* OPENSSL_SUPPORTS_CTX_APP_DATA */
1045 conn = os_zalloc(sizeof(*conn));
1048 conn->ssl = SSL_new(ssl);
1049 if (conn->ssl == NULL) {
1050 tls_show_errors(MSG_INFO, __func__,
1051 "Failed to initialize new SSL connection");
1056 conn->context = context;
1057 SSL_set_app_data(conn->ssl, conn);
1058 SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1059 SSL_set_msg_callback_arg(conn->ssl, conn);
1060 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1061 SSL_OP_SINGLE_DH_USE;
1062 #ifdef SSL_OP_NO_COMPRESSION
1063 options |= SSL_OP_NO_COMPRESSION;
1064 #endif /* SSL_OP_NO_COMPRESSION */
1065 SSL_set_options(conn->ssl, options);
1067 conn->ssl_in = BIO_new(BIO_s_mem());
1068 if (!conn->ssl_in) {
1069 tls_show_errors(MSG_INFO, __func__,
1070 "Failed to create a new BIO for ssl_in");
1071 SSL_free(conn->ssl);
1076 conn->ssl_out = BIO_new(BIO_s_mem());
1077 if (!conn->ssl_out) {
1078 tls_show_errors(MSG_INFO, __func__,
1079 "Failed to create a new BIO for ssl_out");
1080 SSL_free(conn->ssl);
1081 BIO_free(conn->ssl_in);
1086 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1092 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1096 SSL_free(conn->ssl);
1097 tls_engine_deinit(conn);
1098 os_free(conn->subject_match);
1099 os_free(conn->altsubject_match);
1100 os_free(conn->suffix_match);
1101 os_free(conn->session_ticket);
1106 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1108 return conn ? SSL_is_init_finished(conn->ssl) : 0;
1112 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1117 /* Shutdown previous TLS connection without notifying the peer
1118 * because the connection was already terminated in practice
1119 * and "close notify" shutdown alert would confuse AS. */
1120 SSL_set_quiet_shutdown(conn->ssl, 1);
1121 SSL_shutdown(conn->ssl);
1126 static int tls_match_altsubject_component(X509 *cert, int type,
1127 const char *value, size_t len)
1134 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1136 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1137 gen = sk_GENERAL_NAME_value(ext, i);
1138 if (gen->type != type)
1140 if (os_strlen((char *) gen->d.ia5->data) == len &&
1141 os_memcmp(value, gen->d.ia5->data, len) == 0)
1149 static int tls_match_altsubject(X509 *cert, const char *match)
1152 const char *pos, *end;
1157 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1160 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1163 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1167 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1171 end = os_strchr(pos, ';');
1173 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1174 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1175 os_strncmp(end + 1, "URI:", 4) == 0)
1177 end = os_strchr(end + 1, ';');
1182 len = os_strlen(pos);
1183 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1192 #ifndef CONFIG_NATIVE_WINDOWS
1193 static int domain_suffix_match(const u8 *val, size_t len, const char *match)
1195 size_t i, match_len;
1197 /* Check for embedded nuls that could mess up suffix matching */
1198 for (i = 0; i < len; i++) {
1199 if (val[i] == '\0') {
1200 wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1205 match_len = os_strlen(match);
1206 if (match_len > len)
1209 if (os_strncasecmp((const char *) val + len - match_len, match,
1211 return 0; /* no match */
1213 if (match_len == len)
1214 return 1; /* exact match */
1216 if (val[len - match_len - 1] == '.')
1217 return 1; /* full label match completes suffix match */
1219 wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1222 #endif /* CONFIG_NATIVE_WINDOWS */
1225 static int tls_match_suffix(X509 *cert, const char *match)
1227 #ifdef CONFIG_NATIVE_WINDOWS
1228 /* wincrypt.h has conflicting X509_NAME definition */
1230 #else /* CONFIG_NATIVE_WINDOWS */
1238 wpa_printf(MSG_DEBUG, "TLS: Match domain against suffix %s", match);
1240 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1242 for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1243 gen = sk_GENERAL_NAME_value(ext, j);
1244 if (gen->type != GEN_DNS)
1247 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1248 gen->d.dNSName->data,
1249 gen->d.dNSName->length);
1250 if (domain_suffix_match(gen->d.dNSName->data,
1251 gen->d.dNSName->length, match) == 1) {
1252 wpa_printf(MSG_DEBUG, "TLS: Suffix match in dNSName found");
1258 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1262 name = X509_get_subject_name(cert);
1268 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1271 e = X509_NAME_get_entry(name, i);
1274 cn = X509_NAME_ENTRY_get_data(e);
1277 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1278 cn->data, cn->length);
1279 if (domain_suffix_match(cn->data, cn->length, match) == 1) {
1280 wpa_printf(MSG_DEBUG, "TLS: Suffix match in commonName found");
1285 wpa_printf(MSG_DEBUG, "TLS: No CommonName suffix match found");
1287 #endif /* CONFIG_NATIVE_WINDOWS */
1291 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1294 case X509_V_ERR_CERT_REVOKED:
1295 return TLS_FAIL_REVOKED;
1296 case X509_V_ERR_CERT_NOT_YET_VALID:
1297 case X509_V_ERR_CRL_NOT_YET_VALID:
1298 return TLS_FAIL_NOT_YET_VALID;
1299 case X509_V_ERR_CERT_HAS_EXPIRED:
1300 case X509_V_ERR_CRL_HAS_EXPIRED:
1301 return TLS_FAIL_EXPIRED;
1302 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1303 case X509_V_ERR_UNABLE_TO_GET_CRL:
1304 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1305 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1306 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1307 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1308 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1309 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1310 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1311 case X509_V_ERR_INVALID_CA:
1312 return TLS_FAIL_UNTRUSTED;
1313 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1314 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1315 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1316 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1317 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1318 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1319 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1320 case X509_V_ERR_CERT_UNTRUSTED:
1321 case X509_V_ERR_CERT_REJECTED:
1322 return TLS_FAIL_BAD_CERTIFICATE;
1324 return TLS_FAIL_UNSPECIFIED;
1329 static struct wpabuf * get_x509_cert(X509 *cert)
1334 int cert_len = i2d_X509(cert, NULL);
1338 buf = wpabuf_alloc(cert_len);
1342 tmp = wpabuf_put(buf, cert_len);
1343 i2d_X509(cert, &tmp);
1348 static void openssl_tls_fail_event(struct tls_connection *conn,
1349 X509 *err_cert, int err, int depth,
1350 const char *subject, const char *err_str,
1351 enum tls_fail_reason reason)
1353 union tls_event_data ev;
1354 struct wpabuf *cert = NULL;
1355 struct tls_context *context = conn->context;
1357 if (context->event_cb == NULL)
1360 cert = get_x509_cert(err_cert);
1361 os_memset(&ev, 0, sizeof(ev));
1362 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1363 reason : openssl_tls_fail_reason(err);
1364 ev.cert_fail.depth = depth;
1365 ev.cert_fail.subject = subject;
1366 ev.cert_fail.reason_txt = err_str;
1367 ev.cert_fail.cert = cert;
1368 context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1373 static void openssl_tls_cert_event(struct tls_connection *conn,
1374 X509 *err_cert, int depth,
1375 const char *subject)
1377 struct wpabuf *cert = NULL;
1378 union tls_event_data ev;
1379 struct tls_context *context = conn->context;
1380 char *altsubject[TLS_MAX_ALT_SUBJECT];
1381 int alt, num_altsubject = 0;
1385 #ifdef CONFIG_SHA256
1387 #endif /* CONFIG_SHA256 */
1389 if (context->event_cb == NULL)
1392 os_memset(&ev, 0, sizeof(ev));
1393 if (conn->cert_probe || context->cert_in_cb) {
1394 cert = get_x509_cert(err_cert);
1395 ev.peer_cert.cert = cert;
1397 #ifdef CONFIG_SHA256
1401 addr[0] = wpabuf_head(cert);
1402 len[0] = wpabuf_len(cert);
1403 if (sha256_vector(1, addr, len, hash) == 0) {
1404 ev.peer_cert.hash = hash;
1405 ev.peer_cert.hash_len = sizeof(hash);
1408 #endif /* CONFIG_SHA256 */
1409 ev.peer_cert.depth = depth;
1410 ev.peer_cert.subject = subject;
1412 ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1413 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1416 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1418 gen = sk_GENERAL_NAME_value(ext, i);
1419 if (gen->type != GEN_EMAIL &&
1420 gen->type != GEN_DNS &&
1421 gen->type != GEN_URI)
1424 pos = os_malloc(10 + gen->d.ia5->length + 1);
1427 altsubject[num_altsubject++] = pos;
1429 switch (gen->type) {
1431 os_memcpy(pos, "EMAIL:", 6);
1435 os_memcpy(pos, "DNS:", 4);
1439 os_memcpy(pos, "URI:", 4);
1444 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1445 pos += gen->d.ia5->length;
1449 for (alt = 0; alt < num_altsubject; alt++)
1450 ev.peer_cert.altsubject[alt] = altsubject[alt];
1451 ev.peer_cert.num_altsubject = num_altsubject;
1453 context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1455 for (alt = 0; alt < num_altsubject; alt++)
1456 os_free(altsubject[alt]);
1460 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1466 struct tls_connection *conn;
1467 struct tls_context *context;
1468 char *match, *altmatch, *suffix_match;
1469 const char *err_str;
1471 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1475 err = X509_STORE_CTX_get_error(x509_ctx);
1476 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1477 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1478 SSL_get_ex_data_X509_STORE_CTX_idx());
1479 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1481 conn = SSL_get_app_data(ssl);
1486 conn->peer_cert = err_cert;
1487 else if (depth == 1)
1488 conn->peer_issuer = err_cert;
1489 else if (depth == 2)
1490 conn->peer_issuer_issuer = err_cert;
1492 context = conn->context;
1493 match = conn->subject_match;
1494 altmatch = conn->altsubject_match;
1495 suffix_match = conn->suffix_match;
1497 if (!preverify_ok && !conn->ca_cert_verify)
1499 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1501 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1502 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1503 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1504 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1509 err_str = X509_verify_cert_error_string(err);
1511 #ifdef CONFIG_SHA256
1512 if (preverify_ok && depth == 0 && conn->server_cert_only) {
1513 struct wpabuf *cert;
1514 cert = get_x509_cert(err_cert);
1516 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1517 "server certificate data");
1523 addr[0] = wpabuf_head(cert);
1524 len[0] = wpabuf_len(cert);
1525 if (sha256_vector(1, addr, len, hash) < 0 ||
1526 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1527 err_str = "Server certificate mismatch";
1528 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1534 #endif /* CONFIG_SHA256 */
1536 if (!preverify_ok) {
1537 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1538 " error %d (%s) depth %d for '%s'", err, err_str,
1540 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1541 err_str, TLS_FAIL_UNSPECIFIED);
1542 return preverify_ok;
1545 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1546 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1547 preverify_ok, err, err_str,
1548 conn->ca_cert_verify, depth, buf);
1549 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1550 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1551 "match with '%s'", buf, match);
1553 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1555 TLS_FAIL_SUBJECT_MISMATCH);
1556 } else if (depth == 0 && altmatch &&
1557 !tls_match_altsubject(err_cert, altmatch)) {
1558 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1559 "'%s' not found", altmatch);
1561 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1562 "AltSubject mismatch",
1563 TLS_FAIL_ALTSUBJECT_MISMATCH);
1564 } else if (depth == 0 && suffix_match &&
1565 !tls_match_suffix(err_cert, suffix_match)) {
1566 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
1569 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1570 "Domain suffix mismatch",
1571 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1573 openssl_tls_cert_event(conn, err_cert, depth, buf);
1575 if (conn->cert_probe && preverify_ok && depth == 0) {
1576 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1577 "on probe-only run");
1579 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1580 "Server certificate chain probe",
1581 TLS_FAIL_SERVER_CHAIN_PROBE);
1584 if (preverify_ok && context->event_cb != NULL)
1585 context->event_cb(context->cb_ctx,
1586 TLS_CERT_CHAIN_SUCCESS, NULL);
1588 return preverify_ok;
1592 #ifndef OPENSSL_NO_STDIO
1593 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1595 SSL_CTX *ssl_ctx = _ssl_ctx;
1596 X509_LOOKUP *lookup;
1599 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1600 X509_LOOKUP_file());
1601 if (lookup == NULL) {
1602 tls_show_errors(MSG_WARNING, __func__,
1603 "Failed add lookup for X509 store");
1607 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1608 unsigned long err = ERR_peek_error();
1609 tls_show_errors(MSG_WARNING, __func__,
1610 "Failed load CA in DER format");
1611 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1612 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1613 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1614 "cert already in hash table error",
1622 #endif /* OPENSSL_NO_STDIO */
1625 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1626 const char *ca_cert, const u8 *ca_cert_blob,
1627 size_t ca_cert_blob_len, const char *ca_path)
1629 SSL_CTX *ssl_ctx = _ssl_ctx;
1632 * Remove previously configured trusted CA certificates before adding
1635 X509_STORE_free(ssl_ctx->cert_store);
1636 ssl_ctx->cert_store = X509_STORE_new();
1637 if (ssl_ctx->cert_store == NULL) {
1638 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1639 "certificate store", __func__);
1643 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1644 conn->ca_cert_verify = 1;
1646 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1647 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1649 conn->cert_probe = 1;
1650 conn->ca_cert_verify = 0;
1654 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1655 #ifdef CONFIG_SHA256
1656 const char *pos = ca_cert + 7;
1657 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1658 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1659 "hash value '%s'", ca_cert);
1663 if (os_strlen(pos) != 32 * 2) {
1664 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1665 "hash length in ca_cert '%s'", ca_cert);
1668 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1669 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1670 "value in ca_cert '%s'", ca_cert);
1673 conn->server_cert_only = 1;
1674 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1675 "certificate match");
1677 #else /* CONFIG_SHA256 */
1678 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1679 "cannot validate server certificate hash");
1681 #endif /* CONFIG_SHA256 */
1685 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1688 tls_show_errors(MSG_WARNING, __func__,
1689 "Failed to parse ca_cert_blob");
1693 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1694 unsigned long err = ERR_peek_error();
1695 tls_show_errors(MSG_WARNING, __func__,
1696 "Failed to add ca_cert_blob to "
1697 "certificate store");
1698 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1699 ERR_GET_REASON(err) ==
1700 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1701 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1702 "cert already in hash table error",
1710 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1711 "to certificate store", __func__);
1716 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1717 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1718 STACK_OF(X509_INFO) *stack = NULL;
1722 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1728 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1729 X509_INFO *info = sk_X509_INFO_value(stack, i);
1731 X509_STORE_add_cert(ssl_ctx->cert_store,
1735 X509_STORE_add_crl(ssl_ctx->cert_store,
1739 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1740 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1743 #endif /* ANDROID */
1745 #ifdef CONFIG_NATIVE_WINDOWS
1746 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1748 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1749 "system certificate store");
1752 #endif /* CONFIG_NATIVE_WINDOWS */
1754 if (ca_cert || ca_path) {
1755 #ifndef OPENSSL_NO_STDIO
1756 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1758 tls_show_errors(MSG_WARNING, __func__,
1759 "Failed to load root certificates");
1761 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1762 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1763 "DER format CA certificate",
1768 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1769 "certificate(s) loaded");
1770 tls_get_errors(ssl_ctx);
1772 #else /* OPENSSL_NO_STDIO */
1773 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1776 #endif /* OPENSSL_NO_STDIO */
1778 /* No ca_cert configured - do not try to verify server
1780 conn->ca_cert_verify = 0;
1787 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1790 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1792 tls_show_errors(MSG_WARNING, __func__,
1793 "Failed to load root certificates");
1797 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1798 "certificate(s) loaded");
1800 #ifndef OPENSSL_NO_STDIO
1801 /* Add the same CAs to the client certificate requests */
1802 SSL_CTX_set_client_CA_list(ssl_ctx,
1803 SSL_load_client_CA_file(ca_cert));
1804 #endif /* OPENSSL_NO_STDIO */
1811 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1816 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1818 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1819 "certificate store when enabling "
1823 flags = X509_V_FLAG_CRL_CHECK;
1825 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1826 X509_STORE_set_flags(cs, flags);
1832 static int tls_connection_set_subject_match(struct tls_connection *conn,
1833 const char *subject_match,
1834 const char *altsubject_match,
1835 const char *suffix_match)
1837 os_free(conn->subject_match);
1838 conn->subject_match = NULL;
1839 if (subject_match) {
1840 conn->subject_match = os_strdup(subject_match);
1841 if (conn->subject_match == NULL)
1845 os_free(conn->altsubject_match);
1846 conn->altsubject_match = NULL;
1847 if (altsubject_match) {
1848 conn->altsubject_match = os_strdup(altsubject_match);
1849 if (conn->altsubject_match == NULL)
1853 os_free(conn->suffix_match);
1854 conn->suffix_match = NULL;
1856 conn->suffix_match = os_strdup(suffix_match);
1857 if (conn->suffix_match == NULL)
1865 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1868 static int counter = 0;
1874 conn->ca_cert_verify = 1;
1875 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1876 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1877 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1879 conn->ca_cert_verify = 0;
1880 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1883 SSL_set_accept_state(conn->ssl);
1886 * Set session id context in order to avoid fatal errors when client
1887 * tries to resume a session. However, set the context to a unique
1888 * value in order to effectively disable session resumption for now
1889 * since not all areas of the server code are ready for it (e.g.,
1890 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1894 SSL_set_session_id_context(conn->ssl,
1895 (const unsigned char *) &counter,
1902 static int tls_connection_client_cert(struct tls_connection *conn,
1903 const char *client_cert,
1904 const u8 *client_cert_blob,
1905 size_t client_cert_blob_len)
1907 if (client_cert == NULL && client_cert_blob == NULL)
1910 if (client_cert_blob &&
1911 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1912 client_cert_blob_len) == 1) {
1913 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1916 } else if (client_cert_blob) {
1917 tls_show_errors(MSG_DEBUG, __func__,
1918 "SSL_use_certificate_ASN1 failed");
1921 if (client_cert == NULL)
1925 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1926 BIO *bio = BIO_from_keystore(&client_cert[11]);
1930 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1934 if (SSL_use_certificate(conn->ssl, x509) == 1)
1940 #endif /* ANDROID */
1942 #ifndef OPENSSL_NO_STDIO
1943 if (SSL_use_certificate_file(conn->ssl, client_cert,
1944 SSL_FILETYPE_ASN1) == 1) {
1945 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1950 if (SSL_use_certificate_file(conn->ssl, client_cert,
1951 SSL_FILETYPE_PEM) == 1) {
1953 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1958 tls_show_errors(MSG_DEBUG, __func__,
1959 "SSL_use_certificate_file failed");
1960 #else /* OPENSSL_NO_STDIO */
1961 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1962 #endif /* OPENSSL_NO_STDIO */
1968 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1970 #ifndef OPENSSL_NO_STDIO
1971 if (client_cert == NULL)
1974 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1975 SSL_FILETYPE_ASN1) != 1 &&
1976 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
1977 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1978 SSL_FILETYPE_PEM) != 1) {
1979 tls_show_errors(MSG_INFO, __func__,
1980 "Failed to load client certificate");
1984 #else /* OPENSSL_NO_STDIO */
1985 if (client_cert == NULL)
1987 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1989 #endif /* OPENSSL_NO_STDIO */
1993 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1995 if (password == NULL) {
1998 os_strlcpy(buf, (char *) password, size);
1999 return os_strlen(buf);
2004 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
2009 STACK_OF(X509) *certs;
2016 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2017 tls_show_errors(MSG_DEBUG, __func__,
2018 "Failed to parse PKCS12 file");
2022 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2025 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2027 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2028 "subject='%s'", buf);
2030 if (SSL_use_certificate(ssl, cert) != 1)
2033 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
2040 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2042 if (SSL_use_PrivateKey(ssl, pkey) != 1)
2045 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
2048 EVP_PKEY_free(pkey);
2052 while ((cert = sk_X509_pop(certs)) != NULL) {
2053 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2055 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2056 " from PKCS12: subject='%s'", buf);
2058 * There is no SSL equivalent for the chain cert - so
2059 * always add it to the context...
2061 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
2066 sk_X509_free(certs);
2072 tls_get_errors(ssl_ctx);
2076 #endif /* PKCS12_FUNCS */
2079 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
2086 f = fopen(private_key, "rb");
2090 p12 = d2i_PKCS12_fp(f, NULL);
2094 tls_show_errors(MSG_INFO, __func__,
2095 "Failed to use PKCS#12 file");
2099 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2101 #else /* PKCS12_FUNCS */
2102 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2105 #endif /* PKCS12_FUNCS */
2109 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
2110 const u8 *blob, size_t len, const char *passwd)
2115 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
2117 tls_show_errors(MSG_INFO, __func__,
2118 "Failed to use PKCS#12 blob");
2122 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2124 #else /* PKCS12_FUNCS */
2125 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2128 #endif /* PKCS12_FUNCS */
2132 #ifndef OPENSSL_NO_ENGINE
2133 static int tls_engine_get_cert(struct tls_connection *conn,
2134 const char *cert_id,
2137 /* this runs after the private key is loaded so no PIN is required */
2139 const char *cert_id;
2142 params.cert_id = cert_id;
2145 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2146 0, ¶ms, NULL, 1)) {
2147 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2148 " '%s' [%s]", cert_id,
2149 ERR_error_string(ERR_get_error(), NULL));
2150 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2153 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2155 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2157 *cert = params.cert;
2160 #endif /* OPENSSL_NO_ENGINE */
2163 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2164 const char *cert_id)
2166 #ifndef OPENSSL_NO_ENGINE
2169 if (tls_engine_get_cert(conn, cert_id, &cert))
2172 if (!SSL_use_certificate(conn->ssl, cert)) {
2173 tls_show_errors(MSG_ERROR, __func__,
2174 "SSL_use_certificate failed");
2179 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2183 #else /* OPENSSL_NO_ENGINE */
2185 #endif /* OPENSSL_NO_ENGINE */
2189 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
2190 struct tls_connection *conn,
2191 const char *ca_cert_id)
2193 #ifndef OPENSSL_NO_ENGINE
2195 SSL_CTX *ssl_ctx = _ssl_ctx;
2197 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2200 /* start off the same as tls_connection_ca_cert */
2201 X509_STORE_free(ssl_ctx->cert_store);
2202 ssl_ctx->cert_store = X509_STORE_new();
2203 if (ssl_ctx->cert_store == NULL) {
2204 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2205 "certificate store", __func__);
2209 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
2210 unsigned long err = ERR_peek_error();
2211 tls_show_errors(MSG_WARNING, __func__,
2212 "Failed to add CA certificate from engine "
2213 "to certificate store");
2214 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2215 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2216 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2217 " already in hash table error",
2225 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2226 "to certificate store", __func__);
2227 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2228 conn->ca_cert_verify = 1;
2232 #else /* OPENSSL_NO_ENGINE */
2234 #endif /* OPENSSL_NO_ENGINE */
2238 static int tls_connection_engine_private_key(struct tls_connection *conn)
2240 #ifndef OPENSSL_NO_ENGINE
2241 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2242 tls_show_errors(MSG_ERROR, __func__,
2243 "ENGINE: cannot use private key for TLS");
2246 if (!SSL_check_private_key(conn->ssl)) {
2247 tls_show_errors(MSG_INFO, __func__,
2248 "Private key failed verification");
2252 #else /* OPENSSL_NO_ENGINE */
2253 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2254 "engine support was not compiled in");
2256 #endif /* OPENSSL_NO_ENGINE */
2260 static int tls_connection_private_key(void *_ssl_ctx,
2261 struct tls_connection *conn,
2262 const char *private_key,
2263 const char *private_key_passwd,
2264 const u8 *private_key_blob,
2265 size_t private_key_blob_len)
2267 SSL_CTX *ssl_ctx = _ssl_ctx;
2271 if (private_key == NULL && private_key_blob == NULL)
2274 if (private_key_passwd) {
2275 passwd = os_strdup(private_key_passwd);
2281 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2282 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2285 while (private_key_blob) {
2286 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2287 (u8 *) private_key_blob,
2288 private_key_blob_len) == 1) {
2289 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2290 "ASN1(EVP_PKEY_RSA) --> OK");
2295 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2296 (u8 *) private_key_blob,
2297 private_key_blob_len) == 1) {
2298 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2299 "ASN1(EVP_PKEY_DSA) --> OK");
2304 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2305 (u8 *) private_key_blob,
2306 private_key_blob_len) == 1) {
2307 wpa_printf(MSG_DEBUG, "OpenSSL: "
2308 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2313 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2314 private_key_blob_len, passwd) == 0) {
2315 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2324 while (!ok && private_key) {
2325 #ifndef OPENSSL_NO_STDIO
2326 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2327 SSL_FILETYPE_ASN1) == 1) {
2328 wpa_printf(MSG_DEBUG, "OpenSSL: "
2329 "SSL_use_PrivateKey_File (DER) --> OK");
2334 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2335 SSL_FILETYPE_PEM) == 1) {
2336 wpa_printf(MSG_DEBUG, "OpenSSL: "
2337 "SSL_use_PrivateKey_File (PEM) --> OK");
2341 #else /* OPENSSL_NO_STDIO */
2342 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2344 #endif /* OPENSSL_NO_STDIO */
2346 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2348 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2354 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2355 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2356 "access certificate store --> OK");
2365 tls_show_errors(MSG_INFO, __func__,
2366 "Failed to load private key");
2371 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2374 if (!SSL_check_private_key(conn->ssl)) {
2375 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2380 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2385 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2386 const char *private_key_passwd)
2390 if (private_key == NULL)
2393 if (private_key_passwd) {
2394 passwd = os_strdup(private_key_passwd);
2400 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2401 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2403 #ifndef OPENSSL_NO_STDIO
2404 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2405 SSL_FILETYPE_ASN1) != 1 &&
2406 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2407 SSL_FILETYPE_PEM) != 1 &&
2408 #endif /* OPENSSL_NO_STDIO */
2409 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2410 tls_show_errors(MSG_INFO, __func__,
2411 "Failed to load private key");
2418 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2420 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2421 tls_show_errors(MSG_INFO, __func__,
2422 "Private key failed verification");
2430 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2432 #ifdef OPENSSL_NO_DH
2433 if (dh_file == NULL)
2435 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2436 "dh_file specified");
2438 #else /* OPENSSL_NO_DH */
2442 /* TODO: add support for dh_blob */
2443 if (dh_file == NULL)
2448 bio = BIO_new_file(dh_file, "r");
2450 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2451 dh_file, ERR_error_string(ERR_get_error(), NULL));
2454 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2456 #ifndef OPENSSL_NO_DSA
2457 while (dh == NULL) {
2459 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2460 " trying to parse as DSA params", dh_file,
2461 ERR_error_string(ERR_get_error(), NULL));
2462 bio = BIO_new_file(dh_file, "r");
2465 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2468 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2469 "'%s': %s", dh_file,
2470 ERR_error_string(ERR_get_error(), NULL));
2474 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2475 dh = DSA_dup_DH(dsa);
2478 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2479 "params into DH params");
2484 #endif /* !OPENSSL_NO_DSA */
2486 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2491 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2492 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2494 ERR_error_string(ERR_get_error(), NULL));
2500 #endif /* OPENSSL_NO_DH */
2504 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2506 #ifdef OPENSSL_NO_DH
2507 if (dh_file == NULL)
2509 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2510 "dh_file specified");
2512 #else /* OPENSSL_NO_DH */
2516 /* TODO: add support for dh_blob */
2517 if (dh_file == NULL)
2519 if (ssl_ctx == NULL)
2522 bio = BIO_new_file(dh_file, "r");
2524 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2525 dh_file, ERR_error_string(ERR_get_error(), NULL));
2528 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2530 #ifndef OPENSSL_NO_DSA
2531 while (dh == NULL) {
2533 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2534 " trying to parse as DSA params", dh_file,
2535 ERR_error_string(ERR_get_error(), NULL));
2536 bio = BIO_new_file(dh_file, "r");
2539 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2542 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2543 "'%s': %s", dh_file,
2544 ERR_error_string(ERR_get_error(), NULL));
2548 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2549 dh = DSA_dup_DH(dsa);
2552 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2553 "params into DH params");
2558 #endif /* !OPENSSL_NO_DSA */
2560 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2565 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2566 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2568 ERR_error_string(ERR_get_error(), NULL));
2574 #endif /* OPENSSL_NO_DH */
2578 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2579 struct tls_keys *keys)
2582 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2585 #else /* CONFIG_FIPS */
2588 if (conn == NULL || keys == NULL)
2591 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2594 os_memset(keys, 0, sizeof(*keys));
2595 keys->master_key = ssl->session->master_key;
2596 keys->master_key_len = ssl->session->master_key_length;
2597 keys->client_random = ssl->s3->client_random;
2598 keys->client_random_len = SSL3_RANDOM_SIZE;
2599 keys->server_random = ssl->s3->server_random;
2600 keys->server_random_len = SSL3_RANDOM_SIZE;
2603 #endif /* CONFIG_FIPS */
2607 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2608 const char *label, int server_random_first,
2609 u8 *out, size_t out_len)
2611 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2615 if (server_random_first)
2618 if (SSL_export_keying_material(ssl, out, out_len, label,
2619 os_strlen(label), NULL, 0, 0) == 1) {
2620 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2628 static struct wpabuf *
2629 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2633 struct wpabuf *out_data;
2636 * Give TLS handshake data from the server (if available) to OpenSSL
2640 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2642 tls_show_errors(MSG_INFO, __func__,
2643 "Handshake failed - BIO_write");
2647 /* Initiate TLS handshake or continue the existing handshake */
2649 res = SSL_accept(conn->ssl);
2651 res = SSL_connect(conn->ssl);
2653 int err = SSL_get_error(conn->ssl, res);
2654 if (err == SSL_ERROR_WANT_READ)
2655 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2657 else if (err == SSL_ERROR_WANT_WRITE)
2658 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2661 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2666 /* Get the TLS handshake data to be sent to the server */
2667 res = BIO_ctrl_pending(conn->ssl_out);
2668 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2669 out_data = wpabuf_alloc(res);
2670 if (out_data == NULL) {
2671 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2672 "handshake output (%d bytes)", res);
2673 if (BIO_reset(conn->ssl_out) < 0) {
2674 tls_show_errors(MSG_INFO, __func__,
2675 "BIO_reset failed");
2679 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2682 tls_show_errors(MSG_INFO, __func__,
2683 "Handshake failed - BIO_read");
2684 if (BIO_reset(conn->ssl_out) < 0) {
2685 tls_show_errors(MSG_INFO, __func__,
2686 "BIO_reset failed");
2688 wpabuf_free(out_data);
2691 wpabuf_put(out_data, res);
2697 static struct wpabuf *
2698 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2700 struct wpabuf *appl_data;
2703 appl_data = wpabuf_alloc(max_len + 100);
2704 if (appl_data == NULL)
2707 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2708 wpabuf_size(appl_data));
2710 int err = SSL_get_error(conn->ssl, res);
2711 if (err == SSL_ERROR_WANT_READ ||
2712 err == SSL_ERROR_WANT_WRITE) {
2713 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2716 tls_show_errors(MSG_INFO, __func__,
2717 "Failed to read possible "
2718 "Application Data");
2720 wpabuf_free(appl_data);
2724 wpabuf_put(appl_data, res);
2725 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2726 "message", appl_data);
2732 static struct wpabuf *
2733 openssl_connection_handshake(struct tls_connection *conn,
2734 const struct wpabuf *in_data,
2735 struct wpabuf **appl_data, int server)
2737 struct wpabuf *out_data;
2742 out_data = openssl_handshake(conn, in_data, server);
2743 if (out_data == NULL)
2745 if (conn->invalid_hb_used) {
2746 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2747 wpabuf_free(out_data);
2751 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2752 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2754 if (conn->invalid_hb_used) {
2755 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2757 wpabuf_free(*appl_data);
2760 wpabuf_free(out_data);
2769 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2770 const struct wpabuf *in_data,
2771 struct wpabuf **appl_data)
2773 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2777 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2778 struct tls_connection *conn,
2779 const struct wpabuf *in_data,
2780 struct wpabuf **appl_data)
2782 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2786 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2787 struct tls_connection *conn,
2788 const struct wpabuf *in_data)
2796 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2797 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2798 (res = BIO_reset(conn->ssl_out)) < 0) {
2799 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2802 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2804 tls_show_errors(MSG_INFO, __func__,
2805 "Encryption failed - SSL_write");
2809 /* Read encrypted data to be sent to the server */
2810 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2813 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2815 tls_show_errors(MSG_INFO, __func__,
2816 "Encryption failed - BIO_read");
2820 wpabuf_put(buf, res);
2826 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2827 struct tls_connection *conn,
2828 const struct wpabuf *in_data)
2833 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2834 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2835 wpabuf_len(in_data));
2837 tls_show_errors(MSG_INFO, __func__,
2838 "Decryption failed - BIO_write");
2841 if (BIO_reset(conn->ssl_out) < 0) {
2842 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2846 /* Read decrypted data for further processing */
2848 * Even though we try to disable TLS compression, it is possible that
2849 * this cannot be done with all TLS libraries. Add extra buffer space
2850 * to handle the possibility of the decrypted data being longer than
2853 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2856 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2858 tls_show_errors(MSG_INFO, __func__,
2859 "Decryption failed - SSL_read");
2863 wpabuf_put(buf, res);
2865 if (conn->invalid_hb_used) {
2866 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2875 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2877 return conn ? conn->ssl->hit : 0;
2881 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2884 char buf[100], *pos, *end;
2888 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2893 end = pos + sizeof(buf);
2896 while (*c != TLS_CIPHER_NONE) {
2900 case TLS_CIPHER_RC4_SHA:
2903 case TLS_CIPHER_AES128_SHA:
2904 suite = "AES128-SHA";
2906 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2907 suite = "DHE-RSA-AES128-SHA";
2909 case TLS_CIPHER_ANON_DH_AES128_SHA:
2910 suite = "ADH-AES128-SHA";
2913 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2914 "cipher selection: %d", *c);
2917 ret = os_snprintf(pos, end - pos, ":%s", suite);
2918 if (os_snprintf_error(end - pos, ret))
2925 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2927 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2928 tls_show_errors(MSG_INFO, __func__,
2929 "Cipher suite configuration failed");
2937 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2938 char *buf, size_t buflen)
2941 if (conn == NULL || conn->ssl == NULL)
2944 name = SSL_get_cipher(conn->ssl);
2948 os_strlcpy(buf, name, buflen);
2953 int tls_connection_enable_workaround(void *ssl_ctx,
2954 struct tls_connection *conn)
2956 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2962 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2963 /* ClientHello TLS extensions require a patch to openssl, so this function is
2964 * commented out unless explicitly needed for EAP-FAST in order to be able to
2965 * build this file with unmodified openssl. */
2966 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2967 int ext_type, const u8 *data,
2970 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2973 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2979 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2982 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2986 return conn->failed;
2990 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2994 return conn->read_alerts;
2998 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3002 return conn->write_alerts;
3008 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3010 #ifndef CONFIG_NO_STDOUT_DEBUG
3016 if (wpa_debug_level > MSG_DEBUG)
3019 out = BIO_new(BIO_s_mem());
3023 OCSP_RESPONSE_print(out, rsp, 0);
3024 rlen = BIO_ctrl_pending(out);
3025 txt = os_malloc(rlen + 1);
3031 res = BIO_read(out, txt, rlen);
3034 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3038 #endif /* CONFIG_NO_STDOUT_DEBUG */
3042 static void debug_print_cert(X509 *cert, const char *title)
3044 #ifndef CONFIG_NO_STDOUT_DEBUG
3050 if (wpa_debug_level > MSG_DEBUG)
3053 out = BIO_new(BIO_s_mem());
3057 X509_print(out, cert);
3058 rlen = BIO_ctrl_pending(out);
3059 txt = os_malloc(rlen + 1);
3065 res = BIO_read(out, txt, rlen);
3068 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3073 #endif /* CONFIG_NO_STDOUT_DEBUG */
3077 static int ocsp_resp_cb(SSL *s, void *arg)
3079 struct tls_connection *conn = arg;
3080 const unsigned char *p;
3081 int len, status, reason;
3083 OCSP_BASICRESP *basic;
3085 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3087 STACK_OF(X509) *certs = NULL;
3089 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3091 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3092 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3095 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3097 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3099 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3103 ocsp_debug_print_resp(rsp);
3105 status = OCSP_response_status(rsp);
3106 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3107 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3108 status, OCSP_response_status_str(status));
3112 basic = OCSP_response_get1_basic(rsp);
3114 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3118 store = SSL_CTX_get_cert_store(s->ctx);
3119 if (conn->peer_issuer) {
3120 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3122 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3123 tls_show_errors(MSG_INFO, __func__,
3124 "OpenSSL: Could not add issuer to certificate store\n");
3126 certs = sk_X509_new_null();
3129 cert = X509_dup(conn->peer_issuer);
3130 if (cert && !sk_X509_push(certs, cert)) {
3133 "OpenSSL: Could not add issuer to OCSP responder trust store\n");
3135 sk_X509_free(certs);
3138 if (conn->peer_issuer_issuer) {
3139 cert = X509_dup(conn->peer_issuer_issuer);
3140 if (cert && !sk_X509_push(certs, cert)) {
3143 "OpenSSL: Could not add issuer to OCSP responder trust store\n");
3150 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3151 sk_X509_pop_free(certs, X509_free);
3153 tls_show_errors(MSG_INFO, __func__,
3154 "OpenSSL: OCSP response failed verification");
3155 OCSP_BASICRESP_free(basic);
3156 OCSP_RESPONSE_free(rsp);
3160 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3162 if (!conn->peer_cert) {
3163 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3164 OCSP_BASICRESP_free(basic);
3165 OCSP_RESPONSE_free(rsp);
3169 if (!conn->peer_issuer) {
3170 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3171 OCSP_BASICRESP_free(basic);
3172 OCSP_RESPONSE_free(rsp);
3176 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3178 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3179 OCSP_BASICRESP_free(basic);
3180 OCSP_RESPONSE_free(rsp);
3184 if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3185 &this_update, &next_update)) {
3186 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3187 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3188 " (OCSP not required)");
3189 OCSP_BASICRESP_free(basic);
3190 OCSP_RESPONSE_free(rsp);
3191 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3194 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3195 tls_show_errors(MSG_INFO, __func__,
3196 "OpenSSL: OCSP status times invalid");
3197 OCSP_BASICRESP_free(basic);
3198 OCSP_RESPONSE_free(rsp);
3202 OCSP_BASICRESP_free(basic);
3203 OCSP_RESPONSE_free(rsp);
3205 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3206 OCSP_cert_status_str(status));
3208 if (status == V_OCSP_CERTSTATUS_GOOD)
3210 if (status == V_OCSP_CERTSTATUS_REVOKED)
3212 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3213 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3216 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3221 static int ocsp_status_cb(SSL *s, void *arg)
3227 if (tls_global->ocsp_stapling_response == NULL) {
3228 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3229 return SSL_TLSEXT_ERR_OK;
3232 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3234 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3235 /* TODO: Build OCSPResponse with responseStatus = internalError
3237 return SSL_TLSEXT_ERR_OK;
3239 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3240 tmp = OPENSSL_malloc(len);
3243 return SSL_TLSEXT_ERR_ALERT_FATAL;
3246 os_memcpy(tmp, resp, len);
3248 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3250 return SSL_TLSEXT_ERR_OK;
3253 #endif /* HAVE_OCSP */
3256 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3257 const struct tls_connection_params *params)
3262 const char *key_id = params->key_id;
3263 const char *cert_id = params->cert_id;
3264 const char *ca_cert_id = params->ca_cert_id;
3265 const char *engine_id = params->engine ? params->engine_id : NULL;
3271 * If the engine isn't explicitly configured, and any of the
3272 * cert/key fields are actually PKCS#11 URIs, then automatically
3273 * use the PKCS#11 ENGINE.
3275 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3278 if (!key_id && params->private_key && can_pkcs11 &&
3279 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3281 key_id = params->private_key;
3284 if (!cert_id && params->client_cert && can_pkcs11 &&
3285 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3287 cert_id = params->client_cert;
3290 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3291 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3293 ca_cert_id = params->ca_cert;
3296 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3297 if (can_pkcs11 == 2 && !engine_id)
3298 engine_id = "pkcs11";
3300 if (params->flags & TLS_CONN_EAP_FAST) {
3301 wpa_printf(MSG_DEBUG,
3302 "OpenSSL: Use TLSv1_method() for EAP-FAST");
3303 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3304 tls_show_errors(MSG_INFO, __func__,
3305 "Failed to set TLSv1_method() for EAP-FAST");
3310 while ((err = ERR_get_error())) {
3311 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3312 __func__, ERR_error_string(err, NULL));
3316 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3317 ret = tls_engine_init(conn, engine_id, params->pin,
3318 key_id, cert_id, ca_cert_id);
3322 if (tls_connection_set_subject_match(conn,
3323 params->subject_match,
3324 params->altsubject_match,
3325 params->suffix_match))
3328 if (engine_id && ca_cert_id) {
3329 if (tls_connection_engine_ca_cert(tls_ctx, conn,
3331 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3332 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
3333 params->ca_cert_blob,
3334 params->ca_cert_blob_len,
3338 if (engine_id && cert_id) {
3339 if (tls_connection_engine_client_cert(conn, cert_id))
3340 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3341 } else if (tls_connection_client_cert(conn, params->client_cert,
3342 params->client_cert_blob,
3343 params->client_cert_blob_len))
3346 if (engine_id && key_id) {
3347 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3348 if (tls_connection_engine_private_key(conn))
3349 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3350 } else if (tls_connection_private_key(tls_ctx, conn,
3351 params->private_key,
3352 params->private_key_passwd,
3353 params->private_key_blob,
3354 params->private_key_blob_len)) {
3355 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3356 params->private_key);
3360 if (tls_connection_dh(conn, params->dh_file)) {
3361 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3366 if (params->openssl_ciphers &&
3367 SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3368 wpa_printf(MSG_INFO,
3369 "OpenSSL: Failed to set cipher string '%s'",
3370 params->openssl_ciphers);
3374 #ifdef SSL_OP_NO_TICKET
3375 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3376 SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
3377 #ifdef SSL_clear_options
3379 SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
3380 #endif /* SSL_clear_options */
3381 #endif /* SSL_OP_NO_TICKET */
3383 #ifdef SSL_OP_NO_TLSv1_1
3384 if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
3385 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3387 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3388 #endif /* SSL_OP_NO_TLSv1_1 */
3389 #ifdef SSL_OP_NO_TLSv1_2
3390 if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
3391 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3393 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3394 #endif /* SSL_OP_NO_TLSv1_2 */
3397 if (params->flags & TLS_CONN_REQUEST_OCSP) {
3398 SSL_CTX *ssl_ctx = tls_ctx;
3399 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3400 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3401 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3403 #endif /* HAVE_OCSP */
3405 conn->flags = params->flags;
3407 tls_get_errors(tls_ctx);
3413 int tls_global_set_params(void *tls_ctx,
3414 const struct tls_connection_params *params)
3416 SSL_CTX *ssl_ctx = tls_ctx;
3419 while ((err = ERR_get_error())) {
3420 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3421 __func__, ERR_error_string(err, NULL));
3424 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
3427 if (tls_global_client_cert(ssl_ctx, params->client_cert))
3430 if (tls_global_private_key(ssl_ctx, params->private_key,
3431 params->private_key_passwd))
3434 if (tls_global_dh(ssl_ctx, params->dh_file)) {
3435 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3440 if (params->openssl_ciphers &&
3441 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3442 wpa_printf(MSG_INFO,
3443 "OpenSSL: Failed to set cipher string '%s'",
3444 params->openssl_ciphers);
3448 #ifdef SSL_OP_NO_TICKET
3449 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3450 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3451 #ifdef SSL_CTX_clear_options
3453 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3454 #endif /* SSL_clear_options */
3455 #endif /* SSL_OP_NO_TICKET */
3458 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3459 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3460 os_free(tls_global->ocsp_stapling_response);
3461 if (params->ocsp_stapling_response)
3462 tls_global->ocsp_stapling_response =
3463 os_strdup(params->ocsp_stapling_response);
3465 tls_global->ocsp_stapling_response = NULL;
3466 #endif /* HAVE_OCSP */
3472 int tls_connection_get_keyblock_size(void *tls_ctx,
3473 struct tls_connection *conn)
3475 const EVP_CIPHER *c;
3479 if (conn == NULL || conn->ssl == NULL ||
3480 conn->ssl->enc_read_ctx == NULL ||
3481 conn->ssl->enc_read_ctx->cipher == NULL ||
3482 conn->ssl->read_hash == NULL)
3485 c = conn->ssl->enc_read_ctx->cipher;
3486 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
3487 h = EVP_MD_CTX_md(conn->ssl->read_hash);
3489 h = conn->ssl->read_hash;
3492 md_size = EVP_MD_size(h);
3493 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
3494 else if (conn->ssl->s3)
3495 md_size = conn->ssl->s3->tmp.new_mac_secret_size;
3500 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
3501 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
3502 EVP_CIPHER_iv_length(c));
3503 return 2 * (EVP_CIPHER_key_length(c) +
3505 EVP_CIPHER_iv_length(c));
3509 unsigned int tls_capabilities(void *tls_ctx)
3515 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3516 /* Pre-shared secred requires a patch to openssl, so this function is
3517 * commented out unless explicitly needed for EAP-FAST in order to be able to
3518 * build this file with unmodified openssl. */
3520 #ifdef OPENSSL_IS_BORINGSSL
3521 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3522 STACK_OF(SSL_CIPHER) *peer_ciphers,
3523 const SSL_CIPHER **cipher, void *arg)
3524 #else /* OPENSSL_IS_BORINGSSL */
3525 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3526 STACK_OF(SSL_CIPHER) *peer_ciphers,
3527 SSL_CIPHER **cipher, void *arg)
3528 #endif /* OPENSSL_IS_BORINGSSL */
3530 struct tls_connection *conn = arg;
3533 if (conn == NULL || conn->session_ticket_cb == NULL)
3536 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3537 conn->session_ticket,
3538 conn->session_ticket_len,
3539 s->s3->client_random,
3540 s->s3->server_random, secret);
3541 os_free(conn->session_ticket);
3542 conn->session_ticket = NULL;
3547 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3552 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3555 struct tls_connection *conn = arg;
3557 if (conn == NULL || conn->session_ticket_cb == NULL)
3560 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3562 os_free(conn->session_ticket);
3563 conn->session_ticket = NULL;
3565 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3566 "extension", data, len);
3568 conn->session_ticket = os_malloc(len);
3569 if (conn->session_ticket == NULL)
3572 os_memcpy(conn->session_ticket, data, len);
3573 conn->session_ticket_len = len;
3577 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3580 int tls_connection_set_session_ticket_cb(void *tls_ctx,
3581 struct tls_connection *conn,
3582 tls_session_ticket_cb cb,
3585 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3586 conn->session_ticket_cb = cb;
3587 conn->session_ticket_cb_ctx = ctx;
3590 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3593 SSL_set_session_ticket_ext_cb(conn->ssl,
3594 tls_session_ticket_ext_cb, conn);
3596 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3598 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3602 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3604 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3608 int tls_get_library_version(char *buf, size_t buf_len)
3610 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
3611 OPENSSL_VERSION_TEXT,
3612 SSLeay_version(SSLEAY_VERSION));