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/pkcs12.h>
22 #include <openssl/x509v3.h>
23 #ifndef OPENSSL_NO_ENGINE
24 #include <openssl/engine.h>
25 #endif /* OPENSSL_NO_ENGINE */
26 #ifndef OPENSSL_NO_DSA
27 #include <openssl/dsa.h>
30 #include <openssl/dh.h>
38 #include "tls_openssl.h"
40 #if defined(OPENSSL_IS_BORINGSSL)
41 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
42 typedef size_t stack_index_t
;
44 typedef int stack_index_t
;
47 #ifdef SSL_set_tlsext_status_type
48 #ifndef OPENSSL_NO_TLSEXT
50 #include <openssl/ocsp.h>
51 #endif /* OPENSSL_NO_TLSEXT */
52 #endif /* SSL_set_tlsext_status_type */
54 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
56 * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
57 * 1.1.0. Provide compatibility wrappers for older versions.
60 static size_t SSL_get_client_random(const SSL
*ssl
, unsigned char *out
,
63 if (!ssl
->s3
|| outlen
< SSL3_RANDOM_SIZE
)
65 os_memcpy(out
, ssl
->s3
->client_random
, SSL3_RANDOM_SIZE
);
66 return SSL3_RANDOM_SIZE
;
70 static size_t SSL_get_server_random(const SSL
*ssl
, unsigned char *out
,
73 if (!ssl
->s3
|| outlen
< SSL3_RANDOM_SIZE
)
75 os_memcpy(out
, ssl
->s3
->server_random
, SSL3_RANDOM_SIZE
);
76 return SSL3_RANDOM_SIZE
;
80 static size_t SSL_SESSION_get_master_key(const SSL_SESSION
*session
,
81 unsigned char *out
, size_t outlen
)
83 if (!session
|| session
->master_key_length
< 0 ||
84 (size_t) session
->master_key_length
> outlen
)
86 if ((size_t) session
->master_key_length
< outlen
)
87 outlen
= session
->master_key_length
;
88 os_memcpy(out
, session
->master_key
, outlen
);
95 #include <openssl/pem.h>
96 #include <keystore/keystore_get.h>
98 static BIO
* BIO_from_keystore(const char *key
)
101 uint8_t *value
= NULL
;
102 int length
= keystore_get(key
, strlen(key
), &value
);
103 if (length
!= -1 && (bio
= BIO_new(BIO_s_mem())) != NULL
)
104 BIO_write(bio
, value
, length
);
110 static int tls_add_ca_from_keystore(X509_STORE
*ctx
, const char *key_alias
)
112 BIO
*bio
= BIO_from_keystore(key_alias
);
113 STACK_OF(X509_INFO
) *stack
= NULL
;
117 stack
= PEM_X509_INFO_read_bio(bio
, NULL
, NULL
, NULL
);
122 wpa_printf(MSG_WARNING
, "TLS: Failed to parse certificate: %s",
127 for (i
= 0; i
< sk_X509_INFO_num(stack
); ++i
) {
128 X509_INFO
*info
= sk_X509_INFO_value(stack
, i
);
131 X509_STORE_add_cert(ctx
, info
->x509
);
133 X509_STORE_add_crl(ctx
, info
->crl
);
136 sk_X509_INFO_pop_free(stack
, X509_INFO_free
);
142 static int tls_add_ca_from_keystore_encoded(X509_STORE
*ctx
,
143 const char *encoded_key_alias
)
146 int len
= os_strlen(encoded_key_alias
);
147 unsigned char *decoded_alias
;
150 wpa_printf(MSG_WARNING
, "Invalid hex-encoded alias: %s",
155 decoded_alias
= os_malloc(len
/ 2 + 1);
157 if (!hexstr2bin(encoded_key_alias
, decoded_alias
, len
/ 2)) {
158 decoded_alias
[len
/ 2] = '\0';
159 rc
= tls_add_ca_from_keystore(
160 ctx
, (const char *) decoded_alias
);
162 os_free(decoded_alias
);
170 static int tls_openssl_ref_count
= 0;
171 static int tls_ex_idx_session
= -1;
174 void (*event_cb
)(void *ctx
, enum tls_event ev
,
175 union tls_event_data
*data
);
178 char *ocsp_stapling_response
;
181 static struct tls_context
*tls_global
= NULL
;
186 unsigned int tls_session_lifetime
;
189 struct tls_connection
{
190 struct tls_context
*context
;
193 BIO
*ssl_in
, *ssl_out
;
194 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
195 ENGINE
*engine
; /* functional reference to the engine */
196 EVP_PKEY
*private_key
; /* the private key if using engine */
197 #endif /* OPENSSL_NO_ENGINE */
198 char *subject_match
, *altsubject_match
, *suffix_match
, *domain_match
;
199 int read_alerts
, write_alerts
, failed
;
201 tls_session_ticket_cb session_ticket_cb
;
202 void *session_ticket_cb_ctx
;
204 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
206 size_t session_ticket_len
;
208 unsigned int ca_cert_verify
:1;
209 unsigned int cert_probe
:1;
210 unsigned int server_cert_only
:1;
211 unsigned int invalid_hb_used
:1;
212 unsigned int success_data
:1;
214 u8 srv_cert_hash
[32];
220 X509
*peer_issuer_issuer
;
222 unsigned char client_random
[SSL3_RANDOM_SIZE
];
223 unsigned char server_random
[SSL3_RANDOM_SIZE
];
227 static struct tls_context
* tls_context_new(const struct tls_config
*conf
)
229 struct tls_context
*context
= os_zalloc(sizeof(*context
));
233 context
->event_cb
= conf
->event_cb
;
234 context
->cb_ctx
= conf
->cb_ctx
;
235 context
->cert_in_cb
= conf
->cert_in_cb
;
241 #ifdef CONFIG_NO_STDOUT_DEBUG
243 static void _tls_show_errors(void)
247 while ((err
= ERR_get_error())) {
248 /* Just ignore the errors, since stdout is disabled */
251 #define tls_show_errors(l, f, t) _tls_show_errors()
253 #else /* CONFIG_NO_STDOUT_DEBUG */
255 static void tls_show_errors(int level
, const char *func
, const char *txt
)
259 wpa_printf(level
, "OpenSSL: %s - %s %s",
260 func
, txt
, ERR_error_string(ERR_get_error(), NULL
));
262 while ((err
= ERR_get_error())) {
263 wpa_printf(MSG_INFO
, "OpenSSL: pending error: %s",
264 ERR_error_string(err
, NULL
));
268 #endif /* CONFIG_NO_STDOUT_DEBUG */
271 #ifdef CONFIG_NATIVE_WINDOWS
273 /* Windows CryptoAPI and access to certificate stores */
274 #include <wincrypt.h>
276 #ifdef __MINGW32_VERSION
278 * MinGW does not yet include all the needed definitions for CryptoAPI, so
279 * define here whatever extra is needed.
281 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
282 #define CERT_STORE_READONLY_FLAG 0x00008000
283 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
285 #endif /* __MINGW32_VERSION */
288 struct cryptoapi_rsa_data
{
289 const CERT_CONTEXT
*cert
;
290 HCRYPTPROV crypt_prov
;
292 BOOL free_crypt_prov
;
296 static void cryptoapi_error(const char *msg
)
298 wpa_printf(MSG_INFO
, "CryptoAPI: %s; err=%u",
299 msg
, (unsigned int) GetLastError());
303 static int cryptoapi_rsa_pub_enc(int flen
, const unsigned char *from
,
304 unsigned char *to
, RSA
*rsa
, int padding
)
306 wpa_printf(MSG_DEBUG
, "%s - not implemented", __func__
);
311 static int cryptoapi_rsa_pub_dec(int flen
, const unsigned char *from
,
312 unsigned char *to
, RSA
*rsa
, int padding
)
314 wpa_printf(MSG_DEBUG
, "%s - not implemented", __func__
);
319 static int cryptoapi_rsa_priv_enc(int flen
, const unsigned char *from
,
320 unsigned char *to
, RSA
*rsa
, int padding
)
322 struct cryptoapi_rsa_data
*priv
=
323 (struct cryptoapi_rsa_data
*) rsa
->meth
->app_data
;
325 DWORD hash_size
, len
, i
;
326 unsigned char *buf
= NULL
;
330 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT
,
331 ERR_R_PASSED_NULL_PARAMETER
);
335 if (padding
!= RSA_PKCS1_PADDING
) {
336 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT
,
337 RSA_R_UNKNOWN_PADDING_TYPE
);
341 if (flen
!= 16 /* MD5 */ + 20 /* SHA-1 */) {
342 wpa_printf(MSG_INFO
, "%s - only MD5-SHA1 hash supported",
344 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT
,
345 RSA_R_INVALID_MESSAGE_LENGTH
);
349 if (!CryptCreateHash(priv
->crypt_prov
, CALG_SSL3_SHAMD5
, 0, 0, &hash
))
351 cryptoapi_error("CryptCreateHash failed");
355 len
= sizeof(hash_size
);
356 if (!CryptGetHashParam(hash
, HP_HASHSIZE
, (BYTE
*) &hash_size
, &len
,
358 cryptoapi_error("CryptGetHashParam failed");
362 if ((int) hash_size
!= flen
) {
363 wpa_printf(MSG_INFO
, "CryptoAPI: Invalid hash size (%u != %d)",
364 (unsigned) hash_size
, flen
);
365 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT
,
366 RSA_R_INVALID_MESSAGE_LENGTH
);
369 if (!CryptSetHashParam(hash
, HP_HASHVAL
, (BYTE
* ) from
, 0)) {
370 cryptoapi_error("CryptSetHashParam failed");
375 buf
= os_malloc(len
);
377 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT
, ERR_R_MALLOC_FAILURE
);
381 if (!CryptSignHash(hash
, priv
->key_spec
, NULL
, 0, buf
, &len
)) {
382 cryptoapi_error("CryptSignHash failed");
386 for (i
= 0; i
< len
; i
++)
387 to
[i
] = buf
[len
- i
- 1];
392 CryptDestroyHash(hash
);
398 static int cryptoapi_rsa_priv_dec(int flen
, const unsigned char *from
,
399 unsigned char *to
, RSA
*rsa
, int padding
)
401 wpa_printf(MSG_DEBUG
, "%s - not implemented", __func__
);
406 static void cryptoapi_free_data(struct cryptoapi_rsa_data
*priv
)
410 if (priv
->crypt_prov
&& priv
->free_crypt_prov
)
411 CryptReleaseContext(priv
->crypt_prov
, 0);
413 CertFreeCertificateContext(priv
->cert
);
418 static int cryptoapi_finish(RSA
*rsa
)
420 cryptoapi_free_data((struct cryptoapi_rsa_data
*) rsa
->meth
->app_data
);
421 os_free((void *) rsa
->meth
);
427 static const CERT_CONTEXT
* cryptoapi_find_cert(const char *name
, DWORD store
)
430 const CERT_CONTEXT
*ret
= NULL
;
432 cs
= CertOpenStore((LPCSTR
) CERT_STORE_PROV_SYSTEM
, 0, 0,
433 store
| CERT_STORE_OPEN_EXISTING_FLAG
|
434 CERT_STORE_READONLY_FLAG
, L
"MY");
436 cryptoapi_error("Failed to open 'My system store'");
440 if (strncmp(name
, "cert://", 7) == 0) {
441 unsigned short wbuf
[255];
442 MultiByteToWideChar(CP_ACP
, 0, name
+ 7, -1, wbuf
, 255);
443 ret
= CertFindCertificateInStore(cs
, X509_ASN_ENCODING
|
445 0, CERT_FIND_SUBJECT_STR
,
447 } else if (strncmp(name
, "hash://", 7) == 0) {
448 CRYPT_HASH_BLOB blob
;
450 const char *hash
= name
+ 7;
453 len
= os_strlen(hash
) / 2;
454 buf
= os_malloc(len
);
455 if (buf
&& hexstr2bin(hash
, buf
, len
) == 0) {
458 ret
= CertFindCertificateInStore(cs
,
467 CertCloseStore(cs
, 0);
473 static int tls_cryptoapi_cert(SSL
*ssl
, const char *name
)
476 RSA
*rsa
= NULL
, *pub_rsa
;
477 struct cryptoapi_rsa_data
*priv
;
478 RSA_METHOD
*rsa_meth
;
481 (strncmp(name
, "cert://", 7) != 0 &&
482 strncmp(name
, "hash://", 7) != 0))
485 priv
= os_zalloc(sizeof(*priv
));
486 rsa_meth
= os_zalloc(sizeof(*rsa_meth
));
487 if (priv
== NULL
|| rsa_meth
== NULL
) {
488 wpa_printf(MSG_WARNING
, "CryptoAPI: Failed to allocate memory "
489 "for CryptoAPI RSA method");
495 priv
->cert
= cryptoapi_find_cert(name
, CERT_SYSTEM_STORE_CURRENT_USER
);
496 if (priv
->cert
== NULL
) {
497 priv
->cert
= cryptoapi_find_cert(
498 name
, CERT_SYSTEM_STORE_LOCAL_MACHINE
);
500 if (priv
->cert
== NULL
) {
501 wpa_printf(MSG_INFO
, "CryptoAPI: Could not find certificate "
506 cert
= d2i_X509(NULL
,
507 (const unsigned char **) &priv
->cert
->pbCertEncoded
,
508 priv
->cert
->cbCertEncoded
);
510 wpa_printf(MSG_INFO
, "CryptoAPI: Could not process X509 DER "
515 if (!CryptAcquireCertificatePrivateKey(priv
->cert
,
516 CRYPT_ACQUIRE_COMPARE_KEY_FLAG
,
517 NULL
, &priv
->crypt_prov
,
519 &priv
->free_crypt_prov
)) {
520 cryptoapi_error("Failed to acquire a private key for the "
525 rsa_meth
->name
= "Microsoft CryptoAPI RSA Method";
526 rsa_meth
->rsa_pub_enc
= cryptoapi_rsa_pub_enc
;
527 rsa_meth
->rsa_pub_dec
= cryptoapi_rsa_pub_dec
;
528 rsa_meth
->rsa_priv_enc
= cryptoapi_rsa_priv_enc
;
529 rsa_meth
->rsa_priv_dec
= cryptoapi_rsa_priv_dec
;
530 rsa_meth
->finish
= cryptoapi_finish
;
531 rsa_meth
->flags
= RSA_METHOD_FLAG_NO_CHECK
;
532 rsa_meth
->app_data
= (char *) priv
;
536 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE
,
537 ERR_R_MALLOC_FAILURE
);
541 if (!SSL_use_certificate(ssl
, cert
)) {
546 pub_rsa
= cert
->cert_info
->key
->pkey
->pkey
.rsa
;
550 rsa
->n
= BN_dup(pub_rsa
->n
);
551 rsa
->e
= BN_dup(pub_rsa
->e
);
552 if (!RSA_set_method(rsa
, rsa_meth
))
555 if (!SSL_use_RSAPrivateKey(ssl
, rsa
))
568 cryptoapi_free_data(priv
);
574 static int tls_cryptoapi_ca_cert(SSL_CTX
*ssl_ctx
, SSL
*ssl
, const char *name
)
577 PCCERT_CONTEXT ctx
= NULL
;
585 if (name
== NULL
|| strncmp(name
, "cert_store://", 13) != 0)
590 wstore
= os_malloc((os_strlen(store
) + 1) * sizeof(WCHAR
));
593 wsprintf(wstore
, L
"%S", store
);
594 cs
= CertOpenSystemStore(0, wstore
);
597 cs
= CertOpenSystemStore(0, store
);
600 wpa_printf(MSG_DEBUG
, "%s: failed to open system cert store "
601 "'%s': error=%d", __func__
, store
,
602 (int) GetLastError());
606 while ((ctx
= CertEnumCertificatesInStore(cs
, ctx
))) {
607 cert
= d2i_X509(NULL
,
608 (const unsigned char **) &ctx
->pbCertEncoded
,
611 wpa_printf(MSG_INFO
, "CryptoAPI: Could not process "
612 "X509 DER encoding for CA cert");
616 X509_NAME_oneline(X509_get_subject_name(cert
), buf
,
618 wpa_printf(MSG_DEBUG
, "OpenSSL: Loaded CA certificate for "
619 "system certificate store: subject='%s'", buf
);
621 if (!X509_STORE_add_cert(ssl_ctx
->cert_store
, cert
)) {
622 tls_show_errors(MSG_WARNING
, __func__
,
623 "Failed to add ca_cert to OpenSSL "
624 "certificate store");
630 if (!CertCloseStore(cs
, 0)) {
631 wpa_printf(MSG_DEBUG
, "%s: failed to close system cert store "
632 "'%s': error=%d", __func__
, name
+ 13,
633 (int) GetLastError());
640 #else /* CONFIG_NATIVE_WINDOWS */
642 static int tls_cryptoapi_cert(SSL
*ssl
, const char *name
)
647 #endif /* CONFIG_NATIVE_WINDOWS */
650 static void ssl_info_cb(const SSL
*ssl
, int where
, int ret
)
655 wpa_printf(MSG_DEBUG
, "SSL: (where=0x%x ret=0x%x)", where
, ret
);
656 w
= where
& ~SSL_ST_MASK
;
657 if (w
& SSL_ST_CONNECT
)
659 else if (w
& SSL_ST_ACCEPT
)
664 if (where
& SSL_CB_LOOP
) {
665 wpa_printf(MSG_DEBUG
, "SSL: %s:%s",
666 str
, SSL_state_string_long(ssl
));
667 } else if (where
& SSL_CB_ALERT
) {
668 struct tls_connection
*conn
= SSL_get_app_data((SSL
*) ssl
);
669 wpa_printf(MSG_INFO
, "SSL: SSL3 alert: %s:%s:%s",
670 where
& SSL_CB_READ
?
671 "read (remote end reported an error)" :
672 "write (local SSL3 detected an error)",
673 SSL_alert_type_string_long(ret
),
674 SSL_alert_desc_string_long(ret
));
675 if ((ret
>> 8) == SSL3_AL_FATAL
) {
676 if (where
& SSL_CB_READ
)
679 conn
->write_alerts
++;
681 if (conn
->context
->event_cb
!= NULL
) {
682 union tls_event_data ev
;
683 struct tls_context
*context
= conn
->context
;
684 os_memset(&ev
, 0, sizeof(ev
));
685 ev
.alert
.is_local
= !(where
& SSL_CB_READ
);
686 ev
.alert
.type
= SSL_alert_type_string_long(ret
);
687 ev
.alert
.description
= SSL_alert_desc_string_long(ret
);
688 context
->event_cb(context
->cb_ctx
, TLS_ALERT
, &ev
);
690 } else if (where
& SSL_CB_EXIT
&& ret
<= 0) {
691 wpa_printf(MSG_DEBUG
, "SSL: %s:%s in %s",
692 str
, ret
== 0 ? "failed" : "error",
693 SSL_state_string_long(ssl
));
698 #ifndef OPENSSL_NO_ENGINE
700 * tls_engine_load_dynamic_generic - load any openssl engine
701 * @pre: an array of commands and values that load an engine initialized
702 * in the engine specific function
703 * @post: an array of commands and values that initialize an already loaded
704 * engine (or %NULL if not required)
705 * @id: the engine id of the engine to load (only required if post is not %NULL
707 * This function is a generic function that loads any openssl engine.
709 * Returns: 0 on success, -1 on failure
711 static int tls_engine_load_dynamic_generic(const char *pre
[],
712 const char *post
[], const char *id
)
715 const char *dynamic_id
= "dynamic";
717 engine
= ENGINE_by_id(id
);
720 wpa_printf(MSG_DEBUG
, "ENGINE: engine '%s' is already "
726 engine
= ENGINE_by_id(dynamic_id
);
727 if (engine
== NULL
) {
728 wpa_printf(MSG_INFO
, "ENGINE: Can't find engine %s [%s]",
730 ERR_error_string(ERR_get_error(), NULL
));
734 /* Perform the pre commands. This will load the engine. */
735 while (pre
&& pre
[0]) {
736 wpa_printf(MSG_DEBUG
, "ENGINE: '%s' '%s'", pre
[0], pre
[1]);
737 if (ENGINE_ctrl_cmd_string(engine
, pre
[0], pre
[1], 0) == 0) {
738 wpa_printf(MSG_INFO
, "ENGINE: ctrl cmd_string failed: "
739 "%s %s [%s]", pre
[0], pre
[1],
740 ERR_error_string(ERR_get_error(), NULL
));
748 * Free the reference to the "dynamic" engine. The loaded engine can
749 * now be looked up using ENGINE_by_id().
753 engine
= ENGINE_by_id(id
);
754 if (engine
== NULL
) {
755 wpa_printf(MSG_INFO
, "ENGINE: Can't find engine %s [%s]",
756 id
, ERR_error_string(ERR_get_error(), NULL
));
760 while (post
&& post
[0]) {
761 wpa_printf(MSG_DEBUG
, "ENGINE: '%s' '%s'", post
[0], post
[1]);
762 if (ENGINE_ctrl_cmd_string(engine
, post
[0], post
[1], 0) == 0) {
763 wpa_printf(MSG_DEBUG
, "ENGINE: ctrl cmd_string failed:"
764 " %s %s [%s]", post
[0], post
[1],
765 ERR_error_string(ERR_get_error(), NULL
));
766 ENGINE_remove(engine
);
779 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
780 * @pkcs11_so_path: pksc11_so_path from the configuration
781 * @pcks11_module_path: pkcs11_module_path from the configuration
783 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path
,
784 const char *pkcs11_module_path
)
786 char *engine_id
= "pkcs11";
787 const char *pre_cmd
[] = {
788 "SO_PATH", NULL
/* pkcs11_so_path */,
789 "ID", NULL
/* engine_id */,
791 /* "NO_VCHECK", "1", */
795 const char *post_cmd
[] = {
796 "MODULE_PATH", NULL
/* pkcs11_module_path */,
803 pre_cmd
[1] = pkcs11_so_path
;
804 pre_cmd
[3] = engine_id
;
805 if (pkcs11_module_path
)
806 post_cmd
[1] = pkcs11_module_path
;
810 wpa_printf(MSG_DEBUG
, "ENGINE: Loading pkcs11 Engine from %s",
813 return tls_engine_load_dynamic_generic(pre_cmd
, post_cmd
, engine_id
);
818 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
819 * @opensc_so_path: opensc_so_path from the configuration
821 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path
)
823 char *engine_id
= "opensc";
824 const char *pre_cmd
[] = {
825 "SO_PATH", NULL
/* opensc_so_path */,
826 "ID", NULL
/* engine_id */,
835 pre_cmd
[1] = opensc_so_path
;
836 pre_cmd
[3] = engine_id
;
838 wpa_printf(MSG_DEBUG
, "ENGINE: Loading OpenSC Engine from %s",
841 return tls_engine_load_dynamic_generic(pre_cmd
, NULL
, engine_id
);
843 #endif /* OPENSSL_NO_ENGINE */
846 static void remove_session_cb(SSL_CTX
*ctx
, SSL_SESSION
*sess
)
850 if (tls_ex_idx_session
< 0)
852 buf
= SSL_SESSION_get_ex_data(sess
, tls_ex_idx_session
);
855 wpa_printf(MSG_DEBUG
,
856 "OpenSSL: Free application session data %p (sess %p)",
860 SSL_SESSION_set_ex_data(sess
, tls_ex_idx_session
, NULL
);
864 void * tls_init(const struct tls_config
*conf
)
866 struct tls_data
*data
;
868 struct tls_context
*context
;
871 if (tls_openssl_ref_count
== 0) {
872 tls_global
= context
= tls_context_new(conf
);
877 if (conf
&& conf
->fips_mode
) {
878 static int fips_enabled
= 0;
880 if (!fips_enabled
&& !FIPS_mode_set(1)) {
881 wpa_printf(MSG_ERROR
, "Failed to enable FIPS "
883 ERR_load_crypto_strings();
884 ERR_print_errors_fp(stderr
);
889 wpa_printf(MSG_INFO
, "Running in FIPS mode");
893 #else /* OPENSSL_FIPS */
894 if (conf
&& conf
->fips_mode
) {
895 wpa_printf(MSG_ERROR
, "FIPS mode requested, but not "
901 #endif /* OPENSSL_FIPS */
902 #endif /* CONFIG_FIPS */
903 #if OPENSSL_VERSION_NUMBER < 0x10100000L
904 SSL_load_error_strings();
906 #ifndef OPENSSL_NO_SHA256
907 EVP_add_digest(EVP_sha256());
908 #endif /* OPENSSL_NO_SHA256 */
909 /* TODO: if /dev/urandom is available, PRNG is seeded
910 * automatically. If this is not the case, random data should
914 #ifndef OPENSSL_NO_RC2
916 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
917 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
918 * versions, but it looks like OpenSSL 1.0.0 does not do that
921 EVP_add_cipher(EVP_rc2_40_cbc());
922 #endif /* OPENSSL_NO_RC2 */
924 #endif /* PKCS12_FUNCS */
927 context
= tls_context_new(conf
);
931 tls_openssl_ref_count
++;
933 data
= os_zalloc(sizeof(*data
));
935 ssl
= SSL_CTX_new(SSLv23_method());
939 tls_openssl_ref_count
--;
940 if (context
!= tls_global
)
942 if (tls_openssl_ref_count
== 0) {
951 data
->tls_session_lifetime
= conf
->tls_session_lifetime
;
953 SSL_CTX_set_options(ssl
, SSL_OP_NO_SSLv2
);
954 SSL_CTX_set_options(ssl
, SSL_OP_NO_SSLv3
);
956 SSL_CTX_set_info_callback(ssl
, ssl_info_cb
);
957 SSL_CTX_set_app_data(ssl
, context
);
958 if (data
->tls_session_lifetime
> 0) {
959 SSL_CTX_set_quiet_shutdown(ssl
, 1);
961 * Set default context here. In practice, this will be replaced
962 * by the per-EAP method context in tls_connection_set_verify().
964 SSL_CTX_set_session_id_context(ssl
, (u8
*) "hostapd", 7);
965 SSL_CTX_set_session_cache_mode(ssl
, SSL_SESS_CACHE_SERVER
);
966 SSL_CTX_set_timeout(ssl
, data
->tls_session_lifetime
);
967 SSL_CTX_sess_set_remove_cb(ssl
, remove_session_cb
);
969 SSL_CTX_set_session_cache_mode(ssl
, SSL_SESS_CACHE_OFF
);
972 if (tls_ex_idx_session
< 0) {
973 tls_ex_idx_session
= SSL_SESSION_get_ex_new_index(
974 0, NULL
, NULL
, NULL
, NULL
);
975 if (tls_ex_idx_session
< 0) {
981 #ifndef OPENSSL_NO_ENGINE
982 wpa_printf(MSG_DEBUG
, "ENGINE: Loading dynamic engine");
983 ERR_load_ENGINE_strings();
984 ENGINE_load_dynamic();
987 (conf
->opensc_engine_path
|| conf
->pkcs11_engine_path
||
988 conf
->pkcs11_module_path
)) {
989 if (tls_engine_load_dynamic_opensc(conf
->opensc_engine_path
) ||
990 tls_engine_load_dynamic_pkcs11(conf
->pkcs11_engine_path
,
991 conf
->pkcs11_module_path
)) {
996 #endif /* OPENSSL_NO_ENGINE */
998 if (conf
&& conf
->openssl_ciphers
)
999 ciphers
= conf
->openssl_ciphers
;
1001 ciphers
= "DEFAULT:!EXP:!LOW";
1002 if (SSL_CTX_set_cipher_list(ssl
, ciphers
) != 1) {
1003 wpa_printf(MSG_ERROR
,
1004 "OpenSSL: Failed to set cipher string '%s'",
1014 void tls_deinit(void *ssl_ctx
)
1016 struct tls_data
*data
= ssl_ctx
;
1017 SSL_CTX
*ssl
= data
->ssl
;
1018 struct tls_context
*context
= SSL_CTX_get_app_data(ssl
);
1019 if (context
!= tls_global
)
1021 if (data
->tls_session_lifetime
> 0)
1022 SSL_CTX_flush_sessions(ssl
, 0);
1025 tls_openssl_ref_count
--;
1026 if (tls_openssl_ref_count
== 0) {
1027 #if OPENSSL_VERSION_NUMBER < 0x10100000L
1028 #ifndef OPENSSL_NO_ENGINE
1030 #endif /* OPENSSL_NO_ENGINE */
1031 CRYPTO_cleanup_all_ex_data();
1032 ERR_remove_thread_state(NULL
);
1035 #endif /* < 1.1.0 */
1036 os_free(tls_global
->ocsp_stapling_response
);
1037 tls_global
->ocsp_stapling_response
= NULL
;
1038 os_free(tls_global
);
1046 #ifndef OPENSSL_NO_ENGINE
1048 /* Cryptoki return values */
1049 #define CKR_PIN_INCORRECT 0x000000a0
1050 #define CKR_PIN_INVALID 0x000000a1
1051 #define CKR_PIN_LEN_RANGE 0x000000a2
1054 #define ERR_LIB_PKCS11 ERR_LIB_USER
1056 static int tls_is_pin_error(unsigned int err
)
1058 return ERR_GET_LIB(err
) == ERR_LIB_PKCS11
&&
1059 (ERR_GET_REASON(err
) == CKR_PIN_INCORRECT
||
1060 ERR_GET_REASON(err
) == CKR_PIN_INVALID
||
1061 ERR_GET_REASON(err
) == CKR_PIN_LEN_RANGE
);
1064 #endif /* OPENSSL_NO_ENGINE */
1068 /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
1069 EVP_PKEY
* EVP_PKEY_from_keystore(const char *key_id
);
1070 #endif /* ANDROID */
1072 static int tls_engine_init(struct tls_connection
*conn
, const char *engine_id
,
1073 const char *pin
, const char *key_id
,
1074 const char *cert_id
, const char *ca_cert_id
)
1076 #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
1077 #if !defined(OPENSSL_NO_ENGINE)
1078 #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
1081 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED
;
1082 conn
->engine
= NULL
;
1083 conn
->private_key
= EVP_PKEY_from_keystore(key_id
);
1084 if (!conn
->private_key
) {
1085 wpa_printf(MSG_ERROR
,
1086 "ENGINE: cannot load private key with id '%s' [%s]",
1088 ERR_error_string(ERR_get_error(), NULL
));
1089 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED
;
1091 #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
1093 #ifndef OPENSSL_NO_ENGINE
1095 if (engine_id
== NULL
) {
1096 wpa_printf(MSG_ERROR
, "ENGINE: Engine ID not set");
1102 ENGINE_load_dynamic();
1104 conn
->engine
= ENGINE_by_id(engine_id
);
1105 if (!conn
->engine
) {
1106 wpa_printf(MSG_ERROR
, "ENGINE: engine %s not available [%s]",
1107 engine_id
, ERR_error_string(ERR_get_error(), NULL
));
1110 if (ENGINE_init(conn
->engine
) != 1) {
1111 wpa_printf(MSG_ERROR
, "ENGINE: engine init failed "
1112 "(engine: %s) [%s]", engine_id
,
1113 ERR_error_string(ERR_get_error(), NULL
));
1116 wpa_printf(MSG_DEBUG
, "ENGINE: engine initialized");
1119 if (pin
&& ENGINE_ctrl_cmd_string(conn
->engine
, "PIN", pin
, 0) == 0) {
1120 wpa_printf(MSG_ERROR
, "ENGINE: cannot set pin [%s]",
1121 ERR_error_string(ERR_get_error(), NULL
));
1127 * Ensure that the ENGINE does not attempt to use the OpenSSL
1128 * UI system to obtain a PIN, if we didn't provide one.
1131 const void *password
;
1132 const char *prompt_info
;
1133 } key_cb
= { "", NULL
};
1135 /* load private key first in-case PIN is required for cert */
1136 conn
->private_key
= ENGINE_load_private_key(conn
->engine
,
1139 if (!conn
->private_key
) {
1140 unsigned long err
= ERR_get_error();
1142 wpa_printf(MSG_ERROR
,
1143 "ENGINE: cannot load private key with id '%s' [%s]",
1145 ERR_error_string(err
, NULL
));
1146 if (tls_is_pin_error(err
))
1147 ret
= TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN
;
1149 ret
= TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED
;
1154 /* handle a certificate and/or CA certificate */
1155 if (cert_id
|| ca_cert_id
) {
1156 const char *cmd_name
= "LOAD_CERT_CTRL";
1158 /* test if the engine supports a LOAD_CERT_CTRL */
1159 if (!ENGINE_ctrl(conn
->engine
, ENGINE_CTRL_GET_CMD_FROM_NAME
,
1160 0, (void *)cmd_name
, NULL
)) {
1161 wpa_printf(MSG_ERROR
, "ENGINE: engine does not support"
1162 " loading certificates");
1163 ret
= TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED
;
1172 ENGINE_free(conn
->engine
);
1173 conn
->engine
= NULL
;
1176 if (conn
->private_key
) {
1177 EVP_PKEY_free(conn
->private_key
);
1178 conn
->private_key
= NULL
;
1182 #else /* OPENSSL_NO_ENGINE */
1184 #endif /* OPENSSL_NO_ENGINE */
1188 static void tls_engine_deinit(struct tls_connection
*conn
)
1190 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1191 wpa_printf(MSG_DEBUG
, "ENGINE: engine deinit");
1192 if (conn
->private_key
) {
1193 EVP_PKEY_free(conn
->private_key
);
1194 conn
->private_key
= NULL
;
1197 #if !defined(OPENSSL_IS_BORINGSSL)
1198 ENGINE_finish(conn
->engine
);
1199 #endif /* !OPENSSL_IS_BORINGSSL */
1200 conn
->engine
= NULL
;
1202 #endif /* ANDROID || !OPENSSL_NO_ENGINE */
1206 int tls_get_errors(void *ssl_ctx
)
1211 while ((err
= ERR_get_error())) {
1212 wpa_printf(MSG_INFO
, "TLS - SSL error: %s",
1213 ERR_error_string(err
, NULL
));
1221 static const char * openssl_content_type(int content_type
)
1223 switch (content_type
) {
1225 return "change cipher spec";
1231 return "application data";
1235 return "TLS header info"; /* pseudo content type */
1242 static const char * openssl_handshake_type(int content_type
, const u8
*buf
,
1245 if (content_type
!= 22 || !buf
|| len
== 0)
1249 return "hello request";
1251 return "client hello";
1253 return "server hello";
1255 return "new session ticket";
1257 return "certificate";
1259 return "server key exchange";
1261 return "certificate request";
1263 return "server hello done";
1265 return "certificate verify";
1267 return "client key exchange";
1271 return "certificate url";
1273 return "certificate status";
1280 static void tls_msg_cb(int write_p
, int version
, int content_type
,
1281 const void *buf
, size_t len
, SSL
*ssl
, void *arg
)
1283 struct tls_connection
*conn
= arg
;
1284 const u8
*pos
= buf
;
1287 wpa_printf(MSG_DEBUG
,
1288 "OpenSSL: session ver=0x%x content_type=%d",
1289 version
, content_type
);
1290 wpa_hexdump_key(MSG_MSGDUMP
, "OpenSSL: Data", buf
, len
);
1294 wpa_printf(MSG_DEBUG
, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
1295 write_p
? "TX" : "RX", version
, content_type
,
1296 openssl_content_type(content_type
),
1297 openssl_handshake_type(content_type
, buf
, len
));
1298 wpa_hexdump_key(MSG_MSGDUMP
, "OpenSSL: Message", buf
, len
);
1299 if (content_type
== 24 && len
>= 3 && pos
[0] == 1) {
1300 size_t payload_len
= WPA_GET_BE16(pos
+ 1);
1301 if (payload_len
+ 3 > len
) {
1302 wpa_printf(MSG_ERROR
, "OpenSSL: Heartbeat attack detected");
1303 conn
->invalid_hb_used
= 1;
1309 struct tls_connection
* tls_connection_init(void *ssl_ctx
)
1311 struct tls_data
*data
= ssl_ctx
;
1312 SSL_CTX
*ssl
= data
->ssl
;
1313 struct tls_connection
*conn
;
1315 struct tls_context
*context
= SSL_CTX_get_app_data(ssl
);
1317 conn
= os_zalloc(sizeof(*conn
));
1320 conn
->ssl_ctx
= ssl
;
1321 conn
->ssl
= SSL_new(ssl
);
1322 if (conn
->ssl
== NULL
) {
1323 tls_show_errors(MSG_INFO
, __func__
,
1324 "Failed to initialize new SSL connection");
1329 conn
->context
= context
;
1330 SSL_set_app_data(conn
->ssl
, conn
);
1331 SSL_set_msg_callback(conn
->ssl
, tls_msg_cb
);
1332 SSL_set_msg_callback_arg(conn
->ssl
, conn
);
1333 options
= SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
|
1334 SSL_OP_SINGLE_DH_USE
;
1335 #ifdef SSL_OP_NO_COMPRESSION
1336 options
|= SSL_OP_NO_COMPRESSION
;
1337 #endif /* SSL_OP_NO_COMPRESSION */
1338 SSL_set_options(conn
->ssl
, options
);
1340 conn
->ssl_in
= BIO_new(BIO_s_mem());
1341 if (!conn
->ssl_in
) {
1342 tls_show_errors(MSG_INFO
, __func__
,
1343 "Failed to create a new BIO for ssl_in");
1344 SSL_free(conn
->ssl
);
1349 conn
->ssl_out
= BIO_new(BIO_s_mem());
1350 if (!conn
->ssl_out
) {
1351 tls_show_errors(MSG_INFO
, __func__
,
1352 "Failed to create a new BIO for ssl_out");
1353 SSL_free(conn
->ssl
);
1354 BIO_free(conn
->ssl_in
);
1359 SSL_set_bio(conn
->ssl
, conn
->ssl_in
, conn
->ssl_out
);
1365 void tls_connection_deinit(void *ssl_ctx
, struct tls_connection
*conn
)
1369 if (conn
->success_data
) {
1371 * Make sure ssl_clear_bad_session() does not remove this
1374 SSL_set_quiet_shutdown(conn
->ssl
, 1);
1375 SSL_shutdown(conn
->ssl
);
1377 SSL_free(conn
->ssl
);
1378 tls_engine_deinit(conn
);
1379 os_free(conn
->subject_match
);
1380 os_free(conn
->altsubject_match
);
1381 os_free(conn
->suffix_match
);
1382 os_free(conn
->domain_match
);
1383 os_free(conn
->session_ticket
);
1388 int tls_connection_established(void *ssl_ctx
, struct tls_connection
*conn
)
1390 return conn
? SSL_is_init_finished(conn
->ssl
) : 0;
1394 int tls_connection_shutdown(void *ssl_ctx
, struct tls_connection
*conn
)
1399 /* Shutdown previous TLS connection without notifying the peer
1400 * because the connection was already terminated in practice
1401 * and "close notify" shutdown alert would confuse AS. */
1402 SSL_set_quiet_shutdown(conn
->ssl
, 1);
1403 SSL_shutdown(conn
->ssl
);
1404 return SSL_clear(conn
->ssl
) == 1 ? 0 : -1;
1408 static int tls_match_altsubject_component(X509
*cert
, int type
,
1409 const char *value
, size_t len
)
1416 ext
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
);
1418 for (i
= 0; ext
&& i
< sk_GENERAL_NAME_num(ext
); i
++) {
1419 gen
= sk_GENERAL_NAME_value(ext
, i
);
1420 if (gen
->type
!= type
)
1422 if (os_strlen((char *) gen
->d
.ia5
->data
) == len
&&
1423 os_memcmp(value
, gen
->d
.ia5
->data
, len
) == 0)
1427 sk_GENERAL_NAME_pop_free(ext
, GENERAL_NAME_free
);
1433 static int tls_match_altsubject(X509
*cert
, const char *match
)
1436 const char *pos
, *end
;
1441 if (os_strncmp(pos
, "EMAIL:", 6) == 0) {
1444 } else if (os_strncmp(pos
, "DNS:", 4) == 0) {
1447 } else if (os_strncmp(pos
, "URI:", 4) == 0) {
1451 wpa_printf(MSG_INFO
, "TLS: Invalid altSubjectName "
1455 end
= os_strchr(pos
, ';');
1457 if (os_strncmp(end
+ 1, "EMAIL:", 6) == 0 ||
1458 os_strncmp(end
+ 1, "DNS:", 4) == 0 ||
1459 os_strncmp(end
+ 1, "URI:", 4) == 0)
1461 end
= os_strchr(end
+ 1, ';');
1466 len
= os_strlen(pos
);
1467 if (tls_match_altsubject_component(cert
, type
, pos
, len
) > 0)
1476 #ifndef CONFIG_NATIVE_WINDOWS
1477 static int domain_suffix_match(const u8
*val
, size_t len
, const char *match
,
1480 size_t i
, match_len
;
1482 /* Check for embedded nuls that could mess up suffix matching */
1483 for (i
= 0; i
< len
; i
++) {
1484 if (val
[i
] == '\0') {
1485 wpa_printf(MSG_DEBUG
, "TLS: Embedded null in a string - reject");
1490 match_len
= os_strlen(match
);
1491 if (match_len
> len
|| (full
&& match_len
!= len
))
1494 if (os_strncasecmp((const char *) val
+ len
- match_len
, match
,
1496 return 0; /* no match */
1498 if (match_len
== len
)
1499 return 1; /* exact match */
1501 if (val
[len
- match_len
- 1] == '.')
1502 return 1; /* full label match completes suffix match */
1504 wpa_printf(MSG_DEBUG
, "TLS: Reject due to incomplete label match");
1507 #endif /* CONFIG_NATIVE_WINDOWS */
1510 static int tls_match_suffix(X509
*cert
, const char *match
, int full
)
1512 #ifdef CONFIG_NATIVE_WINDOWS
1513 /* wincrypt.h has conflicting X509_NAME definition */
1515 #else /* CONFIG_NATIVE_WINDOWS */
1523 wpa_printf(MSG_DEBUG
, "TLS: Match domain against %s%s",
1524 full
? "": "suffix ", match
);
1526 ext
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
);
1528 for (j
= 0; ext
&& j
< sk_GENERAL_NAME_num(ext
); j
++) {
1529 gen
= sk_GENERAL_NAME_value(ext
, j
);
1530 if (gen
->type
!= GEN_DNS
)
1533 wpa_hexdump_ascii(MSG_DEBUG
, "TLS: Certificate dNSName",
1534 gen
->d
.dNSName
->data
,
1535 gen
->d
.dNSName
->length
);
1536 if (domain_suffix_match(gen
->d
.dNSName
->data
,
1537 gen
->d
.dNSName
->length
, match
, full
) ==
1539 wpa_printf(MSG_DEBUG
, "TLS: %s in dNSName found",
1540 full
? "Match" : "Suffix match");
1541 sk_GENERAL_NAME_pop_free(ext
, GENERAL_NAME_free
);
1545 sk_GENERAL_NAME_pop_free(ext
, GENERAL_NAME_free
);
1548 wpa_printf(MSG_DEBUG
, "TLS: None of the dNSName(s) matched");
1552 name
= X509_get_subject_name(cert
);
1558 i
= X509_NAME_get_index_by_NID(name
, NID_commonName
, i
);
1561 e
= X509_NAME_get_entry(name
, i
);
1564 cn
= X509_NAME_ENTRY_get_data(e
);
1567 wpa_hexdump_ascii(MSG_DEBUG
, "TLS: Certificate commonName",
1568 cn
->data
, cn
->length
);
1569 if (domain_suffix_match(cn
->data
, cn
->length
, match
, full
) == 1)
1571 wpa_printf(MSG_DEBUG
, "TLS: %s in commonName found",
1572 full
? "Match" : "Suffix match");
1577 wpa_printf(MSG_DEBUG
, "TLS: No CommonName %smatch found",
1578 full
? "": "suffix ");
1580 #endif /* CONFIG_NATIVE_WINDOWS */
1584 static enum tls_fail_reason
openssl_tls_fail_reason(int err
)
1587 case X509_V_ERR_CERT_REVOKED
:
1588 return TLS_FAIL_REVOKED
;
1589 case X509_V_ERR_CERT_NOT_YET_VALID
:
1590 case X509_V_ERR_CRL_NOT_YET_VALID
:
1591 return TLS_FAIL_NOT_YET_VALID
;
1592 case X509_V_ERR_CERT_HAS_EXPIRED
:
1593 case X509_V_ERR_CRL_HAS_EXPIRED
:
1594 return TLS_FAIL_EXPIRED
;
1595 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
:
1596 case X509_V_ERR_UNABLE_TO_GET_CRL
:
1597 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
:
1598 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
:
1599 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
:
1600 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
:
1601 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE
:
1602 case X509_V_ERR_CERT_CHAIN_TOO_LONG
:
1603 case X509_V_ERR_PATH_LENGTH_EXCEEDED
:
1604 case X509_V_ERR_INVALID_CA
:
1605 return TLS_FAIL_UNTRUSTED
;
1606 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE
:
1607 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE
:
1608 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY
:
1609 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD
:
1610 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD
:
1611 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD
:
1612 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD
:
1613 case X509_V_ERR_CERT_UNTRUSTED
:
1614 case X509_V_ERR_CERT_REJECTED
:
1615 return TLS_FAIL_BAD_CERTIFICATE
;
1617 return TLS_FAIL_UNSPECIFIED
;
1622 static struct wpabuf
* get_x509_cert(X509
*cert
)
1627 int cert_len
= i2d_X509(cert
, NULL
);
1631 buf
= wpabuf_alloc(cert_len
);
1635 tmp
= wpabuf_put(buf
, cert_len
);
1636 i2d_X509(cert
, &tmp
);
1641 static void openssl_tls_fail_event(struct tls_connection
*conn
,
1642 X509
*err_cert
, int err
, int depth
,
1643 const char *subject
, const char *err_str
,
1644 enum tls_fail_reason reason
)
1646 union tls_event_data ev
;
1647 struct wpabuf
*cert
= NULL
;
1648 struct tls_context
*context
= conn
->context
;
1650 if (context
->event_cb
== NULL
)
1653 cert
= get_x509_cert(err_cert
);
1654 os_memset(&ev
, 0, sizeof(ev
));
1655 ev
.cert_fail
.reason
= reason
!= TLS_FAIL_UNSPECIFIED
?
1656 reason
: openssl_tls_fail_reason(err
);
1657 ev
.cert_fail
.depth
= depth
;
1658 ev
.cert_fail
.subject
= subject
;
1659 ev
.cert_fail
.reason_txt
= err_str
;
1660 ev
.cert_fail
.cert
= cert
;
1661 context
->event_cb(context
->cb_ctx
, TLS_CERT_CHAIN_FAILURE
, &ev
);
1666 static void openssl_tls_cert_event(struct tls_connection
*conn
,
1667 X509
*err_cert
, int depth
,
1668 const char *subject
)
1670 struct wpabuf
*cert
= NULL
;
1671 union tls_event_data ev
;
1672 struct tls_context
*context
= conn
->context
;
1673 char *altsubject
[TLS_MAX_ALT_SUBJECT
];
1674 int alt
, num_altsubject
= 0;
1678 #ifdef CONFIG_SHA256
1680 #endif /* CONFIG_SHA256 */
1682 if (context
->event_cb
== NULL
)
1685 os_memset(&ev
, 0, sizeof(ev
));
1686 if (conn
->cert_probe
|| (conn
->flags
& TLS_CONN_EXT_CERT_CHECK
) ||
1687 context
->cert_in_cb
) {
1688 cert
= get_x509_cert(err_cert
);
1689 ev
.peer_cert
.cert
= cert
;
1691 #ifdef CONFIG_SHA256
1695 addr
[0] = wpabuf_head(cert
);
1696 len
[0] = wpabuf_len(cert
);
1697 if (sha256_vector(1, addr
, len
, hash
) == 0) {
1698 ev
.peer_cert
.hash
= hash
;
1699 ev
.peer_cert
.hash_len
= sizeof(hash
);
1702 #endif /* CONFIG_SHA256 */
1703 ev
.peer_cert
.depth
= depth
;
1704 ev
.peer_cert
.subject
= subject
;
1706 ext
= X509_get_ext_d2i(err_cert
, NID_subject_alt_name
, NULL
, NULL
);
1707 for (i
= 0; ext
&& i
< sk_GENERAL_NAME_num(ext
); i
++) {
1710 if (num_altsubject
== TLS_MAX_ALT_SUBJECT
)
1712 gen
= sk_GENERAL_NAME_value(ext
, i
);
1713 if (gen
->type
!= GEN_EMAIL
&&
1714 gen
->type
!= GEN_DNS
&&
1715 gen
->type
!= GEN_URI
)
1718 pos
= os_malloc(10 + gen
->d
.ia5
->length
+ 1);
1721 altsubject
[num_altsubject
++] = pos
;
1723 switch (gen
->type
) {
1725 os_memcpy(pos
, "EMAIL:", 6);
1729 os_memcpy(pos
, "DNS:", 4);
1733 os_memcpy(pos
, "URI:", 4);
1738 os_memcpy(pos
, gen
->d
.ia5
->data
, gen
->d
.ia5
->length
);
1739 pos
+= gen
->d
.ia5
->length
;
1742 sk_GENERAL_NAME_pop_free(ext
, GENERAL_NAME_free
);
1744 for (alt
= 0; alt
< num_altsubject
; alt
++)
1745 ev
.peer_cert
.altsubject
[alt
] = altsubject
[alt
];
1746 ev
.peer_cert
.num_altsubject
= num_altsubject
;
1748 context
->event_cb(context
->cb_ctx
, TLS_PEER_CERTIFICATE
, &ev
);
1750 for (alt
= 0; alt
< num_altsubject
; alt
++)
1751 os_free(altsubject
[alt
]);
1755 static int tls_verify_cb(int preverify_ok
, X509_STORE_CTX
*x509_ctx
)
1761 struct tls_connection
*conn
;
1762 struct tls_context
*context
;
1763 char *match
, *altmatch
, *suffix_match
, *domain_match
;
1764 const char *err_str
;
1766 err_cert
= X509_STORE_CTX_get_current_cert(x509_ctx
);
1770 err
= X509_STORE_CTX_get_error(x509_ctx
);
1771 depth
= X509_STORE_CTX_get_error_depth(x509_ctx
);
1772 ssl
= X509_STORE_CTX_get_ex_data(x509_ctx
,
1773 SSL_get_ex_data_X509_STORE_CTX_idx());
1774 X509_NAME_oneline(X509_get_subject_name(err_cert
), buf
, sizeof(buf
));
1776 conn
= SSL_get_app_data(ssl
);
1781 conn
->peer_cert
= err_cert
;
1782 else if (depth
== 1)
1783 conn
->peer_issuer
= err_cert
;
1784 else if (depth
== 2)
1785 conn
->peer_issuer_issuer
= err_cert
;
1787 context
= conn
->context
;
1788 match
= conn
->subject_match
;
1789 altmatch
= conn
->altsubject_match
;
1790 suffix_match
= conn
->suffix_match
;
1791 domain_match
= conn
->domain_match
;
1793 if (!preverify_ok
&& !conn
->ca_cert_verify
)
1795 if (!preverify_ok
&& depth
> 0 && conn
->server_cert_only
)
1797 if (!preverify_ok
&& (conn
->flags
& TLS_CONN_DISABLE_TIME_CHECKS
) &&
1798 (err
== X509_V_ERR_CERT_HAS_EXPIRED
||
1799 err
== X509_V_ERR_CERT_NOT_YET_VALID
)) {
1800 wpa_printf(MSG_DEBUG
, "OpenSSL: Ignore certificate validity "
1805 err_str
= X509_verify_cert_error_string(err
);
1807 #ifdef CONFIG_SHA256
1809 * Do not require preverify_ok so we can explicity allow otherwise
1810 * invalid pinned server certificates.
1812 if (depth
== 0 && conn
->server_cert_only
) {
1813 struct wpabuf
*cert
;
1814 cert
= get_x509_cert(err_cert
);
1816 wpa_printf(MSG_DEBUG
, "OpenSSL: Could not fetch "
1817 "server certificate data");
1823 addr
[0] = wpabuf_head(cert
);
1824 len
[0] = wpabuf_len(cert
);
1825 if (sha256_vector(1, addr
, len
, hash
) < 0 ||
1826 os_memcmp(conn
->srv_cert_hash
, hash
, 32) != 0) {
1827 err_str
= "Server certificate mismatch";
1828 err
= X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
;
1830 } else if (!preverify_ok
) {
1832 * Certificate matches pinned certificate, allow
1833 * regardless of other problems.
1835 wpa_printf(MSG_DEBUG
,
1836 "OpenSSL: Ignore validation issues for a pinned server certificate");
1842 #endif /* CONFIG_SHA256 */
1844 if (!preverify_ok
) {
1845 wpa_printf(MSG_WARNING
, "TLS: Certificate verification failed,"
1846 " error %d (%s) depth %d for '%s'", err
, err_str
,
1848 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1849 err_str
, TLS_FAIL_UNSPECIFIED
);
1850 return preverify_ok
;
1853 wpa_printf(MSG_DEBUG
, "TLS: tls_verify_cb - preverify_ok=%d "
1854 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1855 preverify_ok
, err
, err_str
,
1856 conn
->ca_cert_verify
, depth
, buf
);
1857 if (depth
== 0 && match
&& os_strstr(buf
, match
) == NULL
) {
1858 wpa_printf(MSG_WARNING
, "TLS: Subject '%s' did not "
1859 "match with '%s'", buf
, match
);
1861 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1863 TLS_FAIL_SUBJECT_MISMATCH
);
1864 } else if (depth
== 0 && altmatch
&&
1865 !tls_match_altsubject(err_cert
, altmatch
)) {
1866 wpa_printf(MSG_WARNING
, "TLS: altSubjectName match "
1867 "'%s' not found", altmatch
);
1869 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1870 "AltSubject mismatch",
1871 TLS_FAIL_ALTSUBJECT_MISMATCH
);
1872 } else if (depth
== 0 && suffix_match
&&
1873 !tls_match_suffix(err_cert
, suffix_match
, 0)) {
1874 wpa_printf(MSG_WARNING
, "TLS: Domain suffix match '%s' not found",
1877 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1878 "Domain suffix mismatch",
1879 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH
);
1880 } else if (depth
== 0 && domain_match
&&
1881 !tls_match_suffix(err_cert
, domain_match
, 1)) {
1882 wpa_printf(MSG_WARNING
, "TLS: Domain match '%s' not found",
1885 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1887 TLS_FAIL_DOMAIN_MISMATCH
);
1889 openssl_tls_cert_event(conn
, err_cert
, depth
, buf
);
1891 if (conn
->cert_probe
&& preverify_ok
&& depth
== 0) {
1892 wpa_printf(MSG_DEBUG
, "OpenSSL: Reject server certificate "
1893 "on probe-only run");
1895 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1896 "Server certificate chain probe",
1897 TLS_FAIL_SERVER_CHAIN_PROBE
);
1900 #ifdef OPENSSL_IS_BORINGSSL
1901 if (depth
== 0 && (conn
->flags
& TLS_CONN_REQUEST_OCSP
) &&
1903 enum ocsp_result res
;
1905 res
= check_ocsp_resp(conn
->ssl_ctx
, conn
->ssl
, err_cert
,
1907 conn
->peer_issuer_issuer
);
1908 if (res
== OCSP_REVOKED
) {
1910 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1911 "certificate revoked",
1913 if (err
== X509_V_OK
)
1914 X509_STORE_CTX_set_error(
1915 x509_ctx
, X509_V_ERR_CERT_REVOKED
);
1916 } else if (res
!= OCSP_GOOD
&&
1917 (conn
->flags
& TLS_CONN_REQUIRE_OCSP
)) {
1919 openssl_tls_fail_event(conn
, err_cert
, err
, depth
, buf
,
1920 "bad certificate status response",
1921 TLS_FAIL_UNSPECIFIED
);
1924 #endif /* OPENSSL_IS_BORINGSSL */
1926 if (depth
== 0 && preverify_ok
&& context
->event_cb
!= NULL
)
1927 context
->event_cb(context
->cb_ctx
,
1928 TLS_CERT_CHAIN_SUCCESS
, NULL
);
1930 return preverify_ok
;
1934 #ifndef OPENSSL_NO_STDIO
1935 static int tls_load_ca_der(struct tls_data
*data
, const char *ca_cert
)
1937 SSL_CTX
*ssl_ctx
= data
->ssl
;
1938 X509_LOOKUP
*lookup
;
1941 lookup
= X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx
),
1942 X509_LOOKUP_file());
1943 if (lookup
== NULL
) {
1944 tls_show_errors(MSG_WARNING
, __func__
,
1945 "Failed add lookup for X509 store");
1949 if (!X509_LOOKUP_load_file(lookup
, ca_cert
, X509_FILETYPE_ASN1
)) {
1950 unsigned long err
= ERR_peek_error();
1951 tls_show_errors(MSG_WARNING
, __func__
,
1952 "Failed load CA in DER format");
1953 if (ERR_GET_LIB(err
) == ERR_LIB_X509
&&
1954 ERR_GET_REASON(err
) == X509_R_CERT_ALREADY_IN_HASH_TABLE
) {
1955 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - ignoring "
1956 "cert already in hash table error",
1964 #endif /* OPENSSL_NO_STDIO */
1967 static int tls_connection_ca_cert(struct tls_data
*data
,
1968 struct tls_connection
*conn
,
1969 const char *ca_cert
, const u8
*ca_cert_blob
,
1970 size_t ca_cert_blob_len
, const char *ca_path
)
1972 SSL_CTX
*ssl_ctx
= data
->ssl
;
1976 * Remove previously configured trusted CA certificates before adding
1979 store
= X509_STORE_new();
1980 if (store
== NULL
) {
1981 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - failed to allocate new "
1982 "certificate store", __func__
);
1985 SSL_CTX_set_cert_store(ssl_ctx
, store
);
1987 SSL_set_verify(conn
->ssl
, SSL_VERIFY_PEER
, tls_verify_cb
);
1988 conn
->ca_cert_verify
= 1;
1990 if (ca_cert
&& os_strncmp(ca_cert
, "probe://", 8) == 0) {
1991 wpa_printf(MSG_DEBUG
, "OpenSSL: Probe for server certificate "
1993 conn
->cert_probe
= 1;
1994 conn
->ca_cert_verify
= 0;
1998 if (ca_cert
&& os_strncmp(ca_cert
, "hash://", 7) == 0) {
1999 #ifdef CONFIG_SHA256
2000 const char *pos
= ca_cert
+ 7;
2001 if (os_strncmp(pos
, "server/sha256/", 14) != 0) {
2002 wpa_printf(MSG_DEBUG
, "OpenSSL: Unsupported ca_cert "
2003 "hash value '%s'", ca_cert
);
2007 if (os_strlen(pos
) != 32 * 2) {
2008 wpa_printf(MSG_DEBUG
, "OpenSSL: Unexpected SHA256 "
2009 "hash length in ca_cert '%s'", ca_cert
);
2012 if (hexstr2bin(pos
, conn
->srv_cert_hash
, 32) < 0) {
2013 wpa_printf(MSG_DEBUG
, "OpenSSL: Invalid SHA256 hash "
2014 "value in ca_cert '%s'", ca_cert
);
2017 conn
->server_cert_only
= 1;
2018 wpa_printf(MSG_DEBUG
, "OpenSSL: Checking only server "
2019 "certificate match");
2021 #else /* CONFIG_SHA256 */
2022 wpa_printf(MSG_INFO
, "No SHA256 included in the build - "
2023 "cannot validate server certificate hash");
2025 #endif /* CONFIG_SHA256 */
2029 X509
*cert
= d2i_X509(NULL
,
2030 (const unsigned char **) &ca_cert_blob
,
2033 tls_show_errors(MSG_WARNING
, __func__
,
2034 "Failed to parse ca_cert_blob");
2038 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx
),
2040 unsigned long err
= ERR_peek_error();
2041 tls_show_errors(MSG_WARNING
, __func__
,
2042 "Failed to add ca_cert_blob to "
2043 "certificate store");
2044 if (ERR_GET_LIB(err
) == ERR_LIB_X509
&&
2045 ERR_GET_REASON(err
) ==
2046 X509_R_CERT_ALREADY_IN_HASH_TABLE
) {
2047 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - ignoring "
2048 "cert already in hash table error",
2056 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - added ca_cert_blob "
2057 "to certificate store", __func__
);
2063 if (ca_cert
&& os_strncmp("keystore://", ca_cert
, 11) == 0) {
2064 if (tls_add_ca_from_keystore(ssl_ctx
->cert_store
,
2067 SSL_set_verify(conn
->ssl
, SSL_VERIFY_PEER
, tls_verify_cb
);
2071 /* Multiple aliases separated by space */
2072 if (ca_cert
&& os_strncmp("keystores://", ca_cert
, 12) == 0) {
2073 char *aliases
= os_strdup(&ca_cert
[12]);
2074 const char *delim
= " ";
2081 alias
= strtok_r(aliases
, delim
, &savedptr
);
2082 for (; alias
; alias
= strtok_r(NULL
, delim
, &savedptr
)) {
2083 if (tls_add_ca_from_keystore_encoded(
2084 ssl_ctx
->cert_store
, alias
)) {
2085 wpa_printf(MSG_WARNING
,
2086 "OpenSSL: %s - Failed to add ca_cert %s from keystore",
2096 SSL_set_verify(conn
->ssl
, SSL_VERIFY_PEER
, tls_verify_cb
);
2099 #endif /* ANDROID */
2101 #ifdef CONFIG_NATIVE_WINDOWS
2102 if (ca_cert
&& tls_cryptoapi_ca_cert(ssl_ctx
, conn
->ssl
, ca_cert
) ==
2104 wpa_printf(MSG_DEBUG
, "OpenSSL: Added CA certificates from "
2105 "system certificate store");
2108 #endif /* CONFIG_NATIVE_WINDOWS */
2110 if (ca_cert
|| ca_path
) {
2111 #ifndef OPENSSL_NO_STDIO
2112 if (SSL_CTX_load_verify_locations(ssl_ctx
, ca_cert
, ca_path
) !=
2114 tls_show_errors(MSG_WARNING
, __func__
,
2115 "Failed to load root certificates");
2117 tls_load_ca_der(data
, ca_cert
) == 0) {
2118 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - loaded "
2119 "DER format CA certificate",
2124 wpa_printf(MSG_DEBUG
, "TLS: Trusted root "
2125 "certificate(s) loaded");
2126 tls_get_errors(data
);
2128 #else /* OPENSSL_NO_STDIO */
2129 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - OPENSSL_NO_STDIO",
2132 #endif /* OPENSSL_NO_STDIO */
2134 /* No ca_cert configured - do not try to verify server
2136 conn
->ca_cert_verify
= 0;
2143 static int tls_global_ca_cert(struct tls_data
*data
, const char *ca_cert
)
2145 SSL_CTX
*ssl_ctx
= data
->ssl
;
2148 if (SSL_CTX_load_verify_locations(ssl_ctx
, ca_cert
, NULL
) != 1)
2150 tls_show_errors(MSG_WARNING
, __func__
,
2151 "Failed to load root certificates");
2155 wpa_printf(MSG_DEBUG
, "TLS: Trusted root "
2156 "certificate(s) loaded");
2158 #ifndef OPENSSL_NO_STDIO
2159 /* Add the same CAs to the client certificate requests */
2160 SSL_CTX_set_client_CA_list(ssl_ctx
,
2161 SSL_load_client_CA_file(ca_cert
));
2162 #endif /* OPENSSL_NO_STDIO */
2169 int tls_global_set_verify(void *ssl_ctx
, int check_crl
)
2174 struct tls_data
*data
= ssl_ctx
;
2175 X509_STORE
*cs
= SSL_CTX_get_cert_store(data
->ssl
);
2177 tls_show_errors(MSG_INFO
, __func__
, "Failed to get "
2178 "certificate store when enabling "
2182 flags
= X509_V_FLAG_CRL_CHECK
;
2184 flags
|= X509_V_FLAG_CRL_CHECK_ALL
;
2185 X509_STORE_set_flags(cs
, flags
);
2191 static int tls_connection_set_subject_match(struct tls_connection
*conn
,
2192 const char *subject_match
,
2193 const char *altsubject_match
,
2194 const char *suffix_match
,
2195 const char *domain_match
)
2197 os_free(conn
->subject_match
);
2198 conn
->subject_match
= NULL
;
2199 if (subject_match
) {
2200 conn
->subject_match
= os_strdup(subject_match
);
2201 if (conn
->subject_match
== NULL
)
2205 os_free(conn
->altsubject_match
);
2206 conn
->altsubject_match
= NULL
;
2207 if (altsubject_match
) {
2208 conn
->altsubject_match
= os_strdup(altsubject_match
);
2209 if (conn
->altsubject_match
== NULL
)
2213 os_free(conn
->suffix_match
);
2214 conn
->suffix_match
= NULL
;
2216 conn
->suffix_match
= os_strdup(suffix_match
);
2217 if (conn
->suffix_match
== NULL
)
2221 os_free(conn
->domain_match
);
2222 conn
->domain_match
= NULL
;
2224 conn
->domain_match
= os_strdup(domain_match
);
2225 if (conn
->domain_match
== NULL
)
2233 static void tls_set_conn_flags(SSL
*ssl
, unsigned int flags
)
2235 #ifdef SSL_OP_NO_TICKET
2236 if (flags
& TLS_CONN_DISABLE_SESSION_TICKET
)
2237 SSL_set_options(ssl
, SSL_OP_NO_TICKET
);
2238 #ifdef SSL_clear_options
2240 SSL_clear_options(ssl
, SSL_OP_NO_TICKET
);
2241 #endif /* SSL_clear_options */
2242 #endif /* SSL_OP_NO_TICKET */
2244 #ifdef SSL_OP_NO_TLSv1
2245 if (flags
& TLS_CONN_DISABLE_TLSv1_0
)
2246 SSL_set_options(ssl
, SSL_OP_NO_TLSv1
);
2248 SSL_clear_options(ssl
, SSL_OP_NO_TLSv1
);
2249 #endif /* SSL_OP_NO_TLSv1 */
2250 #ifdef SSL_OP_NO_TLSv1_1
2251 if (flags
& TLS_CONN_DISABLE_TLSv1_1
)
2252 SSL_set_options(ssl
, SSL_OP_NO_TLSv1_1
);
2254 SSL_clear_options(ssl
, SSL_OP_NO_TLSv1_1
);
2255 #endif /* SSL_OP_NO_TLSv1_1 */
2256 #ifdef SSL_OP_NO_TLSv1_2
2257 if (flags
& TLS_CONN_DISABLE_TLSv1_2
)
2258 SSL_set_options(ssl
, SSL_OP_NO_TLSv1_2
);
2260 SSL_clear_options(ssl
, SSL_OP_NO_TLSv1_2
);
2261 #endif /* SSL_OP_NO_TLSv1_2 */
2265 int tls_connection_set_verify(void *ssl_ctx
, struct tls_connection
*conn
,
2266 int verify_peer
, unsigned int flags
,
2267 const u8
*session_ctx
, size_t session_ctx_len
)
2269 static int counter
= 0;
2270 struct tls_data
*data
= ssl_ctx
;
2276 conn
->ca_cert_verify
= 1;
2277 SSL_set_verify(conn
->ssl
, SSL_VERIFY_PEER
|
2278 SSL_VERIFY_FAIL_IF_NO_PEER_CERT
|
2279 SSL_VERIFY_CLIENT_ONCE
, tls_verify_cb
);
2281 conn
->ca_cert_verify
= 0;
2282 SSL_set_verify(conn
->ssl
, SSL_VERIFY_NONE
, NULL
);
2285 tls_set_conn_flags(conn
->ssl
, flags
);
2286 conn
->flags
= flags
;
2288 SSL_set_accept_state(conn
->ssl
);
2290 if (data
->tls_session_lifetime
== 0) {
2292 * Set session id context to a unique value to make sure
2293 * session resumption cannot be used either through session
2294 * caching or TLS ticket extension.
2297 SSL_set_session_id_context(conn
->ssl
,
2298 (const unsigned char *) &counter
,
2300 } else if (session_ctx
) {
2301 SSL_set_session_id_context(conn
->ssl
, session_ctx
,
2309 static int tls_connection_client_cert(struct tls_connection
*conn
,
2310 const char *client_cert
,
2311 const u8
*client_cert_blob
,
2312 size_t client_cert_blob_len
)
2314 if (client_cert
== NULL
&& client_cert_blob
== NULL
)
2318 #if OPENSSL_VERSION_NUMBER < 0x10002000L
2320 * Clear previously set extra chain certificates, if any, from PKCS#12
2321 * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
2324 SSL_CTX_clear_extra_chain_certs(conn
->ssl_ctx
);
2325 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
2326 #endif /* PKCS12_FUNCS */
2328 if (client_cert_blob
&&
2329 SSL_use_certificate_ASN1(conn
->ssl
, (u8
*) client_cert_blob
,
2330 client_cert_blob_len
) == 1) {
2331 wpa_printf(MSG_DEBUG
, "OpenSSL: SSL_use_certificate_ASN1 --> "
2334 } else if (client_cert_blob
) {
2335 tls_show_errors(MSG_DEBUG
, __func__
,
2336 "SSL_use_certificate_ASN1 failed");
2339 if (client_cert
== NULL
)
2343 if (os_strncmp("keystore://", client_cert
, 11) == 0) {
2344 BIO
*bio
= BIO_from_keystore(&client_cert
[11]);
2348 x509
= PEM_read_bio_X509(bio
, NULL
, NULL
, NULL
);
2352 if (SSL_use_certificate(conn
->ssl
, x509
) == 1)
2358 #endif /* ANDROID */
2360 #ifndef OPENSSL_NO_STDIO
2361 if (SSL_use_certificate_file(conn
->ssl
, client_cert
,
2362 SSL_FILETYPE_ASN1
) == 1) {
2363 wpa_printf(MSG_DEBUG
, "OpenSSL: SSL_use_certificate_file (DER)"
2368 if (SSL_use_certificate_file(conn
->ssl
, client_cert
,
2369 SSL_FILETYPE_PEM
) == 1) {
2371 wpa_printf(MSG_DEBUG
, "OpenSSL: SSL_use_certificate_file (PEM)"
2376 tls_show_errors(MSG_DEBUG
, __func__
,
2377 "SSL_use_certificate_file failed");
2378 #else /* OPENSSL_NO_STDIO */
2379 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__
);
2380 #endif /* OPENSSL_NO_STDIO */
2386 static int tls_global_client_cert(struct tls_data
*data
,
2387 const char *client_cert
)
2389 #ifndef OPENSSL_NO_STDIO
2390 SSL_CTX
*ssl_ctx
= data
->ssl
;
2392 if (client_cert
== NULL
)
2395 if (SSL_CTX_use_certificate_file(ssl_ctx
, client_cert
,
2396 SSL_FILETYPE_ASN1
) != 1 &&
2397 SSL_CTX_use_certificate_chain_file(ssl_ctx
, client_cert
) != 1 &&
2398 SSL_CTX_use_certificate_file(ssl_ctx
, client_cert
,
2399 SSL_FILETYPE_PEM
) != 1) {
2400 tls_show_errors(MSG_INFO
, __func__
,
2401 "Failed to load client certificate");
2405 #else /* OPENSSL_NO_STDIO */
2406 if (client_cert
== NULL
)
2408 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__
);
2410 #endif /* OPENSSL_NO_STDIO */
2414 static int tls_passwd_cb(char *buf
, int size
, int rwflag
, void *password
)
2416 if (password
== NULL
) {
2419 os_strlcpy(buf
, (char *) password
, size
);
2420 return os_strlen(buf
);
2425 static int tls_parse_pkcs12(struct tls_data
*data
, SSL
*ssl
, PKCS12
*p12
,
2430 STACK_OF(X509
) *certs
;
2439 if (!PKCS12_parse(p12
, passwd
, &pkey
, &cert
, &certs
)) {
2440 tls_show_errors(MSG_DEBUG
, __func__
,
2441 "Failed to parse PKCS12 file");
2445 wpa_printf(MSG_DEBUG
, "TLS: Successfully parsed PKCS12 data");
2448 X509_NAME_oneline(X509_get_subject_name(cert
), buf
,
2450 wpa_printf(MSG_DEBUG
, "TLS: Got certificate from PKCS12: "
2451 "subject='%s'", buf
);
2453 if (SSL_use_certificate(ssl
, cert
) != 1)
2456 if (SSL_CTX_use_certificate(data
->ssl
, cert
) != 1)
2463 wpa_printf(MSG_DEBUG
, "TLS: Got private key from PKCS12");
2465 if (SSL_use_PrivateKey(ssl
, pkey
) != 1)
2468 if (SSL_CTX_use_PrivateKey(data
->ssl
, pkey
) != 1)
2471 EVP_PKEY_free(pkey
);
2475 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
2477 SSL_clear_chain_certs(ssl
);
2479 SSL_CTX_clear_chain_certs(data
->ssl
);
2480 while ((cert
= sk_X509_pop(certs
)) != NULL
) {
2481 X509_NAME_oneline(X509_get_subject_name(cert
), buf
,
2483 wpa_printf(MSG_DEBUG
, "TLS: additional certificate"
2484 " from PKCS12: subject='%s'", buf
);
2485 if ((ssl
&& SSL_add1_chain_cert(ssl
, cert
) != 1) ||
2486 (!ssl
&& SSL_CTX_add1_chain_cert(data
->ssl
,
2488 tls_show_errors(MSG_DEBUG
, __func__
,
2489 "Failed to add additional certificate");
2495 /* Try to continue anyway */
2497 sk_X509_free(certs
);
2498 #ifndef OPENSSL_IS_BORINGSSL
2500 res
= SSL_build_cert_chain(
2502 SSL_BUILD_CHAIN_FLAG_CHECK
|
2503 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR
);
2505 res
= SSL_CTX_build_cert_chain(
2507 SSL_BUILD_CHAIN_FLAG_CHECK
|
2508 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR
);
2510 tls_show_errors(MSG_DEBUG
, __func__
,
2511 "Failed to build certificate chain");
2512 } else if (res
== 2) {
2513 wpa_printf(MSG_DEBUG
,
2514 "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2516 #endif /* OPENSSL_IS_BORINGSSL */
2518 * Try to continue regardless of result since it is possible for
2519 * the extra certificates not to be required.
2522 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2523 SSL_CTX_clear_extra_chain_certs(data
->ssl
);
2524 while ((cert
= sk_X509_pop(certs
)) != NULL
) {
2525 X509_NAME_oneline(X509_get_subject_name(cert
), buf
,
2527 wpa_printf(MSG_DEBUG
, "TLS: additional certificate"
2528 " from PKCS12: subject='%s'", buf
);
2530 * There is no SSL equivalent for the chain cert - so
2531 * always add it to the context...
2533 if (SSL_CTX_add_extra_chain_cert(data
->ssl
, cert
) != 1)
2539 sk_X509_free(certs
);
2540 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2546 tls_get_errors(data
);
2550 #endif /* PKCS12_FUNCS */
2553 static int tls_read_pkcs12(struct tls_data
*data
, SSL
*ssl
,
2554 const char *private_key
, const char *passwd
)
2560 f
= fopen(private_key
, "rb");
2564 p12
= d2i_PKCS12_fp(f
, NULL
);
2568 tls_show_errors(MSG_INFO
, __func__
,
2569 "Failed to use PKCS#12 file");
2573 return tls_parse_pkcs12(data
, ssl
, p12
, passwd
);
2575 #else /* PKCS12_FUNCS */
2576 wpa_printf(MSG_INFO
, "TLS: PKCS12 support disabled - cannot read "
2579 #endif /* PKCS12_FUNCS */
2583 static int tls_read_pkcs12_blob(struct tls_data
*data
, SSL
*ssl
,
2584 const u8
*blob
, size_t len
, const char *passwd
)
2589 p12
= d2i_PKCS12(NULL
, (const unsigned char **) &blob
, len
);
2591 tls_show_errors(MSG_INFO
, __func__
,
2592 "Failed to use PKCS#12 blob");
2596 return tls_parse_pkcs12(data
, ssl
, p12
, passwd
);
2598 #else /* PKCS12_FUNCS */
2599 wpa_printf(MSG_INFO
, "TLS: PKCS12 support disabled - cannot parse "
2602 #endif /* PKCS12_FUNCS */
2606 #ifndef OPENSSL_NO_ENGINE
2607 static int tls_engine_get_cert(struct tls_connection
*conn
,
2608 const char *cert_id
,
2611 /* this runs after the private key is loaded so no PIN is required */
2613 const char *cert_id
;
2616 params
.cert_id
= cert_id
;
2619 if (!ENGINE_ctrl_cmd(conn
->engine
, "LOAD_CERT_CTRL",
2620 0, ¶ms
, NULL
, 1)) {
2621 unsigned long err
= ERR_get_error();
2623 wpa_printf(MSG_ERROR
, "ENGINE: cannot load client cert with id"
2624 " '%s' [%s]", cert_id
,
2625 ERR_error_string(err
, NULL
));
2626 if (tls_is_pin_error(err
))
2627 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN
;
2628 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED
;
2631 wpa_printf(MSG_ERROR
, "ENGINE: did not properly cert with id"
2633 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED
;
2635 *cert
= params
.cert
;
2638 #endif /* OPENSSL_NO_ENGINE */
2641 static int tls_connection_engine_client_cert(struct tls_connection
*conn
,
2642 const char *cert_id
)
2644 #ifndef OPENSSL_NO_ENGINE
2647 if (tls_engine_get_cert(conn
, cert_id
, &cert
))
2650 if (!SSL_use_certificate(conn
->ssl
, cert
)) {
2651 tls_show_errors(MSG_ERROR
, __func__
,
2652 "SSL_use_certificate failed");
2657 wpa_printf(MSG_DEBUG
, "ENGINE: SSL_use_certificate --> "
2661 #else /* OPENSSL_NO_ENGINE */
2663 #endif /* OPENSSL_NO_ENGINE */
2667 static int tls_connection_engine_ca_cert(struct tls_data
*data
,
2668 struct tls_connection
*conn
,
2669 const char *ca_cert_id
)
2671 #ifndef OPENSSL_NO_ENGINE
2673 SSL_CTX
*ssl_ctx
= data
->ssl
;
2676 if (tls_engine_get_cert(conn
, ca_cert_id
, &cert
))
2679 /* start off the same as tls_connection_ca_cert */
2680 store
= X509_STORE_new();
2681 if (store
== NULL
) {
2682 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - failed to allocate new "
2683 "certificate store", __func__
);
2687 SSL_CTX_set_cert_store(ssl_ctx
, store
);
2688 if (!X509_STORE_add_cert(store
, cert
)) {
2689 unsigned long err
= ERR_peek_error();
2690 tls_show_errors(MSG_WARNING
, __func__
,
2691 "Failed to add CA certificate from engine "
2692 "to certificate store");
2693 if (ERR_GET_LIB(err
) == ERR_LIB_X509
&&
2694 ERR_GET_REASON(err
) == X509_R_CERT_ALREADY_IN_HASH_TABLE
) {
2695 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - ignoring cert"
2696 " already in hash table error",
2704 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - added CA certificate from engine "
2705 "to certificate store", __func__
);
2706 SSL_set_verify(conn
->ssl
, SSL_VERIFY_PEER
, tls_verify_cb
);
2707 conn
->ca_cert_verify
= 1;
2711 #else /* OPENSSL_NO_ENGINE */
2713 #endif /* OPENSSL_NO_ENGINE */
2717 static int tls_connection_engine_private_key(struct tls_connection
*conn
)
2719 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
2720 if (SSL_use_PrivateKey(conn
->ssl
, conn
->private_key
) != 1) {
2721 tls_show_errors(MSG_ERROR
, __func__
,
2722 "ENGINE: cannot use private key for TLS");
2725 if (!SSL_check_private_key(conn
->ssl
)) {
2726 tls_show_errors(MSG_INFO
, __func__
,
2727 "Private key failed verification");
2731 #else /* OPENSSL_NO_ENGINE */
2732 wpa_printf(MSG_ERROR
, "SSL: Configuration uses engine, but "
2733 "engine support was not compiled in");
2735 #endif /* OPENSSL_NO_ENGINE */
2739 static int tls_connection_private_key(struct tls_data
*data
,
2740 struct tls_connection
*conn
,
2741 const char *private_key
,
2742 const char *private_key_passwd
,
2743 const u8
*private_key_blob
,
2744 size_t private_key_blob_len
)
2746 SSL_CTX
*ssl_ctx
= data
->ssl
;
2750 if (private_key
== NULL
&& private_key_blob
== NULL
)
2753 if (private_key_passwd
) {
2754 passwd
= os_strdup(private_key_passwd
);
2760 SSL_CTX_set_default_passwd_cb(ssl_ctx
, tls_passwd_cb
);
2761 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx
, passwd
);
2764 while (private_key_blob
) {
2765 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA
, conn
->ssl
,
2766 (u8
*) private_key_blob
,
2767 private_key_blob_len
) == 1) {
2768 wpa_printf(MSG_DEBUG
, "OpenSSL: SSL_use_PrivateKey_"
2769 "ASN1(EVP_PKEY_RSA) --> OK");
2774 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA
, conn
->ssl
,
2775 (u8
*) private_key_blob
,
2776 private_key_blob_len
) == 1) {
2777 wpa_printf(MSG_DEBUG
, "OpenSSL: SSL_use_PrivateKey_"
2778 "ASN1(EVP_PKEY_DSA) --> OK");
2783 if (SSL_use_RSAPrivateKey_ASN1(conn
->ssl
,
2784 (u8
*) private_key_blob
,
2785 private_key_blob_len
) == 1) {
2786 wpa_printf(MSG_DEBUG
, "OpenSSL: "
2787 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2792 if (tls_read_pkcs12_blob(data
, conn
->ssl
, private_key_blob
,
2793 private_key_blob_len
, passwd
) == 0) {
2794 wpa_printf(MSG_DEBUG
, "OpenSSL: PKCS#12 as blob --> "
2803 while (!ok
&& private_key
) {
2804 #ifndef OPENSSL_NO_STDIO
2805 if (SSL_use_PrivateKey_file(conn
->ssl
, private_key
,
2806 SSL_FILETYPE_ASN1
) == 1) {
2807 wpa_printf(MSG_DEBUG
, "OpenSSL: "
2808 "SSL_use_PrivateKey_File (DER) --> OK");
2813 if (SSL_use_PrivateKey_file(conn
->ssl
, private_key
,
2814 SSL_FILETYPE_PEM
) == 1) {
2815 wpa_printf(MSG_DEBUG
, "OpenSSL: "
2816 "SSL_use_PrivateKey_File (PEM) --> OK");
2820 #else /* OPENSSL_NO_STDIO */
2821 wpa_printf(MSG_DEBUG
, "OpenSSL: %s - OPENSSL_NO_STDIO",
2823 #endif /* OPENSSL_NO_STDIO */
2825 if (tls_read_pkcs12(data
, conn
->ssl
, private_key
, passwd
)
2827 wpa_printf(MSG_DEBUG
, "OpenSSL: Reading PKCS#12 file "
2833 if (tls_cryptoapi_cert(conn
->ssl
, private_key
) == 0) {
2834 wpa_printf(MSG_DEBUG
, "OpenSSL: Using CryptoAPI to "
2835 "access certificate store --> OK");
2844 tls_show_errors(MSG_INFO
, __func__
,
2845 "Failed to load private key");
2850 SSL_CTX_set_default_passwd_cb(ssl_ctx
, NULL
);
2853 if (!SSL_check_private_key(conn
->ssl
)) {
2854 tls_show_errors(MSG_INFO
, __func__
, "Private key failed "
2859 wpa_printf(MSG_DEBUG
, "SSL: Private key loaded successfully");
2864 static int tls_global_private_key(struct tls_data
*data
,
2865 const char *private_key
,
2866 const char *private_key_passwd
)
2868 SSL_CTX
*ssl_ctx
= data
->ssl
;
2871 if (private_key
== NULL
)
2874 if (private_key_passwd
) {
2875 passwd
= os_strdup(private_key_passwd
);
2881 SSL_CTX_set_default_passwd_cb(ssl_ctx
, tls_passwd_cb
);
2882 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx
, passwd
);
2884 #ifndef OPENSSL_NO_STDIO
2885 SSL_CTX_use_PrivateKey_file(ssl_ctx
, private_key
,
2886 SSL_FILETYPE_ASN1
) != 1 &&
2887 SSL_CTX_use_PrivateKey_file(ssl_ctx
, private_key
,
2888 SSL_FILETYPE_PEM
) != 1 &&
2889 #endif /* OPENSSL_NO_STDIO */
2890 tls_read_pkcs12(data
, NULL
, private_key
, passwd
)) {
2891 tls_show_errors(MSG_INFO
, __func__
,
2892 "Failed to load private key");
2899 SSL_CTX_set_default_passwd_cb(ssl_ctx
, NULL
);
2901 if (!SSL_CTX_check_private_key(ssl_ctx
)) {
2902 tls_show_errors(MSG_INFO
, __func__
,
2903 "Private key failed verification");
2911 static int tls_connection_dh(struct tls_connection
*conn
, const char *dh_file
)
2913 #ifdef OPENSSL_NO_DH
2914 if (dh_file
== NULL
)
2916 wpa_printf(MSG_ERROR
, "TLS: openssl does not include DH support, but "
2917 "dh_file specified");
2919 #else /* OPENSSL_NO_DH */
2923 /* TODO: add support for dh_blob */
2924 if (dh_file
== NULL
)
2929 bio
= BIO_new_file(dh_file
, "r");
2931 wpa_printf(MSG_INFO
, "TLS: Failed to open DH file '%s': %s",
2932 dh_file
, ERR_error_string(ERR_get_error(), NULL
));
2935 dh
= PEM_read_bio_DHparams(bio
, NULL
, NULL
, NULL
);
2937 #ifndef OPENSSL_NO_DSA
2938 while (dh
== NULL
) {
2940 wpa_printf(MSG_DEBUG
, "TLS: Failed to parse DH file '%s': %s -"
2941 " trying to parse as DSA params", dh_file
,
2942 ERR_error_string(ERR_get_error(), NULL
));
2943 bio
= BIO_new_file(dh_file
, "r");
2946 dsa
= PEM_read_bio_DSAparams(bio
, NULL
, NULL
, NULL
);
2949 wpa_printf(MSG_DEBUG
, "TLS: Failed to parse DSA file "
2950 "'%s': %s", dh_file
,
2951 ERR_error_string(ERR_get_error(), NULL
));
2955 wpa_printf(MSG_DEBUG
, "TLS: DH file in DSA param format");
2956 dh
= DSA_dup_DH(dsa
);
2959 wpa_printf(MSG_INFO
, "TLS: Failed to convert DSA "
2960 "params into DH params");
2965 #endif /* !OPENSSL_NO_DSA */
2967 wpa_printf(MSG_INFO
, "TLS: Failed to read/parse DH/DSA file "
2972 if (SSL_set_tmp_dh(conn
->ssl
, dh
) != 1) {
2973 wpa_printf(MSG_INFO
, "TLS: Failed to set DH params from '%s': "
2975 ERR_error_string(ERR_get_error(), NULL
));
2981 #endif /* OPENSSL_NO_DH */
2985 static int tls_global_dh(struct tls_data
*data
, const char *dh_file
)
2987 #ifdef OPENSSL_NO_DH
2988 if (dh_file
== NULL
)
2990 wpa_printf(MSG_ERROR
, "TLS: openssl does not include DH support, but "
2991 "dh_file specified");
2993 #else /* OPENSSL_NO_DH */
2994 SSL_CTX
*ssl_ctx
= data
->ssl
;
2998 /* TODO: add support for dh_blob */
2999 if (dh_file
== NULL
)
3001 if (ssl_ctx
== NULL
)
3004 bio
= BIO_new_file(dh_file
, "r");
3006 wpa_printf(MSG_INFO
, "TLS: Failed to open DH file '%s': %s",
3007 dh_file
, ERR_error_string(ERR_get_error(), NULL
));
3010 dh
= PEM_read_bio_DHparams(bio
, NULL
, NULL
, NULL
);
3012 #ifndef OPENSSL_NO_DSA
3013 while (dh
== NULL
) {
3015 wpa_printf(MSG_DEBUG
, "TLS: Failed to parse DH file '%s': %s -"
3016 " trying to parse as DSA params", dh_file
,
3017 ERR_error_string(ERR_get_error(), NULL
));
3018 bio
= BIO_new_file(dh_file
, "r");
3021 dsa
= PEM_read_bio_DSAparams(bio
, NULL
, NULL
, NULL
);
3024 wpa_printf(MSG_DEBUG
, "TLS: Failed to parse DSA file "
3025 "'%s': %s", dh_file
,
3026 ERR_error_string(ERR_get_error(), NULL
));
3030 wpa_printf(MSG_DEBUG
, "TLS: DH file in DSA param format");
3031 dh
= DSA_dup_DH(dsa
);
3034 wpa_printf(MSG_INFO
, "TLS: Failed to convert DSA "
3035 "params into DH params");
3040 #endif /* !OPENSSL_NO_DSA */
3042 wpa_printf(MSG_INFO
, "TLS: Failed to read/parse DH/DSA file "
3047 if (SSL_CTX_set_tmp_dh(ssl_ctx
, dh
) != 1) {
3048 wpa_printf(MSG_INFO
, "TLS: Failed to set DH params from '%s': "
3050 ERR_error_string(ERR_get_error(), NULL
));
3056 #endif /* OPENSSL_NO_DH */
3060 int tls_connection_get_random(void *ssl_ctx
, struct tls_connection
*conn
,
3061 struct tls_random
*keys
)
3065 if (conn
== NULL
|| keys
== NULL
)
3071 os_memset(keys
, 0, sizeof(*keys
));
3072 keys
->client_random
= conn
->client_random
;
3073 keys
->client_random_len
= SSL_get_client_random(
3074 ssl
, conn
->client_random
, sizeof(conn
->client_random
));
3075 keys
->server_random
= conn
->server_random
;
3076 keys
->server_random_len
= SSL_get_server_random(
3077 ssl
, conn
->server_random
, sizeof(conn
->server_random
));
3084 static int openssl_get_keyblock_size(SSL
*ssl
)
3086 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
3087 const EVP_CIPHER
*c
;
3091 if (ssl
->enc_read_ctx
== NULL
|| ssl
->enc_read_ctx
->cipher
== NULL
||
3092 ssl
->read_hash
== NULL
)
3095 c
= ssl
->enc_read_ctx
->cipher
;
3096 h
= EVP_MD_CTX_md(ssl
->read_hash
);
3098 md_size
= EVP_MD_size(h
);
3100 md_size
= ssl
->s3
->tmp
.new_mac_secret_size
;
3104 wpa_printf(MSG_DEBUG
, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
3105 "IV_len=%d", EVP_CIPHER_key_length(c
), md_size
,
3106 EVP_CIPHER_iv_length(c
));
3107 return 2 * (EVP_CIPHER_key_length(c
) +
3109 EVP_CIPHER_iv_length(c
));
3111 const SSL_CIPHER
*ssl_cipher
;
3113 const EVP_CIPHER
*c
;
3116 ssl_cipher
= SSL_get_current_cipher(ssl
);
3119 cipher
= SSL_CIPHER_get_cipher_nid(ssl_cipher
);
3120 digest
= SSL_CIPHER_get_digest_nid(ssl_cipher
);
3121 wpa_printf(MSG_DEBUG
, "OpenSSL: cipher nid %d digest nid %d",
3123 if (cipher
< 0 || digest
< 0)
3125 c
= EVP_get_cipherbynid(cipher
);
3126 h
= EVP_get_digestbynid(digest
);
3130 wpa_printf(MSG_DEBUG
,
3131 "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
3132 EVP_CIPHER_key_length(c
), EVP_MD_size(h
),
3133 EVP_CIPHER_iv_length(c
));
3134 return 2 * (EVP_CIPHER_key_length(c
) + EVP_MD_size(h
) +
3135 EVP_CIPHER_iv_length(c
));
3138 #endif /* CONFIG_FIPS */
3141 static int openssl_tls_prf(struct tls_connection
*conn
,
3142 const char *label
, int server_random_first
,
3143 int skip_keyblock
, u8
*out
, size_t out_len
)
3146 wpa_printf(MSG_ERROR
, "OpenSSL: TLS keys cannot be exported in FIPS "
3149 #else /* CONFIG_FIPS */
3157 unsigned char client_random
[SSL3_RANDOM_SIZE
];
3158 unsigned char server_random
[SSL3_RANDOM_SIZE
];
3159 unsigned char master_key
[64];
3160 size_t master_key_len
;
3164 * TLS library did not support key generation, so get the needed TLS
3165 * session parameters and use an internal implementation of TLS PRF to
3174 ver
= SSL_get_version(ssl
);
3175 sess
= SSL_get_session(ssl
);
3179 if (skip_keyblock
) {
3180 skip
= openssl_get_keyblock_size(ssl
);
3183 tmp_out
= os_malloc(skip
+ out_len
);
3189 rnd
= os_malloc(2 * SSL3_RANDOM_SIZE
);
3195 SSL_get_client_random(ssl
, client_random
, sizeof(client_random
));
3196 SSL_get_server_random(ssl
, server_random
, sizeof(server_random
));
3197 master_key_len
= SSL_SESSION_get_master_key(sess
, master_key
,
3198 sizeof(master_key
));
3200 if (server_random_first
) {
3201 os_memcpy(rnd
, server_random
, SSL3_RANDOM_SIZE
);
3202 os_memcpy(rnd
+ SSL3_RANDOM_SIZE
, client_random
,
3205 os_memcpy(rnd
, client_random
, SSL3_RANDOM_SIZE
);
3206 os_memcpy(rnd
+ SSL3_RANDOM_SIZE
, server_random
,
3210 if (os_strcmp(ver
, "TLSv1.2") == 0) {
3211 tls_prf_sha256(master_key
, master_key_len
,
3212 label
, rnd
, 2 * SSL3_RANDOM_SIZE
,
3213 _out
, skip
+ out_len
);
3215 } else if (tls_prf_sha1_md5(master_key
, master_key_len
,
3216 label
, rnd
, 2 * SSL3_RANDOM_SIZE
,
3217 _out
, skip
+ out_len
) == 0) {
3220 os_memset(master_key
, 0, sizeof(master_key
));
3222 if (ret
== 0 && skip_keyblock
)
3223 os_memcpy(out
, _out
+ skip
, out_len
);
3224 bin_clear_free(tmp_out
, skip
);
3227 #endif /* CONFIG_FIPS */
3231 int tls_connection_prf(void *tls_ctx
, struct tls_connection
*conn
,
3232 const char *label
, int server_random_first
,
3233 int skip_keyblock
, u8
*out
, size_t out_len
)
3237 if (server_random_first
|| skip_keyblock
)
3238 return openssl_tls_prf(conn
, label
,
3239 server_random_first
, skip_keyblock
,
3241 if (SSL_export_keying_material(conn
->ssl
, out
, out_len
, label
,
3242 os_strlen(label
), NULL
, 0, 0) == 1) {
3243 wpa_printf(MSG_DEBUG
, "OpenSSL: Using internal PRF");
3246 return openssl_tls_prf(conn
, label
, server_random_first
,
3247 skip_keyblock
, out
, out_len
);
3251 static struct wpabuf
*
3252 openssl_handshake(struct tls_connection
*conn
, const struct wpabuf
*in_data
,
3256 struct wpabuf
*out_data
;
3259 * Give TLS handshake data from the server (if available) to OpenSSL
3262 if (in_data
&& wpabuf_len(in_data
) > 0 &&
3263 BIO_write(conn
->ssl_in
, wpabuf_head(in_data
), wpabuf_len(in_data
))
3265 tls_show_errors(MSG_INFO
, __func__
,
3266 "Handshake failed - BIO_write");
3270 /* Initiate TLS handshake or continue the existing handshake */
3272 res
= SSL_accept(conn
->ssl
);
3274 res
= SSL_connect(conn
->ssl
);
3276 int err
= SSL_get_error(conn
->ssl
, res
);
3277 if (err
== SSL_ERROR_WANT_READ
)
3278 wpa_printf(MSG_DEBUG
, "SSL: SSL_connect - want "
3280 else if (err
== SSL_ERROR_WANT_WRITE
)
3281 wpa_printf(MSG_DEBUG
, "SSL: SSL_connect - want to "
3284 tls_show_errors(MSG_INFO
, __func__
, "SSL_connect");
3289 /* Get the TLS handshake data to be sent to the server */
3290 res
= BIO_ctrl_pending(conn
->ssl_out
);
3291 wpa_printf(MSG_DEBUG
, "SSL: %d bytes pending from ssl_out", res
);
3292 out_data
= wpabuf_alloc(res
);
3293 if (out_data
== NULL
) {
3294 wpa_printf(MSG_DEBUG
, "SSL: Failed to allocate memory for "
3295 "handshake output (%d bytes)", res
);
3296 if (BIO_reset(conn
->ssl_out
) < 0) {
3297 tls_show_errors(MSG_INFO
, __func__
,
3298 "BIO_reset failed");
3302 res
= res
== 0 ? 0 : BIO_read(conn
->ssl_out
, wpabuf_mhead(out_data
),
3305 tls_show_errors(MSG_INFO
, __func__
,
3306 "Handshake failed - BIO_read");
3307 if (BIO_reset(conn
->ssl_out
) < 0) {
3308 tls_show_errors(MSG_INFO
, __func__
,
3309 "BIO_reset failed");
3311 wpabuf_free(out_data
);
3314 wpabuf_put(out_data
, res
);
3320 static struct wpabuf
*
3321 openssl_get_appl_data(struct tls_connection
*conn
, size_t max_len
)
3323 struct wpabuf
*appl_data
;
3326 appl_data
= wpabuf_alloc(max_len
+ 100);
3327 if (appl_data
== NULL
)
3330 res
= SSL_read(conn
->ssl
, wpabuf_mhead(appl_data
),
3331 wpabuf_size(appl_data
));
3333 int err
= SSL_get_error(conn
->ssl
, res
);
3334 if (err
== SSL_ERROR_WANT_READ
||
3335 err
== SSL_ERROR_WANT_WRITE
) {
3336 wpa_printf(MSG_DEBUG
, "SSL: No Application Data "
3339 tls_show_errors(MSG_INFO
, __func__
,
3340 "Failed to read possible "
3341 "Application Data");
3343 wpabuf_free(appl_data
);
3347 wpabuf_put(appl_data
, res
);
3348 wpa_hexdump_buf_key(MSG_MSGDUMP
, "SSL: Application Data in Finished "
3349 "message", appl_data
);
3355 static struct wpabuf
*
3356 openssl_connection_handshake(struct tls_connection
*conn
,
3357 const struct wpabuf
*in_data
,
3358 struct wpabuf
**appl_data
, int server
)
3360 struct wpabuf
*out_data
;
3365 out_data
= openssl_handshake(conn
, in_data
, server
);
3366 if (out_data
== NULL
)
3368 if (conn
->invalid_hb_used
) {
3369 wpa_printf(MSG_INFO
, "TLS: Heartbeat attack detected - do not send response");
3370 wpabuf_free(out_data
);
3374 if (SSL_is_init_finished(conn
->ssl
)) {
3375 wpa_printf(MSG_DEBUG
,
3376 "OpenSSL: Handshake finished - resumed=%d",
3377 tls_connection_resumed(conn
->ssl_ctx
, conn
));
3378 if (appl_data
&& in_data
)
3379 *appl_data
= openssl_get_appl_data(conn
,
3380 wpabuf_len(in_data
));
3383 if (conn
->invalid_hb_used
) {
3384 wpa_printf(MSG_INFO
, "TLS: Heartbeat attack detected - do not send response");
3386 wpabuf_free(*appl_data
);
3389 wpabuf_free(out_data
);
3398 tls_connection_handshake(void *ssl_ctx
, struct tls_connection
*conn
,
3399 const struct wpabuf
*in_data
,
3400 struct wpabuf
**appl_data
)
3402 return openssl_connection_handshake(conn
, in_data
, appl_data
, 0);
3406 struct wpabuf
* tls_connection_server_handshake(void *tls_ctx
,
3407 struct tls_connection
*conn
,
3408 const struct wpabuf
*in_data
,
3409 struct wpabuf
**appl_data
)
3411 return openssl_connection_handshake(conn
, in_data
, appl_data
, 1);
3415 struct wpabuf
* tls_connection_encrypt(void *tls_ctx
,
3416 struct tls_connection
*conn
,
3417 const struct wpabuf
*in_data
)
3425 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3426 if ((res
= BIO_reset(conn
->ssl_in
)) < 0 ||
3427 (res
= BIO_reset(conn
->ssl_out
)) < 0) {
3428 tls_show_errors(MSG_INFO
, __func__
, "BIO_reset failed");
3431 res
= SSL_write(conn
->ssl
, wpabuf_head(in_data
), wpabuf_len(in_data
));
3433 tls_show_errors(MSG_INFO
, __func__
,
3434 "Encryption failed - SSL_write");
3438 /* Read encrypted data to be sent to the server */
3439 buf
= wpabuf_alloc(wpabuf_len(in_data
) + 300);
3442 res
= BIO_read(conn
->ssl_out
, wpabuf_mhead(buf
), wpabuf_size(buf
));
3444 tls_show_errors(MSG_INFO
, __func__
,
3445 "Encryption failed - BIO_read");
3449 wpabuf_put(buf
, res
);
3455 struct wpabuf
* tls_connection_decrypt(void *tls_ctx
,
3456 struct tls_connection
*conn
,
3457 const struct wpabuf
*in_data
)
3462 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3463 res
= BIO_write(conn
->ssl_in
, wpabuf_head(in_data
),
3464 wpabuf_len(in_data
));
3466 tls_show_errors(MSG_INFO
, __func__
,
3467 "Decryption failed - BIO_write");
3470 if (BIO_reset(conn
->ssl_out
) < 0) {
3471 tls_show_errors(MSG_INFO
, __func__
, "BIO_reset failed");
3475 /* Read decrypted data for further processing */
3477 * Even though we try to disable TLS compression, it is possible that
3478 * this cannot be done with all TLS libraries. Add extra buffer space
3479 * to handle the possibility of the decrypted data being longer than
3482 buf
= wpabuf_alloc((wpabuf_len(in_data
) + 500) * 3);
3485 res
= SSL_read(conn
->ssl
, wpabuf_mhead(buf
), wpabuf_size(buf
));
3487 tls_show_errors(MSG_INFO
, __func__
,
3488 "Decryption failed - SSL_read");
3492 wpabuf_put(buf
, res
);
3494 if (conn
->invalid_hb_used
) {
3495 wpa_printf(MSG_INFO
, "TLS: Heartbeat attack detected - do not send response");
3504 int tls_connection_resumed(void *ssl_ctx
, struct tls_connection
*conn
)
3506 return conn
? SSL_cache_hit(conn
->ssl
) : 0;
3510 int tls_connection_set_cipher_list(void *tls_ctx
, struct tls_connection
*conn
,
3513 char buf
[500], *pos
, *end
;
3517 if (conn
== NULL
|| conn
->ssl
== NULL
|| ciphers
== NULL
)
3522 end
= pos
+ sizeof(buf
);
3525 while (*c
!= TLS_CIPHER_NONE
) {
3529 case TLS_CIPHER_RC4_SHA
:
3532 case TLS_CIPHER_AES128_SHA
:
3533 suite
= "AES128-SHA";
3535 case TLS_CIPHER_RSA_DHE_AES128_SHA
:
3536 suite
= "DHE-RSA-AES128-SHA";
3538 case TLS_CIPHER_ANON_DH_AES128_SHA
:
3539 suite
= "ADH-AES128-SHA";
3541 case TLS_CIPHER_RSA_DHE_AES256_SHA
:
3542 suite
= "DHE-RSA-AES256-SHA";
3544 case TLS_CIPHER_AES256_SHA
:
3545 suite
= "AES256-SHA";
3548 wpa_printf(MSG_DEBUG
, "TLS: Unsupported "
3549 "cipher selection: %d", *c
);
3552 ret
= os_snprintf(pos
, end
- pos
, ":%s", suite
);
3553 if (os_snprintf_error(end
- pos
, ret
))
3560 wpa_printf(MSG_DEBUG
, "OpenSSL: cipher suites: %s", buf
+ 1);
3562 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
3563 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3564 if (os_strstr(buf
, ":ADH-")) {
3566 * Need to drop to security level 0 to allow anonymous
3567 * cipher suites for EAP-FAST.
3569 SSL_set_security_level(conn
->ssl
, 0);
3570 } else if (SSL_get_security_level(conn
->ssl
) == 0) {
3571 /* Force at least security level 1 */
3572 SSL_set_security_level(conn
->ssl
, 1);
3574 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3577 if (SSL_set_cipher_list(conn
->ssl
, buf
+ 1) != 1) {
3578 tls_show_errors(MSG_INFO
, __func__
,
3579 "Cipher suite configuration failed");
3587 int tls_get_version(void *ssl_ctx
, struct tls_connection
*conn
,
3588 char *buf
, size_t buflen
)
3591 if (conn
== NULL
|| conn
->ssl
== NULL
)
3594 name
= SSL_get_version(conn
->ssl
);
3598 os_strlcpy(buf
, name
, buflen
);
3603 int tls_get_cipher(void *ssl_ctx
, struct tls_connection
*conn
,
3604 char *buf
, size_t buflen
)
3607 if (conn
== NULL
|| conn
->ssl
== NULL
)
3610 name
= SSL_get_cipher(conn
->ssl
);
3614 os_strlcpy(buf
, name
, buflen
);
3619 int tls_connection_enable_workaround(void *ssl_ctx
,
3620 struct tls_connection
*conn
)
3622 SSL_set_options(conn
->ssl
, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
);
3628 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3629 /* ClientHello TLS extensions require a patch to openssl, so this function is
3630 * commented out unless explicitly needed for EAP-FAST in order to be able to
3631 * build this file with unmodified openssl. */
3632 int tls_connection_client_hello_ext(void *ssl_ctx
, struct tls_connection
*conn
,
3633 int ext_type
, const u8
*data
,
3636 if (conn
== NULL
|| conn
->ssl
== NULL
|| ext_type
!= 35)
3639 if (SSL_set_session_ticket_ext(conn
->ssl
, (void *) data
,
3645 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3648 int tls_connection_get_failed(void *ssl_ctx
, struct tls_connection
*conn
)
3652 return conn
->failed
;
3656 int tls_connection_get_read_alerts(void *ssl_ctx
, struct tls_connection
*conn
)
3660 return conn
->read_alerts
;
3664 int tls_connection_get_write_alerts(void *ssl_ctx
, struct tls_connection
*conn
)
3668 return conn
->write_alerts
;
3674 static void ocsp_debug_print_resp(OCSP_RESPONSE
*rsp
)
3676 #ifndef CONFIG_NO_STDOUT_DEBUG
3682 if (wpa_debug_level
> MSG_DEBUG
)
3685 out
= BIO_new(BIO_s_mem());
3689 OCSP_RESPONSE_print(out
, rsp
, 0);
3690 rlen
= BIO_ctrl_pending(out
);
3691 txt
= os_malloc(rlen
+ 1);
3697 res
= BIO_read(out
, txt
, rlen
);
3700 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP Response\n%s", txt
);
3704 #endif /* CONFIG_NO_STDOUT_DEBUG */
3708 static void debug_print_cert(X509
*cert
, const char *title
)
3710 #ifndef CONFIG_NO_STDOUT_DEBUG
3716 if (wpa_debug_level
> MSG_DEBUG
)
3719 out
= BIO_new(BIO_s_mem());
3723 X509_print(out
, cert
);
3724 rlen
= BIO_ctrl_pending(out
);
3725 txt
= os_malloc(rlen
+ 1);
3731 res
= BIO_read(out
, txt
, rlen
);
3734 wpa_printf(MSG_DEBUG
, "OpenSSL: %s\n%s", title
, txt
);
3739 #endif /* CONFIG_NO_STDOUT_DEBUG */
3743 static int ocsp_resp_cb(SSL
*s
, void *arg
)
3745 struct tls_connection
*conn
= arg
;
3746 const unsigned char *p
;
3747 int len
, status
, reason
;
3749 OCSP_BASICRESP
*basic
;
3751 ASN1_GENERALIZEDTIME
*produced_at
, *this_update
, *next_update
;
3753 STACK_OF(X509
) *certs
= NULL
;
3755 len
= SSL_get_tlsext_status_ocsp_resp(s
, &p
);
3757 wpa_printf(MSG_DEBUG
, "OpenSSL: No OCSP response received");
3758 return (conn
->flags
& TLS_CONN_REQUIRE_OCSP
) ? 0 : 1;
3761 wpa_hexdump(MSG_DEBUG
, "OpenSSL: OCSP response", p
, len
);
3763 rsp
= d2i_OCSP_RESPONSE(NULL
, &p
, len
);
3765 wpa_printf(MSG_INFO
, "OpenSSL: Failed to parse OCSP response");
3769 ocsp_debug_print_resp(rsp
);
3771 status
= OCSP_response_status(rsp
);
3772 if (status
!= OCSP_RESPONSE_STATUS_SUCCESSFUL
) {
3773 wpa_printf(MSG_INFO
, "OpenSSL: OCSP responder error %d (%s)",
3774 status
, OCSP_response_status_str(status
));
3778 basic
= OCSP_response_get1_basic(rsp
);
3780 wpa_printf(MSG_INFO
, "OpenSSL: Could not find BasicOCSPResponse");
3784 store
= SSL_CTX_get_cert_store(conn
->ssl_ctx
);
3785 if (conn
->peer_issuer
) {
3786 debug_print_cert(conn
->peer_issuer
, "Add OCSP issuer");
3788 if (X509_STORE_add_cert(store
, conn
->peer_issuer
) != 1) {
3789 tls_show_errors(MSG_INFO
, __func__
,
3790 "OpenSSL: Could not add issuer to certificate store");
3792 certs
= sk_X509_new_null();
3795 cert
= X509_dup(conn
->peer_issuer
);
3796 if (cert
&& !sk_X509_push(certs
, cert
)) {
3799 "OpenSSL: Could not add issuer to OCSP responder trust store");
3801 sk_X509_free(certs
);
3804 if (certs
&& conn
->peer_issuer_issuer
) {
3805 cert
= X509_dup(conn
->peer_issuer_issuer
);
3806 if (cert
&& !sk_X509_push(certs
, cert
)) {
3809 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3816 status
= OCSP_basic_verify(basic
, certs
, store
, OCSP_TRUSTOTHER
);
3817 sk_X509_pop_free(certs
, X509_free
);
3819 tls_show_errors(MSG_INFO
, __func__
,
3820 "OpenSSL: OCSP response failed verification");
3821 OCSP_BASICRESP_free(basic
);
3822 OCSP_RESPONSE_free(rsp
);
3826 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP response verification succeeded");
3828 if (!conn
->peer_cert
) {
3829 wpa_printf(MSG_DEBUG
, "OpenSSL: Peer certificate not available for OCSP status check");
3830 OCSP_BASICRESP_free(basic
);
3831 OCSP_RESPONSE_free(rsp
);
3835 if (!conn
->peer_issuer
) {
3836 wpa_printf(MSG_DEBUG
, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3837 OCSP_BASICRESP_free(basic
);
3838 OCSP_RESPONSE_free(rsp
);
3842 id
= OCSP_cert_to_id(NULL
, conn
->peer_cert
, conn
->peer_issuer
);
3844 wpa_printf(MSG_DEBUG
, "OpenSSL: Could not create OCSP certificate identifier");
3845 OCSP_BASICRESP_free(basic
);
3846 OCSP_RESPONSE_free(rsp
);
3850 if (!OCSP_resp_find_status(basic
, id
, &status
, &reason
, &produced_at
,
3851 &this_update
, &next_update
)) {
3852 wpa_printf(MSG_INFO
, "OpenSSL: Could not find current server certificate from OCSP response%s",
3853 (conn
->flags
& TLS_CONN_REQUIRE_OCSP
) ? "" :
3854 " (OCSP not required)");
3855 OCSP_CERTID_free(id
);
3856 OCSP_BASICRESP_free(basic
);
3857 OCSP_RESPONSE_free(rsp
);
3858 return (conn
->flags
& TLS_CONN_REQUIRE_OCSP
) ? 0 : 1;
3860 OCSP_CERTID_free(id
);
3862 if (!OCSP_check_validity(this_update
, next_update
, 5 * 60, -1)) {
3863 tls_show_errors(MSG_INFO
, __func__
,
3864 "OpenSSL: OCSP status times invalid");
3865 OCSP_BASICRESP_free(basic
);
3866 OCSP_RESPONSE_free(rsp
);
3870 OCSP_BASICRESP_free(basic
);
3871 OCSP_RESPONSE_free(rsp
);
3873 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP status for server certificate: %s",
3874 OCSP_cert_status_str(status
));
3876 if (status
== V_OCSP_CERTSTATUS_GOOD
)
3878 if (status
== V_OCSP_CERTSTATUS_REVOKED
)
3880 if (conn
->flags
& TLS_CONN_REQUIRE_OCSP
) {
3881 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP status unknown, but OCSP required");
3884 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3889 static int ocsp_status_cb(SSL
*s
, void *arg
)
3895 if (tls_global
->ocsp_stapling_response
== NULL
) {
3896 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP status callback - no response configured");
3897 return SSL_TLSEXT_ERR_OK
;
3900 resp
= os_readfile(tls_global
->ocsp_stapling_response
, &len
);
3902 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP status callback - could not read response file");
3903 /* TODO: Build OCSPResponse with responseStatus = internalError
3905 return SSL_TLSEXT_ERR_OK
;
3907 wpa_printf(MSG_DEBUG
, "OpenSSL: OCSP status callback - send cached response");
3908 tmp
= OPENSSL_malloc(len
);
3911 return SSL_TLSEXT_ERR_ALERT_FATAL
;
3914 os_memcpy(tmp
, resp
, len
);
3916 SSL_set_tlsext_status_ocsp_resp(s
, tmp
, len
);
3918 return SSL_TLSEXT_ERR_OK
;
3921 #endif /* HAVE_OCSP */
3924 int tls_connection_set_params(void *tls_ctx
, struct tls_connection
*conn
,
3925 const struct tls_connection_params
*params
)
3927 struct tls_data
*data
= tls_ctx
;
3931 const char *key_id
= params
->key_id
;
3932 const char *cert_id
= params
->cert_id
;
3933 const char *ca_cert_id
= params
->ca_cert_id
;
3934 const char *engine_id
= params
->engine
? params
->engine_id
: NULL
;
3939 if (params
->flags
& TLS_CONN_REQUIRE_OCSP_ALL
) {
3940 wpa_printf(MSG_INFO
,
3941 "OpenSSL: ocsp=3 not supported");
3946 * If the engine isn't explicitly configured, and any of the
3947 * cert/key fields are actually PKCS#11 URIs, then automatically
3948 * use the PKCS#11 ENGINE.
3950 if (!engine_id
|| os_strcmp(engine_id
, "pkcs11") == 0)
3953 if (!key_id
&& params
->private_key
&& can_pkcs11
&&
3954 os_strncmp(params
->private_key
, "pkcs11:", 7) == 0) {
3956 key_id
= params
->private_key
;
3959 if (!cert_id
&& params
->client_cert
&& can_pkcs11
&&
3960 os_strncmp(params
->client_cert
, "pkcs11:", 7) == 0) {
3962 cert_id
= params
->client_cert
;
3965 if (!ca_cert_id
&& params
->ca_cert
&& can_pkcs11
&&
3966 os_strncmp(params
->ca_cert
, "pkcs11:", 7) == 0) {
3968 ca_cert_id
= params
->ca_cert
;
3971 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3972 if (can_pkcs11
== 2 && !engine_id
)
3973 engine_id
= "pkcs11";
3975 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3976 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3977 if (params
->flags
& TLS_CONN_EAP_FAST
) {
3978 wpa_printf(MSG_DEBUG
,
3979 "OpenSSL: Use TLSv1_method() for EAP-FAST");
3980 if (SSL_set_ssl_method(conn
->ssl
, TLSv1_method()) != 1) {
3981 tls_show_errors(MSG_INFO
, __func__
,
3982 "Failed to set TLSv1_method() for EAP-FAST");
3987 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3989 while ((err
= ERR_get_error())) {
3990 wpa_printf(MSG_INFO
, "%s: Clearing pending SSL error: %s",
3991 __func__
, ERR_error_string(err
, NULL
));
3995 wpa_printf(MSG_DEBUG
, "SSL: Initializing TLS engine");
3996 ret
= tls_engine_init(conn
, engine_id
, params
->pin
,
3997 key_id
, cert_id
, ca_cert_id
);
4001 if (tls_connection_set_subject_match(conn
,
4002 params
->subject_match
,
4003 params
->altsubject_match
,
4004 params
->suffix_match
,
4005 params
->domain_match
))
4008 if (engine_id
&& ca_cert_id
) {
4009 if (tls_connection_engine_ca_cert(data
, conn
, ca_cert_id
))
4010 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED
;
4011 } else if (tls_connection_ca_cert(data
, conn
, params
->ca_cert
,
4012 params
->ca_cert_blob
,
4013 params
->ca_cert_blob_len
,
4017 if (engine_id
&& cert_id
) {
4018 if (tls_connection_engine_client_cert(conn
, cert_id
))
4019 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED
;
4020 } else if (tls_connection_client_cert(conn
, params
->client_cert
,
4021 params
->client_cert_blob
,
4022 params
->client_cert_blob_len
))
4025 if (engine_id
&& key_id
) {
4026 wpa_printf(MSG_DEBUG
, "TLS: Using private key from engine");
4027 if (tls_connection_engine_private_key(conn
))
4028 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED
;
4029 } else if (tls_connection_private_key(data
, conn
,
4030 params
->private_key
,
4031 params
->private_key_passwd
,
4032 params
->private_key_blob
,
4033 params
->private_key_blob_len
)) {
4034 wpa_printf(MSG_INFO
, "TLS: Failed to load private key '%s'",
4035 params
->private_key
);
4039 if (tls_connection_dh(conn
, params
->dh_file
)) {
4040 wpa_printf(MSG_INFO
, "TLS: Failed to load DH file '%s'",
4045 if (params
->openssl_ciphers
&&
4046 SSL_set_cipher_list(conn
->ssl
, params
->openssl_ciphers
) != 1) {
4047 wpa_printf(MSG_INFO
,
4048 "OpenSSL: Failed to set cipher string '%s'",
4049 params
->openssl_ciphers
);
4053 tls_set_conn_flags(conn
->ssl
, params
->flags
);
4055 #ifdef OPENSSL_IS_BORINGSSL
4056 if (params
->flags
& TLS_CONN_REQUEST_OCSP
) {
4057 SSL_enable_ocsp_stapling(conn
->ssl
);
4059 #else /* OPENSSL_IS_BORINGSSL */
4061 if (params
->flags
& TLS_CONN_REQUEST_OCSP
) {
4062 SSL_CTX
*ssl_ctx
= data
->ssl
;
4063 SSL_set_tlsext_status_type(conn
->ssl
, TLSEXT_STATUSTYPE_ocsp
);
4064 SSL_CTX_set_tlsext_status_cb(ssl_ctx
, ocsp_resp_cb
);
4065 SSL_CTX_set_tlsext_status_arg(ssl_ctx
, conn
);
4067 #else /* HAVE_OCSP */
4068 if (params
->flags
& TLS_CONN_REQUIRE_OCSP
) {
4069 wpa_printf(MSG_INFO
,
4070 "OpenSSL: No OCSP support included - reject configuration");
4073 if (params
->flags
& TLS_CONN_REQUEST_OCSP
) {
4074 wpa_printf(MSG_DEBUG
,
4075 "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
4077 #endif /* HAVE_OCSP */
4078 #endif /* OPENSSL_IS_BORINGSSL */
4080 conn
->flags
= params
->flags
;
4082 tls_get_errors(data
);
4088 int tls_global_set_params(void *tls_ctx
,
4089 const struct tls_connection_params
*params
)
4091 struct tls_data
*data
= tls_ctx
;
4092 SSL_CTX
*ssl_ctx
= data
->ssl
;
4095 while ((err
= ERR_get_error())) {
4096 wpa_printf(MSG_INFO
, "%s: Clearing pending SSL error: %s",
4097 __func__
, ERR_error_string(err
, NULL
));
4100 if (tls_global_ca_cert(data
, params
->ca_cert
) ||
4101 tls_global_client_cert(data
, params
->client_cert
) ||
4102 tls_global_private_key(data
, params
->private_key
,
4103 params
->private_key_passwd
) ||
4104 tls_global_dh(data
, params
->dh_file
)) {
4105 wpa_printf(MSG_INFO
, "TLS: Failed to set global parameters");
4109 if (params
->openssl_ciphers
&&
4110 SSL_CTX_set_cipher_list(ssl_ctx
, params
->openssl_ciphers
) != 1) {
4111 wpa_printf(MSG_INFO
,
4112 "OpenSSL: Failed to set cipher string '%s'",
4113 params
->openssl_ciphers
);
4117 #ifdef SSL_OP_NO_TICKET
4118 if (params
->flags
& TLS_CONN_DISABLE_SESSION_TICKET
)
4119 SSL_CTX_set_options(ssl_ctx
, SSL_OP_NO_TICKET
);
4120 #ifdef SSL_CTX_clear_options
4122 SSL_CTX_clear_options(ssl_ctx
, SSL_OP_NO_TICKET
);
4123 #endif /* SSL_clear_options */
4124 #endif /* SSL_OP_NO_TICKET */
4127 SSL_CTX_set_tlsext_status_cb(ssl_ctx
, ocsp_status_cb
);
4128 SSL_CTX_set_tlsext_status_arg(ssl_ctx
, ssl_ctx
);
4129 os_free(tls_global
->ocsp_stapling_response
);
4130 if (params
->ocsp_stapling_response
)
4131 tls_global
->ocsp_stapling_response
=
4132 os_strdup(params
->ocsp_stapling_response
);
4134 tls_global
->ocsp_stapling_response
= NULL
;
4135 #endif /* HAVE_OCSP */
4141 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4142 /* Pre-shared secred requires a patch to openssl, so this function is
4143 * commented out unless explicitly needed for EAP-FAST in order to be able to
4144 * build this file with unmodified openssl. */
4146 #if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
4147 static int tls_sess_sec_cb(SSL
*s
, void *secret
, int *secret_len
,
4148 STACK_OF(SSL_CIPHER
) *peer_ciphers
,
4149 const SSL_CIPHER
**cipher
, void *arg
)
4150 #else /* OPENSSL_IS_BORINGSSL */
4151 static int tls_sess_sec_cb(SSL
*s
, void *secret
, int *secret_len
,
4152 STACK_OF(SSL_CIPHER
) *peer_ciphers
,
4153 SSL_CIPHER
**cipher
, void *arg
)
4154 #endif /* OPENSSL_IS_BORINGSSL */
4156 struct tls_connection
*conn
= arg
;
4159 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
4160 if (conn
== NULL
|| conn
->session_ticket_cb
== NULL
)
4163 ret
= conn
->session_ticket_cb(conn
->session_ticket_cb_ctx
,
4164 conn
->session_ticket
,
4165 conn
->session_ticket_len
,
4166 s
->s3
->client_random
,
4167 s
->s3
->server_random
, secret
);
4169 unsigned char client_random
[SSL3_RANDOM_SIZE
];
4170 unsigned char server_random
[SSL3_RANDOM_SIZE
];
4172 if (conn
== NULL
|| conn
->session_ticket_cb
== NULL
)
4175 SSL_get_client_random(s
, client_random
, sizeof(client_random
));
4176 SSL_get_server_random(s
, server_random
, sizeof(server_random
));
4178 ret
= conn
->session_ticket_cb(conn
->session_ticket_cb_ctx
,
4179 conn
->session_ticket
,
4180 conn
->session_ticket_len
,
4182 server_random
, secret
);
4185 os_free(conn
->session_ticket
);
4186 conn
->session_ticket
= NULL
;
4191 *secret_len
= SSL_MAX_MASTER_KEY_LENGTH
;
4196 static int tls_session_ticket_ext_cb(SSL
*s
, const unsigned char *data
,
4199 struct tls_connection
*conn
= arg
;
4201 if (conn
== NULL
|| conn
->session_ticket_cb
== NULL
)
4204 wpa_printf(MSG_DEBUG
, "OpenSSL: %s: length=%d", __func__
, len
);
4206 os_free(conn
->session_ticket
);
4207 conn
->session_ticket
= NULL
;
4209 wpa_hexdump(MSG_DEBUG
, "OpenSSL: ClientHello SessionTicket "
4210 "extension", data
, len
);
4212 conn
->session_ticket
= os_malloc(len
);
4213 if (conn
->session_ticket
== NULL
)
4216 os_memcpy(conn
->session_ticket
, data
, len
);
4217 conn
->session_ticket_len
= len
;
4221 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4224 int tls_connection_set_session_ticket_cb(void *tls_ctx
,
4225 struct tls_connection
*conn
,
4226 tls_session_ticket_cb cb
,
4229 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4230 conn
->session_ticket_cb
= cb
;
4231 conn
->session_ticket_cb_ctx
= ctx
;
4234 if (SSL_set_session_secret_cb(conn
->ssl
, tls_sess_sec_cb
,
4237 SSL_set_session_ticket_ext_cb(conn
->ssl
,
4238 tls_session_ticket_ext_cb
, conn
);
4240 if (SSL_set_session_secret_cb(conn
->ssl
, NULL
, NULL
) != 1)
4242 SSL_set_session_ticket_ext_cb(conn
->ssl
, NULL
, NULL
);
4246 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4248 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4252 int tls_get_library_version(char *buf
, size_t buf_len
)
4254 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
4255 return os_snprintf(buf
, buf_len
, "OpenSSL build=%s run=%s",
4256 OPENSSL_VERSION_TEXT
,
4257 OpenSSL_version(OPENSSL_VERSION
));
4259 return os_snprintf(buf
, buf_len
, "OpenSSL build=%s run=%s",
4260 OPENSSL_VERSION_TEXT
,
4261 SSLeay_version(SSLEAY_VERSION
));
4266 void tls_connection_set_success_data(struct tls_connection
*conn
,
4267 struct wpabuf
*data
)
4272 if (tls_ex_idx_session
< 0)
4274 sess
= SSL_get_session(conn
->ssl
);
4277 old
= SSL_SESSION_get_ex_data(sess
, tls_ex_idx_session
);
4279 wpa_printf(MSG_DEBUG
, "OpenSSL: Replacing old success data %p",
4283 if (SSL_SESSION_set_ex_data(sess
, tls_ex_idx_session
, data
) != 1)
4286 wpa_printf(MSG_DEBUG
, "OpenSSL: Stored success data %p", data
);
4287 conn
->success_data
= 1;
4291 wpa_printf(MSG_INFO
, "OpenSSL: Failed to store success data");
4296 void tls_connection_set_success_data_resumed(struct tls_connection
*conn
)
4298 wpa_printf(MSG_DEBUG
,
4299 "OpenSSL: Success data accepted for resumed session");
4300 conn
->success_data
= 1;
4304 const struct wpabuf
*
4305 tls_connection_get_success_data(struct tls_connection
*conn
)
4309 if (tls_ex_idx_session
< 0 ||
4310 !(sess
= SSL_get_session(conn
->ssl
)))
4312 return SSL_SESSION_get_ex_data(sess
, tls_ex_idx_session
);
4316 void tls_connection_remove_session(struct tls_connection
*conn
)
4320 sess
= SSL_get_session(conn
->ssl
);
4324 if (SSL_CTX_remove_session(conn
->ssl_ctx
, sess
) != 1)
4325 wpa_printf(MSG_DEBUG
,
4326 "OpenSSL: Session was not cached");
4328 wpa_printf(MSG_DEBUG
,
4329 "OpenSSL: Removed cached session to disable session resumption");