2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2015, 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/opensslv.h>
22 #include <openssl/pkcs12.h>
23 #include <openssl/x509v3.h>
24 #ifndef OPENSSL_NO_ENGINE
25 #include <openssl/engine.h>
26 #endif /* OPENSSL_NO_ENGINE */
27 #ifndef OPENSSL_NO_DSA
28 #include <openssl/dsa.h>
31 #include <openssl/dh.h>
39 #include "tls_openssl.h"
41 #if !defined(CONFIG_FIPS) && \
42 (defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || \
43 defined(EAP_SERVER_FAST))
44 #define OPENSSL_NEED_EAP_FAST_PRF
47 #if defined(OPENSSL_IS_BORINGSSL)
48 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
49 typedef size_t stack_index_t;
51 typedef int stack_index_t;
54 #ifdef SSL_set_tlsext_status_type
55 #ifndef OPENSSL_NO_TLSEXT
57 #include <openssl/ocsp.h>
58 #endif /* OPENSSL_NO_TLSEXT */
59 #endif /* SSL_set_tlsext_status_type */
61 #if (OPENSSL_VERSION_NUMBER < 0x10100000L || \
62 (defined(LIBRESSL_VERSION_NUMBER) && \
63 LIBRESSL_VERSION_NUMBER < 0x20700000L)) && \
64 !defined(BORINGSSL_API_VERSION)
66 * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
67 * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
71 static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
74 if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
76 os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
77 return SSL3_RANDOM_SIZE;
81 static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
84 if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
86 os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
87 return SSL3_RANDOM_SIZE;
91 #ifdef OPENSSL_NEED_EAP_FAST_PRF
92 static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
93 unsigned char *out, size_t outlen)
95 if (!session || session->master_key_length < 0 ||
96 (size_t) session->master_key_length > outlen)
98 if ((size_t) session->master_key_length < outlen)
99 outlen = session->master_key_length;
100 os_memcpy(out, session->master_key, outlen);
103 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
107 #if OPENSSL_VERSION_NUMBER < 0x10100000L
109 static int RSA_bits(const RSA *r)
111 return BN_num_bits(r->n);
113 #endif /* CONFIG_SUITEB */
116 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
118 return ASN1_STRING_data((ASN1_STRING *) x);
123 #include <openssl/pem.h>
124 #include <keystore/keystore_get.h>
126 static BIO * BIO_from_keystore(const char *key)
129 uint8_t *value = NULL;
130 int length = keystore_get(key, strlen(key), &value);
131 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
132 BIO_write(bio, value, length);
138 static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
140 BIO *bio = BIO_from_keystore(key_alias);
141 STACK_OF(X509_INFO) *stack = NULL;
145 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
150 wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
155 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
156 X509_INFO *info = sk_X509_INFO_value(stack, i);
159 X509_STORE_add_cert(ctx, info->x509);
161 X509_STORE_add_crl(ctx, info->crl);
164 sk_X509_INFO_pop_free(stack, X509_INFO_free);
170 static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
171 const char *encoded_key_alias)
174 int len = os_strlen(encoded_key_alias);
175 unsigned char *decoded_alias;
178 wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
183 decoded_alias = os_malloc(len / 2 + 1);
185 if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
186 decoded_alias[len / 2] = '\0';
187 rc = tls_add_ca_from_keystore(
188 ctx, (const char *) decoded_alias);
190 os_free(decoded_alias);
198 static int tls_openssl_ref_count = 0;
199 static int tls_ex_idx_session = -1;
202 void (*event_cb)(void *ctx, enum tls_event ev,
203 union tls_event_data *data);
206 char *ocsp_stapling_response;
209 static struct tls_context *tls_global = NULL;
214 unsigned int tls_session_lifetime;
217 struct tls_connection {
218 struct tls_context *context;
221 BIO *ssl_in, *ssl_out;
222 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
223 ENGINE *engine; /* functional reference to the engine */
224 EVP_PKEY *private_key; /* the private key if using engine */
225 #endif /* OPENSSL_NO_ENGINE */
226 char *subject_match, *altsubject_match, *suffix_match, *domain_match;
227 int read_alerts, write_alerts, failed;
229 tls_session_ticket_cb session_ticket_cb;
230 void *session_ticket_cb_ctx;
232 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
234 size_t session_ticket_len;
236 unsigned int ca_cert_verify:1;
237 unsigned int cert_probe:1;
238 unsigned int server_cert_only:1;
239 unsigned int invalid_hb_used:1;
240 unsigned int success_data:1;
241 unsigned int client_hello_generated:1;
242 unsigned int server:1;
244 u8 srv_cert_hash[32];
250 X509 *peer_issuer_issuer;
252 unsigned char client_random[SSL3_RANDOM_SIZE];
253 unsigned char server_random[SSL3_RANDOM_SIZE];
256 int server_dh_prime_len;
260 static struct tls_context * tls_context_new(const struct tls_config *conf)
262 struct tls_context *context = os_zalloc(sizeof(*context));
266 context->event_cb = conf->event_cb;
267 context->cb_ctx = conf->cb_ctx;
268 context->cert_in_cb = conf->cert_in_cb;
274 #ifdef CONFIG_NO_STDOUT_DEBUG
276 static void _tls_show_errors(void)
280 while ((err = ERR_get_error())) {
281 /* Just ignore the errors, since stdout is disabled */
284 #define tls_show_errors(l, f, t) _tls_show_errors()
286 #else /* CONFIG_NO_STDOUT_DEBUG */
288 static void tls_show_errors(int level, const char *func, const char *txt)
292 wpa_printf(level, "OpenSSL: %s - %s %s",
293 func, txt, ERR_error_string(ERR_get_error(), NULL));
295 while ((err = ERR_get_error())) {
296 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
297 ERR_error_string(err, NULL));
301 #endif /* CONFIG_NO_STDOUT_DEBUG */
304 #ifdef CONFIG_NATIVE_WINDOWS
306 /* Windows CryptoAPI and access to certificate stores */
307 #include <wincrypt.h>
309 #ifdef __MINGW32_VERSION
311 * MinGW does not yet include all the needed definitions for CryptoAPI, so
312 * define here whatever extra is needed.
314 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
315 #define CERT_STORE_READONLY_FLAG 0x00008000
316 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
318 #endif /* __MINGW32_VERSION */
321 struct cryptoapi_rsa_data {
322 const CERT_CONTEXT *cert;
323 HCRYPTPROV crypt_prov;
325 BOOL free_crypt_prov;
329 static void cryptoapi_error(const char *msg)
331 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
332 msg, (unsigned int) GetLastError());
336 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
337 unsigned char *to, RSA *rsa, int padding)
339 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
344 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
345 unsigned char *to, RSA *rsa, int padding)
347 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
352 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
353 unsigned char *to, RSA *rsa, int padding)
355 struct cryptoapi_rsa_data *priv =
356 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
358 DWORD hash_size, len, i;
359 unsigned char *buf = NULL;
363 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
364 ERR_R_PASSED_NULL_PARAMETER);
368 if (padding != RSA_PKCS1_PADDING) {
369 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
370 RSA_R_UNKNOWN_PADDING_TYPE);
374 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
375 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
377 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
378 RSA_R_INVALID_MESSAGE_LENGTH);
382 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
384 cryptoapi_error("CryptCreateHash failed");
388 len = sizeof(hash_size);
389 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
391 cryptoapi_error("CryptGetHashParam failed");
395 if ((int) hash_size != flen) {
396 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
397 (unsigned) hash_size, flen);
398 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
399 RSA_R_INVALID_MESSAGE_LENGTH);
402 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
403 cryptoapi_error("CryptSetHashParam failed");
408 buf = os_malloc(len);
410 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
414 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
415 cryptoapi_error("CryptSignHash failed");
419 for (i = 0; i < len; i++)
420 to[i] = buf[len - i - 1];
425 CryptDestroyHash(hash);
431 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
432 unsigned char *to, RSA *rsa, int padding)
434 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
439 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
443 if (priv->crypt_prov && priv->free_crypt_prov)
444 CryptReleaseContext(priv->crypt_prov, 0);
446 CertFreeCertificateContext(priv->cert);
451 static int cryptoapi_finish(RSA *rsa)
453 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
454 os_free((void *) rsa->meth);
460 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
463 const CERT_CONTEXT *ret = NULL;
465 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
466 store | CERT_STORE_OPEN_EXISTING_FLAG |
467 CERT_STORE_READONLY_FLAG, L"MY");
469 cryptoapi_error("Failed to open 'My system store'");
473 if (strncmp(name, "cert://", 7) == 0) {
474 unsigned short wbuf[255];
475 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
476 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
478 0, CERT_FIND_SUBJECT_STR,
480 } else if (strncmp(name, "hash://", 7) == 0) {
481 CRYPT_HASH_BLOB blob;
483 const char *hash = name + 7;
486 len = os_strlen(hash) / 2;
487 buf = os_malloc(len);
488 if (buf && hexstr2bin(hash, buf, len) == 0) {
491 ret = CertFindCertificateInStore(cs,
500 CertCloseStore(cs, 0);
506 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
509 RSA *rsa = NULL, *pub_rsa;
510 struct cryptoapi_rsa_data *priv;
511 RSA_METHOD *rsa_meth;
514 (strncmp(name, "cert://", 7) != 0 &&
515 strncmp(name, "hash://", 7) != 0))
518 priv = os_zalloc(sizeof(*priv));
519 rsa_meth = os_zalloc(sizeof(*rsa_meth));
520 if (priv == NULL || rsa_meth == NULL) {
521 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
522 "for CryptoAPI RSA method");
528 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
529 if (priv->cert == NULL) {
530 priv->cert = cryptoapi_find_cert(
531 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
533 if (priv->cert == NULL) {
534 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
539 cert = d2i_X509(NULL,
540 (const unsigned char **) &priv->cert->pbCertEncoded,
541 priv->cert->cbCertEncoded);
543 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
548 if (!CryptAcquireCertificatePrivateKey(priv->cert,
549 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
550 NULL, &priv->crypt_prov,
552 &priv->free_crypt_prov)) {
553 cryptoapi_error("Failed to acquire a private key for the "
558 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
559 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
560 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
561 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
562 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
563 rsa_meth->finish = cryptoapi_finish;
564 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
565 rsa_meth->app_data = (char *) priv;
569 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
570 ERR_R_MALLOC_FAILURE);
574 if (!SSL_use_certificate(ssl, cert)) {
579 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
583 rsa->n = BN_dup(pub_rsa->n);
584 rsa->e = BN_dup(pub_rsa->e);
585 if (!RSA_set_method(rsa, rsa_meth))
588 if (!SSL_use_RSAPrivateKey(ssl, rsa))
601 cryptoapi_free_data(priv);
607 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
610 PCCERT_CONTEXT ctx = NULL;
618 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
623 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
626 wsprintf(wstore, L"%S", store);
627 cs = CertOpenSystemStore(0, wstore);
630 cs = CertOpenSystemStore(0, store);
633 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
634 "'%s': error=%d", __func__, store,
635 (int) GetLastError());
639 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
640 cert = d2i_X509(NULL,
641 (const unsigned char **) &ctx->pbCertEncoded,
644 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
645 "X509 DER encoding for CA cert");
649 X509_NAME_oneline(X509_get_subject_name(cert), buf,
651 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
652 "system certificate store: subject='%s'", buf);
654 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
656 tls_show_errors(MSG_WARNING, __func__,
657 "Failed to add ca_cert to OpenSSL "
658 "certificate store");
664 if (!CertCloseStore(cs, 0)) {
665 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
666 "'%s': error=%d", __func__, name + 13,
667 (int) GetLastError());
674 #else /* CONFIG_NATIVE_WINDOWS */
676 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
681 #endif /* CONFIG_NATIVE_WINDOWS */
684 static void ssl_info_cb(const SSL *ssl, int where, int ret)
689 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
690 w = where & ~SSL_ST_MASK;
691 if (w & SSL_ST_CONNECT)
693 else if (w & SSL_ST_ACCEPT)
698 if (where & SSL_CB_LOOP) {
699 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
700 str, SSL_state_string_long(ssl));
701 } else if (where & SSL_CB_ALERT) {
702 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
703 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
704 where & SSL_CB_READ ?
705 "read (remote end reported an error)" :
706 "write (local SSL3 detected an error)",
707 SSL_alert_type_string_long(ret),
708 SSL_alert_desc_string_long(ret));
709 if ((ret >> 8) == SSL3_AL_FATAL) {
710 if (where & SSL_CB_READ)
713 conn->write_alerts++;
715 if (conn->context->event_cb != NULL) {
716 union tls_event_data ev;
717 struct tls_context *context = conn->context;
718 os_memset(&ev, 0, sizeof(ev));
719 ev.alert.is_local = !(where & SSL_CB_READ);
720 ev.alert.type = SSL_alert_type_string_long(ret);
721 ev.alert.description = SSL_alert_desc_string_long(ret);
722 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
724 } else if (where & SSL_CB_EXIT && ret <= 0) {
725 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
726 str, ret == 0 ? "failed" : "error",
727 SSL_state_string_long(ssl));
732 #ifndef OPENSSL_NO_ENGINE
734 * tls_engine_load_dynamic_generic - load any openssl engine
735 * @pre: an array of commands and values that load an engine initialized
736 * in the engine specific function
737 * @post: an array of commands and values that initialize an already loaded
738 * engine (or %NULL if not required)
739 * @id: the engine id of the engine to load (only required if post is not %NULL
741 * This function is a generic function that loads any openssl engine.
743 * Returns: 0 on success, -1 on failure
745 static int tls_engine_load_dynamic_generic(const char *pre[],
746 const char *post[], const char *id)
749 const char *dynamic_id = "dynamic";
751 engine = ENGINE_by_id(id);
753 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
756 * If it was auto-loaded by ENGINE_by_id() we might still
757 * need to tell it which PKCS#11 module to use in legacy
758 * (non-p11-kit) environments. Do so now; even if it was
759 * properly initialised before, setting it again will be
766 engine = ENGINE_by_id(dynamic_id);
767 if (engine == NULL) {
768 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
770 ERR_error_string(ERR_get_error(), NULL));
774 /* Perform the pre commands. This will load the engine. */
775 while (pre && pre[0]) {
776 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
777 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
778 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
779 "%s %s [%s]", pre[0], pre[1],
780 ERR_error_string(ERR_get_error(), NULL));
788 * Free the reference to the "dynamic" engine. The loaded engine can
789 * now be looked up using ENGINE_by_id().
793 engine = ENGINE_by_id(id);
794 if (engine == NULL) {
795 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
796 id, ERR_error_string(ERR_get_error(), NULL));
800 while (post && post[0]) {
801 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
802 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
803 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
804 " %s %s [%s]", post[0], post[1],
805 ERR_error_string(ERR_get_error(), NULL));
806 ENGINE_remove(engine);
819 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
820 * @pkcs11_so_path: pksc11_so_path from the configuration
821 * @pcks11_module_path: pkcs11_module_path from the configuration
823 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
824 const char *pkcs11_module_path)
826 char *engine_id = "pkcs11";
827 const char *pre_cmd[] = {
828 "SO_PATH", NULL /* pkcs11_so_path */,
829 "ID", NULL /* engine_id */,
831 /* "NO_VCHECK", "1", */
835 const char *post_cmd[] = {
836 "MODULE_PATH", NULL /* pkcs11_module_path */,
843 pre_cmd[1] = pkcs11_so_path;
844 pre_cmd[3] = engine_id;
845 if (pkcs11_module_path)
846 post_cmd[1] = pkcs11_module_path;
850 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
853 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
858 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
859 * @opensc_so_path: opensc_so_path from the configuration
861 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
863 char *engine_id = "opensc";
864 const char *pre_cmd[] = {
865 "SO_PATH", NULL /* opensc_so_path */,
866 "ID", NULL /* engine_id */,
875 pre_cmd[1] = opensc_so_path;
876 pre_cmd[3] = engine_id;
878 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
881 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
883 #endif /* OPENSSL_NO_ENGINE */
886 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
890 if (tls_ex_idx_session < 0)
892 buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
895 wpa_printf(MSG_DEBUG,
896 "OpenSSL: Free application session data %p (sess %p)",
900 SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
904 void * tls_init(const struct tls_config *conf)
906 struct tls_data *data;
908 struct tls_context *context;
911 if (tls_openssl_ref_count == 0) {
912 tls_global = context = tls_context_new(conf);
917 if (conf && conf->fips_mode) {
918 static int fips_enabled = 0;
920 if (!fips_enabled && !FIPS_mode_set(1)) {
921 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
923 ERR_load_crypto_strings();
924 ERR_print_errors_fp(stderr);
929 wpa_printf(MSG_INFO, "Running in FIPS mode");
933 #else /* OPENSSL_FIPS */
934 if (conf && conf->fips_mode) {
935 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
941 #endif /* OPENSSL_FIPS */
942 #endif /* CONFIG_FIPS */
943 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
944 (defined(LIBRESSL_VERSION_NUMBER) && \
945 LIBRESSL_VERSION_NUMBER < 0x20700000L)
946 SSL_load_error_strings();
948 #ifndef OPENSSL_NO_SHA256
949 EVP_add_digest(EVP_sha256());
950 #endif /* OPENSSL_NO_SHA256 */
951 /* TODO: if /dev/urandom is available, PRNG is seeded
952 * automatically. If this is not the case, random data should
956 #ifndef OPENSSL_NO_RC2
958 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
959 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
960 * versions, but it looks like OpenSSL 1.0.0 does not do that
963 EVP_add_cipher(EVP_rc2_40_cbc());
964 #endif /* OPENSSL_NO_RC2 */
966 #endif /* PKCS12_FUNCS */
969 context = tls_context_new(conf);
973 tls_openssl_ref_count++;
975 data = os_zalloc(sizeof(*data));
977 ssl = SSL_CTX_new(SSLv23_method());
981 tls_openssl_ref_count--;
982 if (context != tls_global)
984 if (tls_openssl_ref_count == 0) {
993 data->tls_session_lifetime = conf->tls_session_lifetime;
995 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
996 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
998 #ifdef SSL_MODE_NO_AUTO_CHAIN
999 /* Number of deployed use cases assume the default OpenSSL behavior of
1000 * auto chaining the local certificate is in use. BoringSSL removed this
1001 * functionality by default, so we need to restore it here to avoid
1002 * breaking existing use cases. */
1003 SSL_CTX_clear_mode(ssl, SSL_MODE_NO_AUTO_CHAIN);
1004 #endif /* SSL_MODE_NO_AUTO_CHAIN */
1006 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
1007 SSL_CTX_set_app_data(ssl, context);
1008 if (data->tls_session_lifetime > 0) {
1009 SSL_CTX_set_quiet_shutdown(ssl, 1);
1011 * Set default context here. In practice, this will be replaced
1012 * by the per-EAP method context in tls_connection_set_verify().
1014 SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
1015 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
1016 SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
1017 SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
1019 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
1022 if (tls_ex_idx_session < 0) {
1023 tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
1024 0, NULL, NULL, NULL, NULL);
1025 if (tls_ex_idx_session < 0) {
1031 #ifndef OPENSSL_NO_ENGINE
1032 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
1033 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1034 ERR_load_ENGINE_strings();
1035 ENGINE_load_dynamic();
1036 #endif /* OPENSSL_VERSION_NUMBER */
1039 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
1040 conf->pkcs11_module_path)) {
1041 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
1042 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
1043 conf->pkcs11_module_path)) {
1048 #endif /* OPENSSL_NO_ENGINE */
1050 if (conf && conf->openssl_ciphers)
1051 ciphers = conf->openssl_ciphers;
1053 ciphers = TLS_DEFAULT_CIPHERS;
1054 if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
1055 wpa_printf(MSG_ERROR,
1056 "OpenSSL: Failed to set cipher string '%s'",
1066 void tls_deinit(void *ssl_ctx)
1068 struct tls_data *data = ssl_ctx;
1069 SSL_CTX *ssl = data->ssl;
1070 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1071 if (context != tls_global)
1073 if (data->tls_session_lifetime > 0)
1074 SSL_CTX_flush_sessions(ssl, 0);
1077 tls_openssl_ref_count--;
1078 if (tls_openssl_ref_count == 0) {
1079 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
1080 (defined(LIBRESSL_VERSION_NUMBER) && \
1081 LIBRESSL_VERSION_NUMBER < 0x20700000L)
1082 #ifndef OPENSSL_NO_ENGINE
1084 #endif /* OPENSSL_NO_ENGINE */
1085 CRYPTO_cleanup_all_ex_data();
1086 ERR_remove_thread_state(NULL);
1089 #endif /* < 1.1.0 */
1090 os_free(tls_global->ocsp_stapling_response);
1091 tls_global->ocsp_stapling_response = NULL;
1092 os_free(tls_global);
1100 #ifndef OPENSSL_NO_ENGINE
1102 /* Cryptoki return values */
1103 #define CKR_PIN_INCORRECT 0x000000a0
1104 #define CKR_PIN_INVALID 0x000000a1
1105 #define CKR_PIN_LEN_RANGE 0x000000a2
1108 #define ERR_LIB_PKCS11 ERR_LIB_USER
1110 static int tls_is_pin_error(unsigned int err)
1112 return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
1113 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
1114 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
1115 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
1118 #endif /* OPENSSL_NO_ENGINE */
1122 /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
1123 EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
1124 #endif /* ANDROID */
1126 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
1127 const char *pin, const char *key_id,
1128 const char *cert_id, const char *ca_cert_id)
1130 #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
1131 #if !defined(OPENSSL_NO_ENGINE)
1132 #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
1135 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1136 conn->engine = NULL;
1137 conn->private_key = EVP_PKEY_from_keystore(key_id);
1138 if (!conn->private_key) {
1139 wpa_printf(MSG_ERROR,
1140 "ENGINE: cannot load private key with id '%s' [%s]",
1142 ERR_error_string(ERR_get_error(), NULL));
1143 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1145 #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
1147 #ifndef OPENSSL_NO_ENGINE
1149 if (engine_id == NULL) {
1150 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
1156 ENGINE_load_dynamic();
1158 conn->engine = ENGINE_by_id(engine_id);
1159 if (!conn->engine) {
1160 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
1161 engine_id, ERR_error_string(ERR_get_error(), NULL));
1164 if (ENGINE_init(conn->engine) != 1) {
1165 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
1166 "(engine: %s) [%s]", engine_id,
1167 ERR_error_string(ERR_get_error(), NULL));
1170 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
1173 if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
1174 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
1175 ERR_error_string(ERR_get_error(), NULL));
1181 * Ensure that the ENGINE does not attempt to use the OpenSSL
1182 * UI system to obtain a PIN, if we didn't provide one.
1185 const void *password;
1186 const char *prompt_info;
1187 } key_cb = { "", NULL };
1189 /* load private key first in-case PIN is required for cert */
1190 conn->private_key = ENGINE_load_private_key(conn->engine,
1193 if (!conn->private_key) {
1194 unsigned long err = ERR_get_error();
1196 wpa_printf(MSG_ERROR,
1197 "ENGINE: cannot load private key with id '%s' [%s]",
1199 ERR_error_string(err, NULL));
1200 if (tls_is_pin_error(err))
1201 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
1203 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1208 /* handle a certificate and/or CA certificate */
1209 if (cert_id || ca_cert_id) {
1210 const char *cmd_name = "LOAD_CERT_CTRL";
1212 /* test if the engine supports a LOAD_CERT_CTRL */
1213 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
1214 0, (void *)cmd_name, NULL)) {
1215 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
1216 " loading certificates");
1217 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1226 ENGINE_free(conn->engine);
1227 conn->engine = NULL;
1230 if (conn->private_key) {
1231 EVP_PKEY_free(conn->private_key);
1232 conn->private_key = NULL;
1236 #else /* OPENSSL_NO_ENGINE */
1238 #endif /* OPENSSL_NO_ENGINE */
1242 static void tls_engine_deinit(struct tls_connection *conn)
1244 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1245 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1246 if (conn->private_key) {
1247 EVP_PKEY_free(conn->private_key);
1248 conn->private_key = NULL;
1251 #if !defined(OPENSSL_IS_BORINGSSL)
1252 ENGINE_finish(conn->engine);
1253 #endif /* !OPENSSL_IS_BORINGSSL */
1254 conn->engine = NULL;
1256 #endif /* ANDROID || !OPENSSL_NO_ENGINE */
1260 int tls_get_errors(void *ssl_ctx)
1265 while ((err = ERR_get_error())) {
1266 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1267 ERR_error_string(err, NULL));
1275 static const char * openssl_content_type(int content_type)
1277 switch (content_type) {
1279 return "change cipher spec";
1285 return "application data";
1289 return "TLS header info"; /* pseudo content type */
1296 static const char * openssl_handshake_type(int content_type, const u8 *buf,
1299 if (content_type != 22 || !buf || len == 0)
1303 return "hello request";
1305 return "client hello";
1307 return "server hello";
1309 return "new session ticket";
1311 return "certificate";
1313 return "server key exchange";
1315 return "certificate request";
1317 return "server hello done";
1319 return "certificate verify";
1321 return "client key exchange";
1325 return "certificate url";
1327 return "certificate status";
1334 #ifdef CONFIG_SUITEB
1336 static void check_server_hello(struct tls_connection *conn,
1337 const u8 *pos, const u8 *end)
1339 size_t payload_len, id_len;
1342 * Parse ServerHello to get the selected cipher suite since OpenSSL does
1343 * not make it cleanly available during handshake and we need to know
1344 * whether DHE was selected.
1349 payload_len = WPA_GET_BE24(pos);
1352 if ((size_t) (end - pos) < payload_len)
1354 end = pos + payload_len;
1356 /* Skip Version and Random */
1357 if (end - pos < 2 + SSL3_RANDOM_SIZE)
1359 pos += 2 + SSL3_RANDOM_SIZE;
1361 /* Skip Session ID */
1365 if ((size_t) (end - pos) < id_len)
1371 conn->cipher_suite = WPA_GET_BE16(pos);
1372 wpa_printf(MSG_DEBUG, "OpenSSL: Server selected cipher suite 0x%x",
1373 conn->cipher_suite);
1377 static void check_server_key_exchange(SSL *ssl, struct tls_connection *conn,
1378 const u8 *pos, const u8 *end)
1385 if (!(conn->flags & TLS_CONN_SUITEB))
1388 /* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
1389 if (conn->cipher_suite != 0x9f)
1394 payload_len = WPA_GET_BE24(pos);
1397 if ((size_t) (end - pos) < payload_len)
1399 end = pos + payload_len;
1403 dh_len = WPA_GET_BE16(pos);
1406 if ((size_t) (end - pos) < dh_len)
1408 p = BN_bin2bn(pos, dh_len, NULL);
1412 bits = BN_num_bits(p);
1415 conn->server_dh_prime_len = bits;
1416 wpa_printf(MSG_DEBUG, "OpenSSL: Server DH prime length: %d bits",
1417 conn->server_dh_prime_len);
1420 #endif /* CONFIG_SUITEB */
1423 static void tls_msg_cb(int write_p, int version, int content_type,
1424 const void *buf, size_t len, SSL *ssl, void *arg)
1426 struct tls_connection *conn = arg;
1427 const u8 *pos = buf;
1430 wpa_printf(MSG_DEBUG,
1431 "OpenSSL: session ver=0x%x content_type=%d",
1432 version, content_type);
1433 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
1437 wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
1438 write_p ? "TX" : "RX", version, content_type,
1439 openssl_content_type(content_type),
1440 openssl_handshake_type(content_type, buf, len));
1441 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1442 if (content_type == 24 && len >= 3 && pos[0] == 1) {
1443 size_t payload_len = WPA_GET_BE16(pos + 1);
1444 if (payload_len + 3 > len) {
1445 wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1446 conn->invalid_hb_used = 1;
1450 #ifdef CONFIG_SUITEB
1452 * Need to parse these handshake messages to be able to check DH prime
1453 * length since OpenSSL does not expose the new cipher suite and DH
1454 * parameters during handshake (e.g., for cert_cb() callback).
1456 if (content_type == 22 && pos && len > 0 && pos[0] == 2)
1457 check_server_hello(conn, pos + 1, pos + len);
1458 if (content_type == 22 && pos && len > 0 && pos[0] == 12)
1459 check_server_key_exchange(ssl, conn, pos + 1, pos + len);
1460 #endif /* CONFIG_SUITEB */
1464 struct tls_connection * tls_connection_init(void *ssl_ctx)
1466 struct tls_data *data = ssl_ctx;
1467 SSL_CTX *ssl = data->ssl;
1468 struct tls_connection *conn;
1470 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1472 conn = os_zalloc(sizeof(*conn));
1475 conn->ssl_ctx = ssl;
1476 conn->ssl = SSL_new(ssl);
1477 if (conn->ssl == NULL) {
1478 tls_show_errors(MSG_INFO, __func__,
1479 "Failed to initialize new SSL connection");
1484 conn->context = context;
1485 SSL_set_app_data(conn->ssl, conn);
1486 SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1487 SSL_set_msg_callback_arg(conn->ssl, conn);
1488 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1489 SSL_OP_SINGLE_DH_USE;
1490 #ifdef SSL_OP_NO_COMPRESSION
1491 options |= SSL_OP_NO_COMPRESSION;
1492 #endif /* SSL_OP_NO_COMPRESSION */
1493 SSL_set_options(conn->ssl, options);
1495 conn->ssl_in = BIO_new(BIO_s_mem());
1496 if (!conn->ssl_in) {
1497 tls_show_errors(MSG_INFO, __func__,
1498 "Failed to create a new BIO for ssl_in");
1499 SSL_free(conn->ssl);
1504 conn->ssl_out = BIO_new(BIO_s_mem());
1505 if (!conn->ssl_out) {
1506 tls_show_errors(MSG_INFO, __func__,
1507 "Failed to create a new BIO for ssl_out");
1508 SSL_free(conn->ssl);
1509 BIO_free(conn->ssl_in);
1514 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1520 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1524 if (conn->success_data) {
1526 * Make sure ssl_clear_bad_session() does not remove this
1529 SSL_set_quiet_shutdown(conn->ssl, 1);
1530 SSL_shutdown(conn->ssl);
1532 SSL_free(conn->ssl);
1533 tls_engine_deinit(conn);
1534 os_free(conn->subject_match);
1535 os_free(conn->altsubject_match);
1536 os_free(conn->suffix_match);
1537 os_free(conn->domain_match);
1538 os_free(conn->session_ticket);
1543 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1545 return conn ? SSL_is_init_finished(conn->ssl) : 0;
1549 char * tls_connection_peer_serial_num(void *tls_ctx,
1550 struct tls_connection *conn)
1556 if (!conn->peer_cert)
1559 ser = X509_get_serialNumber(conn->peer_cert);
1563 len = ASN1_STRING_length(ser) * 2 + 1;
1564 serial_num = os_malloc(len);
1567 wpa_snprintf_hex_uppercase(serial_num, len,
1568 ASN1_STRING_get0_data(ser),
1569 ASN1_STRING_length(ser));
1574 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1579 /* Shutdown previous TLS connection without notifying the peer
1580 * because the connection was already terminated in practice
1581 * and "close notify" shutdown alert would confuse AS. */
1582 SSL_set_quiet_shutdown(conn->ssl, 1);
1583 SSL_shutdown(conn->ssl);
1584 return SSL_clear(conn->ssl) == 1 ? 0 : -1;
1588 static int tls_match_altsubject_component(X509 *cert, int type,
1589 const char *value, size_t len)
1596 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1598 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1599 gen = sk_GENERAL_NAME_value(ext, i);
1600 if (gen->type != type)
1602 if (os_strlen((char *) gen->d.ia5->data) == len &&
1603 os_memcmp(value, gen->d.ia5->data, len) == 0)
1607 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1613 static int tls_match_altsubject(X509 *cert, const char *match)
1616 const char *pos, *end;
1621 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1624 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1627 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1631 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1635 end = os_strchr(pos, ';');
1637 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1638 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1639 os_strncmp(end + 1, "URI:", 4) == 0)
1641 end = os_strchr(end + 1, ';');
1646 len = os_strlen(pos);
1647 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1656 #ifndef CONFIG_NATIVE_WINDOWS
1657 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1660 size_t i, match_len;
1662 /* Check for embedded nuls that could mess up suffix matching */
1663 for (i = 0; i < len; i++) {
1664 if (val[i] == '\0') {
1665 wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1670 match_len = os_strlen(match);
1671 if (match_len > len || (full && match_len != len))
1674 if (os_strncasecmp((const char *) val + len - match_len, match,
1676 return 0; /* no match */
1678 if (match_len == len)
1679 return 1; /* exact match */
1681 if (val[len - match_len - 1] == '.')
1682 return 1; /* full label match completes suffix match */
1684 wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1687 #endif /* CONFIG_NATIVE_WINDOWS */
1690 static int tls_match_suffix(X509 *cert, const char *match, int full)
1692 #ifdef CONFIG_NATIVE_WINDOWS
1693 /* wincrypt.h has conflicting X509_NAME definition */
1695 #else /* CONFIG_NATIVE_WINDOWS */
1703 wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1704 full ? "": "suffix ", match);
1706 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1708 for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1709 gen = sk_GENERAL_NAME_value(ext, j);
1710 if (gen->type != GEN_DNS)
1713 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1714 gen->d.dNSName->data,
1715 gen->d.dNSName->length);
1716 if (domain_suffix_match(gen->d.dNSName->data,
1717 gen->d.dNSName->length, match, full) ==
1719 wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
1720 full ? "Match" : "Suffix match");
1721 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1725 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1728 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1732 name = X509_get_subject_name(cert);
1738 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1741 e = X509_NAME_get_entry(name, i);
1744 cn = X509_NAME_ENTRY_get_data(e);
1747 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1748 cn->data, cn->length);
1749 if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
1751 wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
1752 full ? "Match" : "Suffix match");
1757 wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
1758 full ? "": "suffix ");
1760 #endif /* CONFIG_NATIVE_WINDOWS */
1764 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1767 case X509_V_ERR_CERT_REVOKED:
1768 return TLS_FAIL_REVOKED;
1769 case X509_V_ERR_CERT_NOT_YET_VALID:
1770 case X509_V_ERR_CRL_NOT_YET_VALID:
1771 return TLS_FAIL_NOT_YET_VALID;
1772 case X509_V_ERR_CERT_HAS_EXPIRED:
1773 case X509_V_ERR_CRL_HAS_EXPIRED:
1774 return TLS_FAIL_EXPIRED;
1775 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1776 case X509_V_ERR_UNABLE_TO_GET_CRL:
1777 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1778 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1779 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1780 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1781 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1782 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1783 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1784 case X509_V_ERR_INVALID_CA:
1785 return TLS_FAIL_UNTRUSTED;
1786 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1787 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1788 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1789 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1790 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1791 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1792 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1793 case X509_V_ERR_CERT_UNTRUSTED:
1794 case X509_V_ERR_CERT_REJECTED:
1795 return TLS_FAIL_BAD_CERTIFICATE;
1797 return TLS_FAIL_UNSPECIFIED;
1802 static struct wpabuf * get_x509_cert(X509 *cert)
1807 int cert_len = i2d_X509(cert, NULL);
1811 buf = wpabuf_alloc(cert_len);
1815 tmp = wpabuf_put(buf, cert_len);
1816 i2d_X509(cert, &tmp);
1821 static void openssl_tls_fail_event(struct tls_connection *conn,
1822 X509 *err_cert, int err, int depth,
1823 const char *subject, const char *err_str,
1824 enum tls_fail_reason reason)
1826 union tls_event_data ev;
1827 struct wpabuf *cert = NULL;
1828 struct tls_context *context = conn->context;
1830 if (context->event_cb == NULL)
1833 cert = get_x509_cert(err_cert);
1834 os_memset(&ev, 0, sizeof(ev));
1835 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1836 reason : openssl_tls_fail_reason(err);
1837 ev.cert_fail.depth = depth;
1838 ev.cert_fail.subject = subject;
1839 ev.cert_fail.reason_txt = err_str;
1840 ev.cert_fail.cert = cert;
1841 context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1846 static void openssl_tls_cert_event(struct tls_connection *conn,
1847 X509 *err_cert, int depth,
1848 const char *subject)
1850 struct wpabuf *cert = NULL;
1851 union tls_event_data ev;
1852 struct tls_context *context = conn->context;
1853 char *altsubject[TLS_MAX_ALT_SUBJECT];
1854 int alt, num_altsubject = 0;
1859 char serial_num[128];
1860 #ifdef CONFIG_SHA256
1862 #endif /* CONFIG_SHA256 */
1864 if (context->event_cb == NULL)
1867 os_memset(&ev, 0, sizeof(ev));
1868 if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
1869 context->cert_in_cb) {
1870 cert = get_x509_cert(err_cert);
1871 ev.peer_cert.cert = cert;
1873 #ifdef CONFIG_SHA256
1877 addr[0] = wpabuf_head(cert);
1878 len[0] = wpabuf_len(cert);
1879 if (sha256_vector(1, addr, len, hash) == 0) {
1880 ev.peer_cert.hash = hash;
1881 ev.peer_cert.hash_len = sizeof(hash);
1884 #endif /* CONFIG_SHA256 */
1885 ev.peer_cert.depth = depth;
1886 ev.peer_cert.subject = subject;
1888 ser = X509_get_serialNumber(err_cert);
1890 wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
1891 ASN1_STRING_get0_data(ser),
1892 ASN1_STRING_length(ser));
1893 ev.peer_cert.serial_num = serial_num;
1896 ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1897 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1900 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1902 gen = sk_GENERAL_NAME_value(ext, i);
1903 if (gen->type != GEN_EMAIL &&
1904 gen->type != GEN_DNS &&
1905 gen->type != GEN_URI)
1908 pos = os_malloc(10 + gen->d.ia5->length + 1);
1911 altsubject[num_altsubject++] = pos;
1913 switch (gen->type) {
1915 os_memcpy(pos, "EMAIL:", 6);
1919 os_memcpy(pos, "DNS:", 4);
1923 os_memcpy(pos, "URI:", 4);
1928 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1929 pos += gen->d.ia5->length;
1932 sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1934 for (alt = 0; alt < num_altsubject; alt++)
1935 ev.peer_cert.altsubject[alt] = altsubject[alt];
1936 ev.peer_cert.num_altsubject = num_altsubject;
1938 context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1940 for (alt = 0; alt < num_altsubject; alt++)
1941 os_free(altsubject[alt]);
1945 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1951 struct tls_connection *conn;
1952 struct tls_context *context;
1953 char *match, *altmatch, *suffix_match, *domain_match;
1954 const char *err_str;
1956 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1960 err = X509_STORE_CTX_get_error(x509_ctx);
1961 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1962 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1963 SSL_get_ex_data_X509_STORE_CTX_idx());
1964 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1966 conn = SSL_get_app_data(ssl);
1971 conn->peer_cert = err_cert;
1972 else if (depth == 1)
1973 conn->peer_issuer = err_cert;
1974 else if (depth == 2)
1975 conn->peer_issuer_issuer = err_cert;
1977 context = conn->context;
1978 match = conn->subject_match;
1979 altmatch = conn->altsubject_match;
1980 suffix_match = conn->suffix_match;
1981 domain_match = conn->domain_match;
1983 if (!preverify_ok && !conn->ca_cert_verify)
1985 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1987 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1988 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1989 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1990 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1995 err_str = X509_verify_cert_error_string(err);
1997 #ifdef CONFIG_SHA256
1999 * Do not require preverify_ok so we can explicity allow otherwise
2000 * invalid pinned server certificates.
2002 if (depth == 0 && conn->server_cert_only) {
2003 struct wpabuf *cert;
2004 cert = get_x509_cert(err_cert);
2006 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
2007 "server certificate data");
2013 addr[0] = wpabuf_head(cert);
2014 len[0] = wpabuf_len(cert);
2015 if (sha256_vector(1, addr, len, hash) < 0 ||
2016 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
2017 err_str = "Server certificate mismatch";
2018 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2020 } else if (!preverify_ok) {
2022 * Certificate matches pinned certificate, allow
2023 * regardless of other problems.
2025 wpa_printf(MSG_DEBUG,
2026 "OpenSSL: Ignore validation issues for a pinned server certificate");
2032 #endif /* CONFIG_SHA256 */
2034 if (!preverify_ok) {
2035 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
2036 " error %d (%s) depth %d for '%s'", err, err_str,
2038 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2039 err_str, TLS_FAIL_UNSPECIFIED);
2040 return preverify_ok;
2043 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
2044 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
2045 preverify_ok, err, err_str,
2046 conn->ca_cert_verify, depth, buf);
2047 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
2048 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
2049 "match with '%s'", buf, match);
2051 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2053 TLS_FAIL_SUBJECT_MISMATCH);
2054 } else if (depth == 0 && altmatch &&
2055 !tls_match_altsubject(err_cert, altmatch)) {
2056 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
2057 "'%s' not found", altmatch);
2059 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2060 "AltSubject mismatch",
2061 TLS_FAIL_ALTSUBJECT_MISMATCH);
2062 } else if (depth == 0 && suffix_match &&
2063 !tls_match_suffix(err_cert, suffix_match, 0)) {
2064 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
2067 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2068 "Domain suffix mismatch",
2069 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
2070 } else if (depth == 0 && domain_match &&
2071 !tls_match_suffix(err_cert, domain_match, 1)) {
2072 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
2075 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2077 TLS_FAIL_DOMAIN_MISMATCH);
2079 openssl_tls_cert_event(conn, err_cert, depth, buf);
2081 if (conn->cert_probe && preverify_ok && depth == 0) {
2082 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
2083 "on probe-only run");
2085 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2086 "Server certificate chain probe",
2087 TLS_FAIL_SERVER_CHAIN_PROBE);
2090 #ifdef CONFIG_SUITEB
2091 if (conn->flags & TLS_CONN_SUITEB) {
2096 pk = X509_get_pubkey(err_cert);
2098 rsa = EVP_PKEY_get1_RSA(pk);
2100 len = RSA_bits(rsa);
2107 wpa_printf(MSG_DEBUG,
2108 "OpenSSL: RSA modulus size: %d bits", len);
2111 openssl_tls_fail_event(
2112 conn, err_cert, err,
2114 "Insufficient RSA modulus size",
2115 TLS_FAIL_INSUFFICIENT_KEY_LEN);
2119 #endif /* CONFIG_SUITEB */
2121 #ifdef OPENSSL_IS_BORINGSSL
2122 if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
2124 enum ocsp_result res;
2126 res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
2128 conn->peer_issuer_issuer);
2129 if (res == OCSP_REVOKED) {
2131 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2132 "certificate revoked",
2134 if (err == X509_V_OK)
2135 X509_STORE_CTX_set_error(
2136 x509_ctx, X509_V_ERR_CERT_REVOKED);
2137 } else if (res != OCSP_GOOD &&
2138 (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
2140 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2141 "bad certificate status response",
2142 TLS_FAIL_UNSPECIFIED);
2145 #endif /* OPENSSL_IS_BORINGSSL */
2147 if (depth == 0 && preverify_ok && context->event_cb != NULL)
2148 context->event_cb(context->cb_ctx,
2149 TLS_CERT_CHAIN_SUCCESS, NULL);
2151 return preverify_ok;
2155 #ifndef OPENSSL_NO_STDIO
2156 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
2158 SSL_CTX *ssl_ctx = data->ssl;
2159 X509_LOOKUP *lookup;
2162 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
2163 X509_LOOKUP_file());
2164 if (lookup == NULL) {
2165 tls_show_errors(MSG_WARNING, __func__,
2166 "Failed add lookup for X509 store");
2170 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
2171 unsigned long err = ERR_peek_error();
2172 tls_show_errors(MSG_WARNING, __func__,
2173 "Failed load CA in DER format");
2174 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2175 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2176 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2177 "cert already in hash table error",
2185 #endif /* OPENSSL_NO_STDIO */
2188 static int tls_connection_ca_cert(struct tls_data *data,
2189 struct tls_connection *conn,
2190 const char *ca_cert, const u8 *ca_cert_blob,
2191 size_t ca_cert_blob_len, const char *ca_path)
2193 SSL_CTX *ssl_ctx = data->ssl;
2197 * Remove previously configured trusted CA certificates before adding
2200 store = X509_STORE_new();
2201 if (store == NULL) {
2202 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2203 "certificate store", __func__);
2206 SSL_CTX_set_cert_store(ssl_ctx, store);
2208 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2209 conn->ca_cert_verify = 1;
2211 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
2212 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
2214 conn->cert_probe = 1;
2215 conn->ca_cert_verify = 0;
2219 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
2220 #ifdef CONFIG_SHA256
2221 const char *pos = ca_cert + 7;
2222 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
2223 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
2224 "hash value '%s'", ca_cert);
2228 if (os_strlen(pos) != 32 * 2) {
2229 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
2230 "hash length in ca_cert '%s'", ca_cert);
2233 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
2234 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
2235 "value in ca_cert '%s'", ca_cert);
2238 conn->server_cert_only = 1;
2239 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
2240 "certificate match");
2242 #else /* CONFIG_SHA256 */
2243 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
2244 "cannot validate server certificate hash");
2246 #endif /* CONFIG_SHA256 */
2250 X509 *cert = d2i_X509(NULL,
2251 (const unsigned char **) &ca_cert_blob,
2254 tls_show_errors(MSG_WARNING, __func__,
2255 "Failed to parse ca_cert_blob");
2259 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
2261 unsigned long err = ERR_peek_error();
2262 tls_show_errors(MSG_WARNING, __func__,
2263 "Failed to add ca_cert_blob to "
2264 "certificate store");
2265 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2266 ERR_GET_REASON(err) ==
2267 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2268 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2269 "cert already in hash table error",
2277 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
2278 "to certificate store", __func__);
2284 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
2285 if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
2288 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2292 /* Multiple aliases separated by space */
2293 if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
2294 char *aliases = os_strdup(&ca_cert[12]);
2295 const char *delim = " ";
2302 alias = strtok_r(aliases, delim, &savedptr);
2303 for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
2304 if (tls_add_ca_from_keystore_encoded(
2305 SSL_CTX_get_cert_store(ssl_ctx), alias)) {
2306 wpa_printf(MSG_WARNING,
2307 "OpenSSL: %s - Failed to add ca_cert %s from keystore",
2317 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2320 #endif /* ANDROID */
2322 #ifdef CONFIG_NATIVE_WINDOWS
2323 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
2325 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
2326 "system certificate store");
2329 #endif /* CONFIG_NATIVE_WINDOWS */
2331 if (ca_cert || ca_path) {
2332 #ifndef OPENSSL_NO_STDIO
2333 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
2335 tls_show_errors(MSG_WARNING, __func__,
2336 "Failed to load root certificates");
2338 tls_load_ca_der(data, ca_cert) == 0) {
2339 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
2340 "DER format CA certificate",
2345 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2346 "certificate(s) loaded");
2347 tls_get_errors(data);
2349 #else /* OPENSSL_NO_STDIO */
2350 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2353 #endif /* OPENSSL_NO_STDIO */
2355 /* No ca_cert configured - do not try to verify server
2357 conn->ca_cert_verify = 0;
2364 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
2366 SSL_CTX *ssl_ctx = data->ssl;
2369 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
2371 tls_show_errors(MSG_WARNING, __func__,
2372 "Failed to load root certificates");
2376 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2377 "certificate(s) loaded");
2379 #ifndef OPENSSL_NO_STDIO
2380 /* Add the same CAs to the client certificate requests */
2381 SSL_CTX_set_client_CA_list(ssl_ctx,
2382 SSL_load_client_CA_file(ca_cert));
2383 #endif /* OPENSSL_NO_STDIO */
2390 int tls_global_set_verify(void *ssl_ctx, int check_crl)
2395 struct tls_data *data = ssl_ctx;
2396 X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
2398 tls_show_errors(MSG_INFO, __func__, "Failed to get "
2399 "certificate store when enabling "
2403 flags = X509_V_FLAG_CRL_CHECK;
2405 flags |= X509_V_FLAG_CRL_CHECK_ALL;
2406 X509_STORE_set_flags(cs, flags);
2412 static int tls_connection_set_subject_match(struct tls_connection *conn,
2413 const char *subject_match,
2414 const char *altsubject_match,
2415 const char *suffix_match,
2416 const char *domain_match)
2418 os_free(conn->subject_match);
2419 conn->subject_match = NULL;
2420 if (subject_match) {
2421 conn->subject_match = os_strdup(subject_match);
2422 if (conn->subject_match == NULL)
2426 os_free(conn->altsubject_match);
2427 conn->altsubject_match = NULL;
2428 if (altsubject_match) {
2429 conn->altsubject_match = os_strdup(altsubject_match);
2430 if (conn->altsubject_match == NULL)
2434 os_free(conn->suffix_match);
2435 conn->suffix_match = NULL;
2437 conn->suffix_match = os_strdup(suffix_match);
2438 if (conn->suffix_match == NULL)
2442 os_free(conn->domain_match);
2443 conn->domain_match = NULL;
2445 conn->domain_match = os_strdup(domain_match);
2446 if (conn->domain_match == NULL)
2454 #ifdef CONFIG_SUITEB
2455 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2456 static int suiteb_cert_cb(SSL *ssl, void *arg)
2458 struct tls_connection *conn = arg;
2461 * This cert_cb() is not really the best location for doing a
2462 * constraint check for the ServerKeyExchange message, but this seems to
2463 * be the only place where the current OpenSSL sequence can be
2464 * terminated cleanly with an TLS alert going out to the server.
2467 if (!(conn->flags & TLS_CONN_SUITEB))
2470 /* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
2471 if (conn->cipher_suite != 0x9f)
2474 if (conn->server_dh_prime_len >= 3072)
2477 wpa_printf(MSG_DEBUG,
2478 "OpenSSL: Server DH prime length (%d bits) not sufficient for Suite B RSA - reject handshake",
2479 conn->server_dh_prime_len);
2482 #endif /* OPENSSL_VERSION_NUMBER */
2483 #endif /* CONFIG_SUITEB */
2486 static int tls_set_conn_flags(struct tls_connection *conn, unsigned int flags,
2487 const char *openssl_ciphers)
2489 SSL *ssl = conn->ssl;
2491 #ifdef SSL_OP_NO_TICKET
2492 if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
2493 SSL_set_options(ssl, SSL_OP_NO_TICKET);
2495 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
2496 #endif /* SSL_OP_NO_TICKET */
2498 #ifdef SSL_OP_NO_TLSv1
2499 if (flags & TLS_CONN_DISABLE_TLSv1_0)
2500 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2502 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
2503 #endif /* SSL_OP_NO_TLSv1 */
2504 #ifdef SSL_OP_NO_TLSv1_1
2505 if (flags & TLS_CONN_DISABLE_TLSv1_1)
2506 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2508 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
2509 #endif /* SSL_OP_NO_TLSv1_1 */
2510 #ifdef SSL_OP_NO_TLSv1_2
2511 if (flags & TLS_CONN_DISABLE_TLSv1_2)
2512 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
2514 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
2515 #endif /* SSL_OP_NO_TLSv1_2 */
2516 #ifdef SSL_OP_NO_TLSv1_3
2517 if (flags & TLS_CONN_DISABLE_TLSv1_3)
2518 SSL_set_options(ssl, SSL_OP_NO_TLSv1_3);
2520 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_3);
2521 #endif /* SSL_OP_NO_TLSv1_3 */
2522 #ifdef CONFIG_SUITEB
2523 #ifdef OPENSSL_IS_BORINGSSL
2524 /* Start with defaults from BoringSSL */
2525 SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, NULL, 0);
2526 #endif /* OPENSSL_IS_BORINGSSL */
2527 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2528 if (flags & TLS_CONN_SUITEB_NO_ECDH) {
2529 const char *ciphers = "DHE-RSA-AES256-GCM-SHA384";
2531 if (openssl_ciphers) {
2532 wpa_printf(MSG_DEBUG,
2533 "OpenSSL: Override ciphers for Suite B (no ECDH): %s",
2535 ciphers = openssl_ciphers;
2537 if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2538 wpa_printf(MSG_INFO,
2539 "OpenSSL: Failed to set Suite B ciphers");
2542 } else if (flags & TLS_CONN_SUITEB) {
2544 const char *ciphers =
2545 "ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384";
2546 int nid[1] = { NID_secp384r1 };
2548 if (openssl_ciphers) {
2549 wpa_printf(MSG_DEBUG,
2550 "OpenSSL: Override ciphers for Suite B: %s",
2552 ciphers = openssl_ciphers;
2554 if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2555 wpa_printf(MSG_INFO,
2556 "OpenSSL: Failed to set Suite B ciphers");
2560 if (SSL_set1_curves(ssl, nid, 1) != 1) {
2561 wpa_printf(MSG_INFO,
2562 "OpenSSL: Failed to set Suite B curves");
2566 ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
2567 if (!ecdh || SSL_set_tmp_ecdh(ssl, ecdh) != 1) {
2569 wpa_printf(MSG_INFO,
2570 "OpenSSL: Failed to set ECDH parameter");
2575 if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
2576 #ifdef OPENSSL_IS_BORINGSSL
2577 uint16_t sigalgs[1] = { SSL_SIGN_RSA_PKCS1_SHA384 };
2579 if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
2581 wpa_printf(MSG_INFO,
2582 "OpenSSL: Failed to set Suite B sigalgs");
2585 #else /* OPENSSL_IS_BORINGSSL */
2586 /* ECDSA+SHA384 if need to add EC support here */
2587 if (SSL_set1_sigalgs_list(ssl, "RSA+SHA384") != 1) {
2588 wpa_printf(MSG_INFO,
2589 "OpenSSL: Failed to set Suite B sigalgs");
2592 #endif /* OPENSSL_IS_BORINGSSL */
2594 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2595 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2596 SSL_set_cert_cb(ssl, suiteb_cert_cb, conn);
2598 #else /* OPENSSL_VERSION_NUMBER < 0x10002000L */
2599 if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
2600 wpa_printf(MSG_ERROR,
2601 "OpenSSL: Suite B RSA case not supported with this OpenSSL version");
2604 #endif /* OPENSSL_VERSION_NUMBER */
2606 #ifdef OPENSSL_IS_BORINGSSL
2607 if (openssl_ciphers && os_strcmp(openssl_ciphers, "SUITEB192") == 0) {
2608 uint16_t sigalgs[1] = { SSL_SIGN_ECDSA_SECP384R1_SHA384 };
2609 int nid[1] = { NID_secp384r1 };
2611 if (SSL_set1_curves(ssl, nid, 1) != 1) {
2612 wpa_printf(MSG_INFO,
2613 "OpenSSL: Failed to set Suite B curves");
2617 if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
2619 wpa_printf(MSG_INFO,
2620 "OpenSSL: Failed to set Suite B sigalgs");
2624 #endif /* OPENSSL_IS_BORINGSSL */
2625 #endif /* CONFIG_SUITEB */
2631 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
2632 int verify_peer, unsigned int flags,
2633 const u8 *session_ctx, size_t session_ctx_len)
2635 static int counter = 0;
2636 struct tls_data *data = ssl_ctx;
2642 conn->ca_cert_verify = 1;
2643 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
2644 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
2645 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
2647 conn->ca_cert_verify = 0;
2648 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
2651 if (tls_set_conn_flags(conn, flags, NULL) < 0)
2653 conn->flags = flags;
2655 SSL_set_accept_state(conn->ssl);
2657 if (data->tls_session_lifetime == 0) {
2659 * Set session id context to a unique value to make sure
2660 * session resumption cannot be used either through session
2661 * caching or TLS ticket extension.
2664 SSL_set_session_id_context(conn->ssl,
2665 (const unsigned char *) &counter,
2667 } else if (session_ctx) {
2668 SSL_set_session_id_context(conn->ssl, session_ctx,
2676 static int tls_connection_client_cert(struct tls_connection *conn,
2677 const char *client_cert,
2678 const u8 *client_cert_blob,
2679 size_t client_cert_blob_len)
2681 if (client_cert == NULL && client_cert_blob == NULL)
2685 #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
2687 * Clear previously set extra chain certificates, if any, from PKCS#12
2688 * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
2691 SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
2692 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
2693 #endif /* PKCS12_FUNCS */
2695 if (client_cert_blob &&
2696 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
2697 client_cert_blob_len) == 1) {
2698 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
2701 } else if (client_cert_blob) {
2702 tls_show_errors(MSG_DEBUG, __func__,
2703 "SSL_use_certificate_ASN1 failed");
2706 if (client_cert == NULL)
2710 if (os_strncmp("keystore://", client_cert, 11) == 0) {
2711 BIO *bio = BIO_from_keystore(&client_cert[11]);
2715 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2718 if (SSL_use_certificate(conn->ssl, x509) == 1)
2723 /* Read additional certificates into the chain. */
2725 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2727 /* Takes ownership of x509 */
2728 SSL_add0_chain_cert(conn->ssl, x509);
2736 #endif /* ANDROID */
2738 #ifndef OPENSSL_NO_STDIO
2739 if (SSL_use_certificate_file(conn->ssl, client_cert,
2740 SSL_FILETYPE_ASN1) == 1) {
2741 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2746 if (SSL_use_certificate_file(conn->ssl, client_cert,
2747 SSL_FILETYPE_PEM) == 1) {
2749 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2754 tls_show_errors(MSG_DEBUG, __func__,
2755 "SSL_use_certificate_file failed");
2756 #else /* OPENSSL_NO_STDIO */
2757 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2758 #endif /* OPENSSL_NO_STDIO */
2764 static int tls_global_client_cert(struct tls_data *data,
2765 const char *client_cert)
2767 #ifndef OPENSSL_NO_STDIO
2768 SSL_CTX *ssl_ctx = data->ssl;
2770 if (client_cert == NULL)
2773 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2774 SSL_FILETYPE_ASN1) != 1 &&
2775 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2776 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2777 SSL_FILETYPE_PEM) != 1) {
2778 tls_show_errors(MSG_INFO, __func__,
2779 "Failed to load client certificate");
2783 #else /* OPENSSL_NO_STDIO */
2784 if (client_cert == NULL)
2786 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2788 #endif /* OPENSSL_NO_STDIO */
2793 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
2798 STACK_OF(X509) *certs;
2807 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2808 tls_show_errors(MSG_DEBUG, __func__,
2809 "Failed to parse PKCS12 file");
2813 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2816 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2818 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2819 "subject='%s'", buf);
2821 if (SSL_use_certificate(ssl, cert) != 1)
2824 if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
2831 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2833 if (SSL_use_PrivateKey(ssl, pkey) != 1)
2836 if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
2839 EVP_PKEY_free(pkey);
2843 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
2845 SSL_clear_chain_certs(ssl);
2847 SSL_CTX_clear_chain_certs(data->ssl);
2848 while ((cert = sk_X509_pop(certs)) != NULL) {
2849 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2851 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2852 " from PKCS12: subject='%s'", buf);
2853 if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
2854 (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
2856 tls_show_errors(MSG_DEBUG, __func__,
2857 "Failed to add additional certificate");
2865 /* Try to continue anyway */
2867 sk_X509_pop_free(certs, X509_free);
2868 #ifndef OPENSSL_IS_BORINGSSL
2870 res = SSL_build_cert_chain(
2872 SSL_BUILD_CHAIN_FLAG_CHECK |
2873 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2875 res = SSL_CTX_build_cert_chain(
2877 SSL_BUILD_CHAIN_FLAG_CHECK |
2878 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2880 tls_show_errors(MSG_DEBUG, __func__,
2881 "Failed to build certificate chain");
2882 } else if (res == 2) {
2883 wpa_printf(MSG_DEBUG,
2884 "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2886 #endif /* OPENSSL_IS_BORINGSSL */
2888 * Try to continue regardless of result since it is possible for
2889 * the extra certificates not to be required.
2892 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2893 SSL_CTX_clear_extra_chain_certs(data->ssl);
2894 while ((cert = sk_X509_pop(certs)) != NULL) {
2895 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2897 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2898 " from PKCS12: subject='%s'", buf);
2900 * There is no SSL equivalent for the chain cert - so
2901 * always add it to the context...
2903 if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
2910 sk_X509_pop_free(certs, X509_free);
2911 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2917 tls_get_errors(data);
2921 #endif /* PKCS12_FUNCS */
2924 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
2925 const char *private_key, const char *passwd)
2931 f = fopen(private_key, "rb");
2935 p12 = d2i_PKCS12_fp(f, NULL);
2939 tls_show_errors(MSG_INFO, __func__,
2940 "Failed to use PKCS#12 file");
2944 return tls_parse_pkcs12(data, ssl, p12, passwd);
2946 #else /* PKCS12_FUNCS */
2947 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2950 #endif /* PKCS12_FUNCS */
2954 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
2955 const u8 *blob, size_t len, const char *passwd)
2960 p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2962 tls_show_errors(MSG_INFO, __func__,
2963 "Failed to use PKCS#12 blob");
2967 return tls_parse_pkcs12(data, ssl, p12, passwd);
2969 #else /* PKCS12_FUNCS */
2970 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2973 #endif /* PKCS12_FUNCS */
2977 #ifndef OPENSSL_NO_ENGINE
2978 static int tls_engine_get_cert(struct tls_connection *conn,
2979 const char *cert_id,
2982 /* this runs after the private key is loaded so no PIN is required */
2984 const char *cert_id;
2987 params.cert_id = cert_id;
2990 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2991 0, ¶ms, NULL, 1)) {
2992 unsigned long err = ERR_get_error();
2994 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2995 " '%s' [%s]", cert_id,
2996 ERR_error_string(err, NULL));
2997 if (tls_is_pin_error(err))
2998 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2999 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3002 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
3004 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3006 *cert = params.cert;
3009 #endif /* OPENSSL_NO_ENGINE */
3012 static int tls_connection_engine_client_cert(struct tls_connection *conn,
3013 const char *cert_id)
3015 #ifndef OPENSSL_NO_ENGINE
3018 if (tls_engine_get_cert(conn, cert_id, &cert))
3021 if (!SSL_use_certificate(conn->ssl, cert)) {
3022 tls_show_errors(MSG_ERROR, __func__,
3023 "SSL_use_certificate failed");
3028 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
3032 #else /* OPENSSL_NO_ENGINE */
3034 #endif /* OPENSSL_NO_ENGINE */
3038 static int tls_connection_engine_ca_cert(struct tls_data *data,
3039 struct tls_connection *conn,
3040 const char *ca_cert_id)
3042 #ifndef OPENSSL_NO_ENGINE
3044 SSL_CTX *ssl_ctx = data->ssl;
3047 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
3050 /* start off the same as tls_connection_ca_cert */
3051 store = X509_STORE_new();
3052 if (store == NULL) {
3053 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
3054 "certificate store", __func__);
3058 SSL_CTX_set_cert_store(ssl_ctx, store);
3059 if (!X509_STORE_add_cert(store, cert)) {
3060 unsigned long err = ERR_peek_error();
3061 tls_show_errors(MSG_WARNING, __func__,
3062 "Failed to add CA certificate from engine "
3063 "to certificate store");
3064 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
3065 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
3066 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
3067 " already in hash table error",
3075 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
3076 "to certificate store", __func__);
3077 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3078 conn->ca_cert_verify = 1;
3082 #else /* OPENSSL_NO_ENGINE */
3084 #endif /* OPENSSL_NO_ENGINE */
3088 static int tls_connection_engine_private_key(struct tls_connection *conn)
3090 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
3091 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
3092 tls_show_errors(MSG_ERROR, __func__,
3093 "ENGINE: cannot use private key for TLS");
3096 if (!SSL_check_private_key(conn->ssl)) {
3097 tls_show_errors(MSG_INFO, __func__,
3098 "Private key failed verification");
3102 #else /* OPENSSL_NO_ENGINE */
3103 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
3104 "engine support was not compiled in");
3106 #endif /* OPENSSL_NO_ENGINE */
3110 #ifndef OPENSSL_NO_STDIO
3111 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
3115 os_strlcpy(buf, (const char *) password, size);
3116 return os_strlen(buf);
3118 #endif /* OPENSSL_NO_STDIO */
3121 static int tls_use_private_key_file(struct tls_data *data, SSL *ssl,
3122 const char *private_key,
3123 const char *private_key_passwd)
3125 #ifndef OPENSSL_NO_STDIO
3130 /* First try ASN.1 (DER). */
3131 bio = BIO_new_file(private_key, "r");
3134 pkey = d2i_PrivateKey_bio(bio, NULL);
3138 wpa_printf(MSG_DEBUG, "OpenSSL: %s (DER) --> loaded", __func__);
3140 /* Try PEM with the provided password. */
3141 bio = BIO_new_file(private_key, "r");
3144 pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_passwd_cb,
3145 (void *) private_key_passwd);
3149 wpa_printf(MSG_DEBUG, "OpenSSL: %s (PEM) --> loaded", __func__);
3150 /* Clear errors from the previous failed load. */
3155 ret = SSL_use_PrivateKey(ssl, pkey);
3157 ret = SSL_CTX_use_PrivateKey(data->ssl, pkey);
3159 EVP_PKEY_free(pkey);
3160 return ret == 1 ? 0 : -1;
3161 #else /* OPENSSL_NO_STDIO */
3162 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3164 #endif /* OPENSSL_NO_STDIO */
3168 static int tls_connection_private_key(struct tls_data *data,
3169 struct tls_connection *conn,
3170 const char *private_key,
3171 const char *private_key_passwd,
3172 const u8 *private_key_blob,
3173 size_t private_key_blob_len)
3177 if (private_key == NULL && private_key_blob == NULL)
3181 while (private_key_blob) {
3182 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
3183 (u8 *) private_key_blob,
3184 private_key_blob_len) == 1) {
3185 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3186 "ASN1(EVP_PKEY_RSA) --> OK");
3191 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
3192 (u8 *) private_key_blob,
3193 private_key_blob_len) == 1) {
3194 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3195 "ASN1(EVP_PKEY_DSA) --> OK");
3200 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
3201 (u8 *) private_key_blob,
3202 private_key_blob_len) == 1) {
3203 wpa_printf(MSG_DEBUG, "OpenSSL: "
3204 "SSL_use_RSAPrivateKey_ASN1 --> OK");
3209 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
3210 private_key_blob_len,
3211 private_key_passwd) == 0) {
3212 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
3221 while (!ok && private_key) {
3222 if (tls_use_private_key_file(data, conn->ssl, private_key,
3223 private_key_passwd) == 0) {
3228 if (tls_read_pkcs12(data, conn->ssl, private_key,
3229 private_key_passwd) == 0) {
3230 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
3236 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
3237 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
3238 "access certificate store --> OK");
3247 tls_show_errors(MSG_INFO, __func__,
3248 "Failed to load private key");
3253 if (!SSL_check_private_key(conn->ssl)) {
3254 tls_show_errors(MSG_INFO, __func__, "Private key failed "
3259 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
3264 static int tls_global_private_key(struct tls_data *data,
3265 const char *private_key,
3266 const char *private_key_passwd)
3268 SSL_CTX *ssl_ctx = data->ssl;
3270 if (private_key == NULL)
3273 if (tls_use_private_key_file(data, NULL, private_key,
3274 private_key_passwd) &&
3275 tls_read_pkcs12(data, NULL, private_key, private_key_passwd)) {
3276 tls_show_errors(MSG_INFO, __func__,
3277 "Failed to load private key");
3283 if (!SSL_CTX_check_private_key(ssl_ctx)) {
3284 tls_show_errors(MSG_INFO, __func__,
3285 "Private key failed verification");
3293 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
3295 #ifdef OPENSSL_NO_DH
3296 if (dh_file == NULL)
3298 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3299 "dh_file specified");
3301 #else /* OPENSSL_NO_DH */
3305 /* TODO: add support for dh_blob */
3306 if (dh_file == NULL)
3311 bio = BIO_new_file(dh_file, "r");
3313 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3314 dh_file, ERR_error_string(ERR_get_error(), NULL));
3317 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3319 #ifndef OPENSSL_NO_DSA
3320 while (dh == NULL) {
3322 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3323 " trying to parse as DSA params", dh_file,
3324 ERR_error_string(ERR_get_error(), NULL));
3325 bio = BIO_new_file(dh_file, "r");
3328 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3331 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3332 "'%s': %s", dh_file,
3333 ERR_error_string(ERR_get_error(), NULL));
3337 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3338 dh = DSA_dup_DH(dsa);
3341 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3342 "params into DH params");
3347 #endif /* !OPENSSL_NO_DSA */
3349 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3354 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
3355 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3357 ERR_error_string(ERR_get_error(), NULL));
3363 #endif /* OPENSSL_NO_DH */
3367 static int tls_global_dh(struct tls_data *data, const char *dh_file)
3369 #ifdef OPENSSL_NO_DH
3370 if (dh_file == NULL)
3372 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3373 "dh_file specified");
3375 #else /* OPENSSL_NO_DH */
3376 SSL_CTX *ssl_ctx = data->ssl;
3380 /* TODO: add support for dh_blob */
3381 if (dh_file == NULL)
3383 if (ssl_ctx == NULL)
3386 bio = BIO_new_file(dh_file, "r");
3388 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3389 dh_file, ERR_error_string(ERR_get_error(), NULL));
3392 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3394 #ifndef OPENSSL_NO_DSA
3395 while (dh == NULL) {
3397 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3398 " trying to parse as DSA params", dh_file,
3399 ERR_error_string(ERR_get_error(), NULL));
3400 bio = BIO_new_file(dh_file, "r");
3403 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3406 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3407 "'%s': %s", dh_file,
3408 ERR_error_string(ERR_get_error(), NULL));
3412 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3413 dh = DSA_dup_DH(dsa);
3416 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3417 "params into DH params");
3422 #endif /* !OPENSSL_NO_DSA */
3424 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3429 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
3430 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3432 ERR_error_string(ERR_get_error(), NULL));
3438 #endif /* OPENSSL_NO_DH */
3442 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
3443 struct tls_random *keys)
3447 if (conn == NULL || keys == NULL)
3453 os_memset(keys, 0, sizeof(*keys));
3454 keys->client_random = conn->client_random;
3455 keys->client_random_len = SSL_get_client_random(
3456 ssl, conn->client_random, sizeof(conn->client_random));
3457 keys->server_random = conn->server_random;
3458 keys->server_random_len = SSL_get_server_random(
3459 ssl, conn->server_random, sizeof(conn->server_random));
3465 #ifdef OPENSSL_NEED_EAP_FAST_PRF
3466 static int openssl_get_keyblock_size(SSL *ssl)
3468 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
3469 (defined(LIBRESSL_VERSION_NUMBER) && \
3470 LIBRESSL_VERSION_NUMBER < 0x20700000L)
3471 const EVP_CIPHER *c;
3475 if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
3476 ssl->read_hash == NULL)
3479 c = ssl->enc_read_ctx->cipher;
3480 h = EVP_MD_CTX_md(ssl->read_hash);
3482 md_size = EVP_MD_size(h);
3484 md_size = ssl->s3->tmp.new_mac_secret_size;
3488 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
3489 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
3490 EVP_CIPHER_iv_length(c));
3491 return 2 * (EVP_CIPHER_key_length(c) +
3493 EVP_CIPHER_iv_length(c));
3495 const SSL_CIPHER *ssl_cipher;
3497 const EVP_CIPHER *c;
3500 ssl_cipher = SSL_get_current_cipher(ssl);
3503 cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
3504 digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
3505 wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
3507 if (cipher < 0 || digest < 0)
3509 c = EVP_get_cipherbynid(cipher);
3510 h = EVP_get_digestbynid(digest);
3514 wpa_printf(MSG_DEBUG,
3515 "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
3516 EVP_CIPHER_key_length(c), EVP_MD_size(h),
3517 EVP_CIPHER_iv_length(c));
3518 return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
3519 EVP_CIPHER_iv_length(c));
3522 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
3525 int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
3526 const char *label, u8 *out, size_t out_len)
3529 SSL_export_keying_material(conn->ssl, out, out_len, label,
3530 os_strlen(label), NULL, 0, 0) != 1)
3536 int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
3537 u8 *out, size_t out_len)
3539 #ifdef OPENSSL_NEED_EAP_FAST_PRF
3547 unsigned char client_random[SSL3_RANDOM_SIZE];
3548 unsigned char server_random[SSL3_RANDOM_SIZE];
3549 unsigned char master_key[64];
3550 size_t master_key_len;
3554 * TLS library did not support EAP-FAST key generation, so get the
3555 * needed TLS session parameters and use an internal implementation of
3556 * TLS PRF to derive the key.
3564 ver = SSL_get_version(ssl);
3565 sess = SSL_get_session(ssl);
3569 skip = openssl_get_keyblock_size(ssl);
3572 tmp_out = os_malloc(skip + out_len);
3577 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
3583 SSL_get_client_random(ssl, client_random, sizeof(client_random));
3584 SSL_get_server_random(ssl, server_random, sizeof(server_random));
3585 master_key_len = SSL_SESSION_get_master_key(sess, master_key,
3586 sizeof(master_key));
3588 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
3589 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
3591 if (os_strcmp(ver, "TLSv1.2") == 0) {
3592 tls_prf_sha256(master_key, master_key_len,
3593 "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
3594 _out, skip + out_len);
3596 } else if (tls_prf_sha1_md5(master_key, master_key_len,
3597 "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
3598 _out, skip + out_len) == 0) {
3601 os_memset(master_key, 0, sizeof(master_key));
3604 os_memcpy(out, _out + skip, out_len);
3605 bin_clear_free(tmp_out, skip);
3608 #else /* OPENSSL_NEED_EAP_FAST_PRF */
3609 wpa_printf(MSG_ERROR,
3610 "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
3612 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
3616 static struct wpabuf *
3617 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data)
3620 struct wpabuf *out_data;
3623 * Give TLS handshake data from the server (if available) to OpenSSL
3626 if (in_data && wpabuf_len(in_data) > 0 &&
3627 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
3629 tls_show_errors(MSG_INFO, __func__,
3630 "Handshake failed - BIO_write");
3634 /* Initiate TLS handshake or continue the existing handshake */
3636 res = SSL_accept(conn->ssl);
3638 res = SSL_connect(conn->ssl);
3640 int err = SSL_get_error(conn->ssl, res);
3641 if (err == SSL_ERROR_WANT_READ)
3642 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
3644 else if (err == SSL_ERROR_WANT_WRITE)
3645 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
3648 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
3650 if (!conn->server && !conn->client_hello_generated) {
3651 /* The server would not understand TLS Alert
3652 * before ClientHello, so simply terminate
3653 * handshake on this type of error case caused
3654 * by a likely internal error like no ciphers
3656 wpa_printf(MSG_DEBUG,
3657 "OpenSSL: Could not generate ClientHello");
3658 conn->write_alerts++;
3664 if (!conn->server && !conn->failed)
3665 conn->client_hello_generated = 1;
3667 #ifdef CONFIG_SUITEB
3668 if ((conn->flags & TLS_CONN_SUITEB) && !conn->server &&
3669 os_strncmp(SSL_get_cipher(conn->ssl), "DHE-", 4) == 0 &&
3670 conn->server_dh_prime_len < 3072) {
3671 struct tls_context *context = conn->context;
3674 * This should not be reached since earlier cert_cb should have
3675 * terminated the handshake. Keep this check here for extra
3676 * protection if anything goes wrong with the more low-level
3677 * checks based on having to parse the TLS handshake messages.
3679 wpa_printf(MSG_DEBUG,
3680 "OpenSSL: Server DH prime length: %d bits",
3681 conn->server_dh_prime_len);
3683 if (context->event_cb) {
3684 union tls_event_data ev;
3686 os_memset(&ev, 0, sizeof(ev));
3687 ev.alert.is_local = 1;
3688 ev.alert.type = "fatal";
3689 ev.alert.description = "insufficient security";
3690 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
3693 * Could send a TLS Alert to the server, but for now, simply
3694 * terminate handshake.
3697 conn->write_alerts++;
3700 #endif /* CONFIG_SUITEB */
3702 /* Get the TLS handshake data to be sent to the server */
3703 res = BIO_ctrl_pending(conn->ssl_out);
3704 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
3705 out_data = wpabuf_alloc(res);
3706 if (out_data == NULL) {
3707 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
3708 "handshake output (%d bytes)", res);
3709 if (BIO_reset(conn->ssl_out) < 0) {
3710 tls_show_errors(MSG_INFO, __func__,
3711 "BIO_reset failed");
3715 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
3718 tls_show_errors(MSG_INFO, __func__,
3719 "Handshake failed - BIO_read");
3720 if (BIO_reset(conn->ssl_out) < 0) {
3721 tls_show_errors(MSG_INFO, __func__,
3722 "BIO_reset failed");
3724 wpabuf_free(out_data);
3727 wpabuf_put(out_data, res);
3733 static struct wpabuf *
3734 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
3736 struct wpabuf *appl_data;
3739 appl_data = wpabuf_alloc(max_len + 100);
3740 if (appl_data == NULL)
3743 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
3744 wpabuf_size(appl_data));
3746 int err = SSL_get_error(conn->ssl, res);
3747 if (err == SSL_ERROR_WANT_READ ||
3748 err == SSL_ERROR_WANT_WRITE) {
3749 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
3752 tls_show_errors(MSG_INFO, __func__,
3753 "Failed to read possible "
3754 "Application Data");
3756 wpabuf_free(appl_data);
3760 wpabuf_put(appl_data, res);
3761 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
3762 "message", appl_data);
3768 static struct wpabuf *
3769 openssl_connection_handshake(struct tls_connection *conn,
3770 const struct wpabuf *in_data,
3771 struct wpabuf **appl_data)
3773 struct wpabuf *out_data;
3778 out_data = openssl_handshake(conn, in_data);
3779 if (out_data == NULL)
3781 if (conn->invalid_hb_used) {
3782 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3783 wpabuf_free(out_data);
3787 if (SSL_is_init_finished(conn->ssl)) {
3788 wpa_printf(MSG_DEBUG,
3789 "OpenSSL: Handshake finished - resumed=%d",
3790 tls_connection_resumed(conn->ssl_ctx, conn));
3791 if (appl_data && in_data)
3792 *appl_data = openssl_get_appl_data(conn,
3793 wpabuf_len(in_data));
3796 if (conn->invalid_hb_used) {
3797 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3799 wpabuf_free(*appl_data);
3802 wpabuf_free(out_data);
3811 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
3812 const struct wpabuf *in_data,
3813 struct wpabuf **appl_data)
3815 return openssl_connection_handshake(conn, in_data, appl_data);
3819 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
3820 struct tls_connection *conn,
3821 const struct wpabuf *in_data,
3822 struct wpabuf **appl_data)
3825 return openssl_connection_handshake(conn, in_data, appl_data);
3829 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
3830 struct tls_connection *conn,
3831 const struct wpabuf *in_data)
3839 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3840 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
3841 (res = BIO_reset(conn->ssl_out)) < 0) {
3842 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3845 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
3847 tls_show_errors(MSG_INFO, __func__,
3848 "Encryption failed - SSL_write");
3852 /* Read encrypted data to be sent to the server */
3853 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
3856 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
3858 tls_show_errors(MSG_INFO, __func__,
3859 "Encryption failed - BIO_read");
3863 wpabuf_put(buf, res);
3869 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3870 struct tls_connection *conn,
3871 const struct wpabuf *in_data)
3876 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3877 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3878 wpabuf_len(in_data));
3880 tls_show_errors(MSG_INFO, __func__,
3881 "Decryption failed - BIO_write");
3884 if (BIO_reset(conn->ssl_out) < 0) {
3885 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3889 /* Read decrypted data for further processing */
3891 * Even though we try to disable TLS compression, it is possible that
3892 * this cannot be done with all TLS libraries. Add extra buffer space
3893 * to handle the possibility of the decrypted data being longer than
3896 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3899 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3901 tls_show_errors(MSG_INFO, __func__,
3902 "Decryption failed - SSL_read");
3906 wpabuf_put(buf, res);
3908 if (conn->invalid_hb_used) {
3909 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3918 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3920 return conn ? SSL_session_reused(conn->ssl) : 0;
3924 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3927 char buf[500], *pos, *end;
3931 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3936 end = pos + sizeof(buf);
3939 while (*c != TLS_CIPHER_NONE) {
3943 case TLS_CIPHER_RC4_SHA:
3946 case TLS_CIPHER_AES128_SHA:
3947 suite = "AES128-SHA";
3949 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3950 suite = "DHE-RSA-AES128-SHA";
3952 case TLS_CIPHER_ANON_DH_AES128_SHA:
3953 suite = "ADH-AES128-SHA";
3955 case TLS_CIPHER_RSA_DHE_AES256_SHA:
3956 suite = "DHE-RSA-AES256-SHA";
3958 case TLS_CIPHER_AES256_SHA:
3959 suite = "AES256-SHA";
3962 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3963 "cipher selection: %d", *c);
3966 ret = os_snprintf(pos, end - pos, ":%s", suite);
3967 if (os_snprintf_error(end - pos, ret))
3974 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3976 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
3977 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3978 if (os_strstr(buf, ":ADH-")) {
3980 * Need to drop to security level 0 to allow anonymous
3981 * cipher suites for EAP-FAST.
3983 SSL_set_security_level(conn->ssl, 0);
3984 } else if (SSL_get_security_level(conn->ssl) == 0) {
3985 /* Force at least security level 1 */
3986 SSL_set_security_level(conn->ssl, 1);
3988 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3991 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3992 tls_show_errors(MSG_INFO, __func__,
3993 "Cipher suite configuration failed");
4001 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
4002 char *buf, size_t buflen)
4005 if (conn == NULL || conn->ssl == NULL)
4008 name = SSL_get_version(conn->ssl);
4012 os_strlcpy(buf, name, buflen);
4017 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
4018 char *buf, size_t buflen)
4021 if (conn == NULL || conn->ssl == NULL)
4024 name = SSL_get_cipher(conn->ssl);
4028 os_strlcpy(buf, name, buflen);
4033 int tls_connection_enable_workaround(void *ssl_ctx,
4034 struct tls_connection *conn)
4036 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4042 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4043 /* ClientHello TLS extensions require a patch to openssl, so this function is
4044 * commented out unless explicitly needed for EAP-FAST in order to be able to
4045 * build this file with unmodified openssl. */
4046 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
4047 int ext_type, const u8 *data,
4050 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
4053 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
4059 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4062 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
4066 return conn->failed;
4070 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
4074 return conn->read_alerts;
4078 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
4082 return conn->write_alerts;
4088 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
4090 #ifndef CONFIG_NO_STDOUT_DEBUG
4096 if (wpa_debug_level > MSG_DEBUG)
4099 out = BIO_new(BIO_s_mem());
4103 OCSP_RESPONSE_print(out, rsp, 0);
4104 rlen = BIO_ctrl_pending(out);
4105 txt = os_malloc(rlen + 1);
4111 res = BIO_read(out, txt, rlen);
4114 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
4118 #endif /* CONFIG_NO_STDOUT_DEBUG */
4122 static void debug_print_cert(X509 *cert, const char *title)
4124 #ifndef CONFIG_NO_STDOUT_DEBUG
4130 if (wpa_debug_level > MSG_DEBUG)
4133 out = BIO_new(BIO_s_mem());
4137 X509_print(out, cert);
4138 rlen = BIO_ctrl_pending(out);
4139 txt = os_malloc(rlen + 1);
4145 res = BIO_read(out, txt, rlen);
4148 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
4153 #endif /* CONFIG_NO_STDOUT_DEBUG */
4157 static int ocsp_resp_cb(SSL *s, void *arg)
4159 struct tls_connection *conn = arg;
4160 const unsigned char *p;
4161 int len, status, reason, res;
4163 OCSP_BASICRESP *basic;
4165 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
4167 STACK_OF(X509) *certs = NULL;
4169 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
4171 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
4172 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4175 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
4177 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
4179 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
4183 ocsp_debug_print_resp(rsp);
4185 status = OCSP_response_status(rsp);
4186 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
4187 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
4188 status, OCSP_response_status_str(status));
4192 basic = OCSP_response_get1_basic(rsp);
4194 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
4198 store = SSL_CTX_get_cert_store(conn->ssl_ctx);
4199 if (conn->peer_issuer) {
4200 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
4202 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
4203 tls_show_errors(MSG_INFO, __func__,
4204 "OpenSSL: Could not add issuer to certificate store");
4206 certs = sk_X509_new_null();
4209 cert = X509_dup(conn->peer_issuer);
4210 if (cert && !sk_X509_push(certs, cert)) {
4213 "OpenSSL: Could not add issuer to OCSP responder trust store");
4215 sk_X509_free(certs);
4218 if (certs && conn->peer_issuer_issuer) {
4219 cert = X509_dup(conn->peer_issuer_issuer);
4220 if (cert && !sk_X509_push(certs, cert)) {
4223 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
4230 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
4231 sk_X509_pop_free(certs, X509_free);
4233 tls_show_errors(MSG_INFO, __func__,
4234 "OpenSSL: OCSP response failed verification");
4235 OCSP_BASICRESP_free(basic);
4236 OCSP_RESPONSE_free(rsp);
4240 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
4242 if (!conn->peer_cert) {
4243 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
4244 OCSP_BASICRESP_free(basic);
4245 OCSP_RESPONSE_free(rsp);
4249 if (!conn->peer_issuer) {
4250 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
4251 OCSP_BASICRESP_free(basic);
4252 OCSP_RESPONSE_free(rsp);
4256 id = OCSP_cert_to_id(EVP_sha256(), conn->peer_cert, conn->peer_issuer);
4258 wpa_printf(MSG_DEBUG,
4259 "OpenSSL: Could not create OCSP certificate identifier (SHA256)");
4260 OCSP_BASICRESP_free(basic);
4261 OCSP_RESPONSE_free(rsp);
4265 res = OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
4266 &this_update, &next_update);
4268 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
4270 wpa_printf(MSG_DEBUG,
4271 "OpenSSL: Could not create OCSP certificate identifier (SHA1)");
4272 OCSP_BASICRESP_free(basic);
4273 OCSP_RESPONSE_free(rsp);
4277 res = OCSP_resp_find_status(basic, id, &status, &reason,
4278 &produced_at, &this_update,
4283 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
4284 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
4285 " (OCSP not required)");
4286 OCSP_CERTID_free(id);
4287 OCSP_BASICRESP_free(basic);
4288 OCSP_RESPONSE_free(rsp);
4289 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4291 OCSP_CERTID_free(id);
4293 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
4294 tls_show_errors(MSG_INFO, __func__,
4295 "OpenSSL: OCSP status times invalid");
4296 OCSP_BASICRESP_free(basic);
4297 OCSP_RESPONSE_free(rsp);
4301 OCSP_BASICRESP_free(basic);
4302 OCSP_RESPONSE_free(rsp);
4304 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
4305 OCSP_cert_status_str(status));
4307 if (status == V_OCSP_CERTSTATUS_GOOD)
4309 if (status == V_OCSP_CERTSTATUS_REVOKED)
4311 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
4312 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
4315 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
4320 static int ocsp_status_cb(SSL *s, void *arg)
4326 if (tls_global->ocsp_stapling_response == NULL) {
4327 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
4328 return SSL_TLSEXT_ERR_OK;
4331 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
4333 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
4334 /* TODO: Build OCSPResponse with responseStatus = internalError
4336 return SSL_TLSEXT_ERR_OK;
4338 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
4339 tmp = OPENSSL_malloc(len);
4342 return SSL_TLSEXT_ERR_ALERT_FATAL;
4345 os_memcpy(tmp, resp, len);
4347 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
4349 return SSL_TLSEXT_ERR_OK;
4352 #endif /* HAVE_OCSP */
4355 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
4356 const struct tls_connection_params *params)
4358 struct tls_data *data = tls_ctx;
4362 const char *key_id = params->key_id;
4363 const char *cert_id = params->cert_id;
4364 const char *ca_cert_id = params->ca_cert_id;
4365 const char *engine_id = params->engine ? params->engine_id : NULL;
4366 const char *ciphers;
4371 if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
4372 wpa_printf(MSG_INFO,
4373 "OpenSSL: ocsp=3 not supported");
4378 * If the engine isn't explicitly configured, and any of the
4379 * cert/key fields are actually PKCS#11 URIs, then automatically
4380 * use the PKCS#11 ENGINE.
4382 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
4385 if (!key_id && params->private_key && can_pkcs11 &&
4386 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
4388 key_id = params->private_key;
4391 if (!cert_id && params->client_cert && can_pkcs11 &&
4392 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
4394 cert_id = params->client_cert;
4397 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
4398 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
4400 ca_cert_id = params->ca_cert;
4403 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
4404 if (can_pkcs11 == 2 && !engine_id)
4405 engine_id = "pkcs11";
4407 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4408 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
4409 if (params->flags & TLS_CONN_EAP_FAST) {
4410 wpa_printf(MSG_DEBUG,
4411 "OpenSSL: Use TLSv1_method() for EAP-FAST");
4412 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
4413 tls_show_errors(MSG_INFO, __func__,
4414 "Failed to set TLSv1_method() for EAP-FAST");
4419 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
4420 #ifdef SSL_OP_NO_TLSv1_3
4421 if (params->flags & TLS_CONN_EAP_FAST) {
4422 /* Need to disable TLS v1.3 at least for now since OpenSSL 1.1.1
4423 * refuses to start the handshake with the modified ciphersuite
4424 * list (no TLS v1.3 ciphersuites included) for EAP-FAST. */
4425 wpa_printf(MSG_DEBUG, "OpenSSL: Disable TLSv1.3 for EAP-FAST");
4426 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_3);
4428 #endif /* SSL_OP_NO_TLSv1_3 */
4430 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4432 while ((err = ERR_get_error())) {
4433 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
4434 __func__, ERR_error_string(err, NULL));
4438 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
4439 ret = tls_engine_init(conn, engine_id, params->pin,
4440 key_id, cert_id, ca_cert_id);
4444 if (tls_connection_set_subject_match(conn,
4445 params->subject_match,
4446 params->altsubject_match,
4447 params->suffix_match,
4448 params->domain_match))
4451 if (engine_id && ca_cert_id) {
4452 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
4453 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4454 } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
4455 params->ca_cert_blob,
4456 params->ca_cert_blob_len,
4460 if (engine_id && cert_id) {
4461 if (tls_connection_engine_client_cert(conn, cert_id))
4462 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4463 } else if (tls_connection_client_cert(conn, params->client_cert,
4464 params->client_cert_blob,
4465 params->client_cert_blob_len))
4468 if (engine_id && key_id) {
4469 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
4470 if (tls_connection_engine_private_key(conn))
4471 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4472 } else if (tls_connection_private_key(data, conn,
4473 params->private_key,
4474 params->private_key_passwd,
4475 params->private_key_blob,
4476 params->private_key_blob_len)) {
4477 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
4478 params->private_key);
4482 if (tls_connection_dh(conn, params->dh_file)) {
4483 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
4488 ciphers = params->openssl_ciphers;
4489 #ifdef CONFIG_SUITEB
4490 #ifdef OPENSSL_IS_BORINGSSL
4491 if (ciphers && os_strcmp(ciphers, "SUITEB192") == 0) {
4492 /* BoringSSL removed support for SUITEB192, so need to handle
4493 * this with hardcoded ciphersuite and additional checks for
4494 * other parameters. */
4495 ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384";
4497 #endif /* OPENSSL_IS_BORINGSSL */
4498 #endif /* CONFIG_SUITEB */
4499 if (ciphers && SSL_set_cipher_list(conn->ssl, ciphers) != 1) {
4500 wpa_printf(MSG_INFO,
4501 "OpenSSL: Failed to set cipher string '%s'",
4506 if (tls_set_conn_flags(conn, params->flags,
4507 params->openssl_ciphers) < 0)
4510 #ifdef OPENSSL_IS_BORINGSSL
4511 if (params->flags & TLS_CONN_REQUEST_OCSP) {
4512 SSL_enable_ocsp_stapling(conn->ssl);
4514 #else /* OPENSSL_IS_BORINGSSL */
4516 if (params->flags & TLS_CONN_REQUEST_OCSP) {
4517 SSL_CTX *ssl_ctx = data->ssl;
4518 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
4519 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
4520 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
4522 #else /* HAVE_OCSP */
4523 if (params->flags & TLS_CONN_REQUIRE_OCSP) {
4524 wpa_printf(MSG_INFO,
4525 "OpenSSL: No OCSP support included - reject configuration");
4528 if (params->flags & TLS_CONN_REQUEST_OCSP) {
4529 wpa_printf(MSG_DEBUG,
4530 "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
4532 #endif /* HAVE_OCSP */
4533 #endif /* OPENSSL_IS_BORINGSSL */
4535 conn->flags = params->flags;
4537 tls_get_errors(data);
4543 int tls_global_set_params(void *tls_ctx,
4544 const struct tls_connection_params *params)
4546 struct tls_data *data = tls_ctx;
4547 SSL_CTX *ssl_ctx = data->ssl;
4550 while ((err = ERR_get_error())) {
4551 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
4552 __func__, ERR_error_string(err, NULL));
4555 if (tls_global_ca_cert(data, params->ca_cert) ||
4556 tls_global_client_cert(data, params->client_cert) ||
4557 tls_global_private_key(data, params->private_key,
4558 params->private_key_passwd) ||
4559 tls_global_dh(data, params->dh_file)) {
4560 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
4564 if (params->openssl_ciphers &&
4565 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
4566 wpa_printf(MSG_INFO,
4567 "OpenSSL: Failed to set cipher string '%s'",
4568 params->openssl_ciphers);
4572 #ifdef SSL_OP_NO_TICKET
4573 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
4574 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
4576 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
4577 #endif /* SSL_OP_NO_TICKET */
4580 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
4581 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
4582 os_free(tls_global->ocsp_stapling_response);
4583 if (params->ocsp_stapling_response)
4584 tls_global->ocsp_stapling_response =
4585 os_strdup(params->ocsp_stapling_response);
4587 tls_global->ocsp_stapling_response = NULL;
4588 #endif /* HAVE_OCSP */
4594 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4595 /* Pre-shared secred requires a patch to openssl, so this function is
4596 * commented out unless explicitly needed for EAP-FAST in order to be able to
4597 * build this file with unmodified openssl. */
4599 #if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4600 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
4601 STACK_OF(SSL_CIPHER) *peer_ciphers,
4602 const SSL_CIPHER **cipher, void *arg)
4603 #else /* OPENSSL_IS_BORINGSSL */
4604 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
4605 STACK_OF(SSL_CIPHER) *peer_ciphers,
4606 SSL_CIPHER **cipher, void *arg)
4607 #endif /* OPENSSL_IS_BORINGSSL */
4609 struct tls_connection *conn = arg;
4612 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
4613 (defined(LIBRESSL_VERSION_NUMBER) && \
4614 LIBRESSL_VERSION_NUMBER < 0x20700000L)
4615 if (conn == NULL || conn->session_ticket_cb == NULL)
4618 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
4619 conn->session_ticket,
4620 conn->session_ticket_len,
4621 s->s3->client_random,
4622 s->s3->server_random, secret);
4624 unsigned char client_random[SSL3_RANDOM_SIZE];
4625 unsigned char server_random[SSL3_RANDOM_SIZE];
4627 if (conn == NULL || conn->session_ticket_cb == NULL)
4630 SSL_get_client_random(s, client_random, sizeof(client_random));
4631 SSL_get_server_random(s, server_random, sizeof(server_random));
4633 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
4634 conn->session_ticket,
4635 conn->session_ticket_len,
4637 server_random, secret);
4640 os_free(conn->session_ticket);
4641 conn->session_ticket = NULL;
4646 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
4651 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
4654 struct tls_connection *conn = arg;
4656 if (conn == NULL || conn->session_ticket_cb == NULL)
4659 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
4661 os_free(conn->session_ticket);
4662 conn->session_ticket = NULL;
4664 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
4665 "extension", data, len);
4667 conn->session_ticket = os_memdup(data, len);
4668 if (conn->session_ticket == NULL)
4671 conn->session_ticket_len = len;
4675 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4678 int tls_connection_set_session_ticket_cb(void *tls_ctx,
4679 struct tls_connection *conn,
4680 tls_session_ticket_cb cb,
4683 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4684 conn->session_ticket_cb = cb;
4685 conn->session_ticket_cb_ctx = ctx;
4688 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
4691 SSL_set_session_ticket_ext_cb(conn->ssl,
4692 tls_session_ticket_ext_cb, conn);
4694 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
4696 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
4700 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4702 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4706 int tls_get_library_version(char *buf, size_t buf_len)
4708 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
4709 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
4710 OPENSSL_VERSION_TEXT,
4711 OpenSSL_version(OPENSSL_VERSION));
4713 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
4714 OPENSSL_VERSION_TEXT,
4715 SSLeay_version(SSLEAY_VERSION));
4720 void tls_connection_set_success_data(struct tls_connection *conn,
4721 struct wpabuf *data)
4726 if (tls_ex_idx_session < 0)
4728 sess = SSL_get_session(conn->ssl);
4731 old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
4733 wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
4737 if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
4740 wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
4741 conn->success_data = 1;
4745 wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
4750 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
4752 wpa_printf(MSG_DEBUG,
4753 "OpenSSL: Success data accepted for resumed session");
4754 conn->success_data = 1;
4758 const struct wpabuf *
4759 tls_connection_get_success_data(struct tls_connection *conn)
4763 if (tls_ex_idx_session < 0 ||
4764 !(sess = SSL_get_session(conn->ssl)))
4766 return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
4770 void tls_connection_remove_session(struct tls_connection *conn)
4774 sess = SSL_get_session(conn->ssl);
4778 if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
4779 wpa_printf(MSG_DEBUG,
4780 "OpenSSL: Session was not cached");
4782 wpa_printf(MSG_DEBUG,
4783 "OpenSSL: Removed cached session to disable session resumption");