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>
39 #if OPENSSL_VERSION_NUMBER < 0x10000000L
40 /* ERR_remove_thread_state replaces ERR_remove_state and the latter is
41 * deprecated. However, OpenSSL 0.9.8 doesn't include
42 * ERR_remove_thread_state. */
43 #define ERR_remove_thread_state(tid) ERR_remove_state(0)
46 #if defined(OPENSSL_IS_BORINGSSL)
47 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
48 typedef size_t stack_index_t;
50 typedef int stack_index_t;
53 #ifdef SSL_set_tlsext_status_type
54 #ifndef OPENSSL_NO_TLSEXT
56 #include <openssl/ocsp.h>
57 #endif /* OPENSSL_NO_TLSEXT */
58 #endif /* SSL_set_tlsext_status_type */
61 #include <openssl/pem.h>
62 #include <keystore/keystore_get.h>
64 static BIO * BIO_from_keystore(const char *key)
67 uint8_t *value = NULL;
68 int length = keystore_get(key, strlen(key), &value);
69 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
70 BIO_write(bio, value, length);
76 static int tls_openssl_ref_count = 0;
79 void (*event_cb)(void *ctx, enum tls_event ev,
80 union tls_event_data *data);
83 char *ocsp_stapling_response;
86 static struct tls_context *tls_global = NULL;
93 struct tls_connection {
94 struct tls_context *context;
97 BIO *ssl_in, *ssl_out;
98 #ifndef OPENSSL_NO_ENGINE
99 ENGINE *engine; /* functional reference to the engine */
100 EVP_PKEY *private_key; /* the private key if using engine */
101 #endif /* OPENSSL_NO_ENGINE */
102 char *subject_match, *altsubject_match, *suffix_match, *domain_match;
103 int read_alerts, write_alerts, failed;
105 tls_session_ticket_cb session_ticket_cb;
106 void *session_ticket_cb_ctx;
108 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
110 size_t session_ticket_len;
112 unsigned int ca_cert_verify:1;
113 unsigned int cert_probe:1;
114 unsigned int server_cert_only:1;
115 unsigned int invalid_hb_used:1;
117 u8 srv_cert_hash[32];
123 X509 *peer_issuer_issuer;
125 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
126 unsigned char client_random[SSL3_RANDOM_SIZE];
127 unsigned char server_random[SSL3_RANDOM_SIZE];
132 static struct tls_context * tls_context_new(const struct tls_config *conf)
134 struct tls_context *context = os_zalloc(sizeof(*context));
138 context->event_cb = conf->event_cb;
139 context->cb_ctx = conf->cb_ctx;
140 context->cert_in_cb = conf->cert_in_cb;
146 #ifdef CONFIG_NO_STDOUT_DEBUG
148 static void _tls_show_errors(void)
152 while ((err = ERR_get_error())) {
153 /* Just ignore the errors, since stdout is disabled */
156 #define tls_show_errors(l, f, t) _tls_show_errors()
158 #else /* CONFIG_NO_STDOUT_DEBUG */
160 static void tls_show_errors(int level, const char *func, const char *txt)
164 wpa_printf(level, "OpenSSL: %s - %s %s",
165 func, txt, ERR_error_string(ERR_get_error(), NULL));
167 while ((err = ERR_get_error())) {
168 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
169 ERR_error_string(err, NULL));
173 #endif /* CONFIG_NO_STDOUT_DEBUG */
176 #ifdef CONFIG_NATIVE_WINDOWS
178 /* Windows CryptoAPI and access to certificate stores */
179 #include <wincrypt.h>
181 #ifdef __MINGW32_VERSION
183 * MinGW does not yet include all the needed definitions for CryptoAPI, so
184 * define here whatever extra is needed.
186 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
187 #define CERT_STORE_READONLY_FLAG 0x00008000
188 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
190 #endif /* __MINGW32_VERSION */
193 struct cryptoapi_rsa_data {
194 const CERT_CONTEXT *cert;
195 HCRYPTPROV crypt_prov;
197 BOOL free_crypt_prov;
201 static void cryptoapi_error(const char *msg)
203 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
204 msg, (unsigned int) GetLastError());
208 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
209 unsigned char *to, RSA *rsa, int padding)
211 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
216 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
217 unsigned char *to, RSA *rsa, int padding)
219 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
224 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
225 unsigned char *to, RSA *rsa, int padding)
227 struct cryptoapi_rsa_data *priv =
228 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
230 DWORD hash_size, len, i;
231 unsigned char *buf = NULL;
235 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
236 ERR_R_PASSED_NULL_PARAMETER);
240 if (padding != RSA_PKCS1_PADDING) {
241 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
242 RSA_R_UNKNOWN_PADDING_TYPE);
246 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
247 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
249 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
250 RSA_R_INVALID_MESSAGE_LENGTH);
254 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
256 cryptoapi_error("CryptCreateHash failed");
260 len = sizeof(hash_size);
261 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
263 cryptoapi_error("CryptGetHashParam failed");
267 if ((int) hash_size != flen) {
268 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
269 (unsigned) hash_size, flen);
270 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
271 RSA_R_INVALID_MESSAGE_LENGTH);
274 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
275 cryptoapi_error("CryptSetHashParam failed");
280 buf = os_malloc(len);
282 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
286 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
287 cryptoapi_error("CryptSignHash failed");
291 for (i = 0; i < len; i++)
292 to[i] = buf[len - i - 1];
297 CryptDestroyHash(hash);
303 static int cryptoapi_rsa_priv_dec(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 void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
315 if (priv->crypt_prov && priv->free_crypt_prov)
316 CryptReleaseContext(priv->crypt_prov, 0);
318 CertFreeCertificateContext(priv->cert);
323 static int cryptoapi_finish(RSA *rsa)
325 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
326 os_free((void *) rsa->meth);
332 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
335 const CERT_CONTEXT *ret = NULL;
337 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
338 store | CERT_STORE_OPEN_EXISTING_FLAG |
339 CERT_STORE_READONLY_FLAG, L"MY");
341 cryptoapi_error("Failed to open 'My system store'");
345 if (strncmp(name, "cert://", 7) == 0) {
346 unsigned short wbuf[255];
347 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
348 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
350 0, CERT_FIND_SUBJECT_STR,
352 } else if (strncmp(name, "hash://", 7) == 0) {
353 CRYPT_HASH_BLOB blob;
355 const char *hash = name + 7;
358 len = os_strlen(hash) / 2;
359 buf = os_malloc(len);
360 if (buf && hexstr2bin(hash, buf, len) == 0) {
363 ret = CertFindCertificateInStore(cs,
372 CertCloseStore(cs, 0);
378 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
381 RSA *rsa = NULL, *pub_rsa;
382 struct cryptoapi_rsa_data *priv;
383 RSA_METHOD *rsa_meth;
386 (strncmp(name, "cert://", 7) != 0 &&
387 strncmp(name, "hash://", 7) != 0))
390 priv = os_zalloc(sizeof(*priv));
391 rsa_meth = os_zalloc(sizeof(*rsa_meth));
392 if (priv == NULL || rsa_meth == NULL) {
393 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
394 "for CryptoAPI RSA method");
400 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
401 if (priv->cert == NULL) {
402 priv->cert = cryptoapi_find_cert(
403 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
405 if (priv->cert == NULL) {
406 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
411 cert = d2i_X509(NULL,
412 (const unsigned char **) &priv->cert->pbCertEncoded,
413 priv->cert->cbCertEncoded);
415 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
420 if (!CryptAcquireCertificatePrivateKey(priv->cert,
421 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
422 NULL, &priv->crypt_prov,
424 &priv->free_crypt_prov)) {
425 cryptoapi_error("Failed to acquire a private key for the "
430 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
431 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
432 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
433 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
434 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
435 rsa_meth->finish = cryptoapi_finish;
436 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
437 rsa_meth->app_data = (char *) priv;
441 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
442 ERR_R_MALLOC_FAILURE);
446 if (!SSL_use_certificate(ssl, cert)) {
451 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
455 rsa->n = BN_dup(pub_rsa->n);
456 rsa->e = BN_dup(pub_rsa->e);
457 if (!RSA_set_method(rsa, rsa_meth))
460 if (!SSL_use_RSAPrivateKey(ssl, rsa))
473 cryptoapi_free_data(priv);
479 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
482 PCCERT_CONTEXT ctx = NULL;
490 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
495 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
498 wsprintf(wstore, L"%S", store);
499 cs = CertOpenSystemStore(0, wstore);
502 cs = CertOpenSystemStore(0, store);
505 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
506 "'%s': error=%d", __func__, store,
507 (int) GetLastError());
511 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
512 cert = d2i_X509(NULL,
513 (const unsigned char **) &ctx->pbCertEncoded,
516 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
517 "X509 DER encoding for CA cert");
521 X509_NAME_oneline(X509_get_subject_name(cert), buf,
523 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
524 "system certificate store: subject='%s'", buf);
526 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
527 tls_show_errors(MSG_WARNING, __func__,
528 "Failed to add ca_cert to OpenSSL "
529 "certificate store");
535 if (!CertCloseStore(cs, 0)) {
536 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
537 "'%s': error=%d", __func__, name + 13,
538 (int) GetLastError());
545 #else /* CONFIG_NATIVE_WINDOWS */
547 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
552 #endif /* CONFIG_NATIVE_WINDOWS */
555 static void ssl_info_cb(const SSL *ssl, int where, int ret)
560 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
561 w = where & ~SSL_ST_MASK;
562 if (w & SSL_ST_CONNECT)
564 else if (w & SSL_ST_ACCEPT)
569 if (where & SSL_CB_LOOP) {
570 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
571 str, SSL_state_string_long(ssl));
572 } else if (where & SSL_CB_ALERT) {
573 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
574 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
575 where & SSL_CB_READ ?
576 "read (remote end reported an error)" :
577 "write (local SSL3 detected an error)",
578 SSL_alert_type_string_long(ret),
579 SSL_alert_desc_string_long(ret));
580 if ((ret >> 8) == SSL3_AL_FATAL) {
581 if (where & SSL_CB_READ)
584 conn->write_alerts++;
586 if (conn->context->event_cb != NULL) {
587 union tls_event_data ev;
588 struct tls_context *context = conn->context;
589 os_memset(&ev, 0, sizeof(ev));
590 ev.alert.is_local = !(where & SSL_CB_READ);
591 ev.alert.type = SSL_alert_type_string_long(ret);
592 ev.alert.description = SSL_alert_desc_string_long(ret);
593 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
595 } else if (where & SSL_CB_EXIT && ret <= 0) {
596 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
597 str, ret == 0 ? "failed" : "error",
598 SSL_state_string_long(ssl));
603 #ifndef OPENSSL_NO_ENGINE
605 * tls_engine_load_dynamic_generic - load any openssl engine
606 * @pre: an array of commands and values that load an engine initialized
607 * in the engine specific function
608 * @post: an array of commands and values that initialize an already loaded
609 * engine (or %NULL if not required)
610 * @id: the engine id of the engine to load (only required if post is not %NULL
612 * This function is a generic function that loads any openssl engine.
614 * Returns: 0 on success, -1 on failure
616 static int tls_engine_load_dynamic_generic(const char *pre[],
617 const char *post[], const char *id)
620 const char *dynamic_id = "dynamic";
622 engine = ENGINE_by_id(id);
625 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
631 engine = ENGINE_by_id(dynamic_id);
632 if (engine == NULL) {
633 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
635 ERR_error_string(ERR_get_error(), NULL));
639 /* Perform the pre commands. This will load the engine. */
640 while (pre && pre[0]) {
641 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
642 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
643 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
644 "%s %s [%s]", pre[0], pre[1],
645 ERR_error_string(ERR_get_error(), NULL));
653 * Free the reference to the "dynamic" engine. The loaded engine can
654 * now be looked up using ENGINE_by_id().
658 engine = ENGINE_by_id(id);
659 if (engine == NULL) {
660 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
661 id, ERR_error_string(ERR_get_error(), NULL));
665 while (post && post[0]) {
666 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
667 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
668 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
669 " %s %s [%s]", post[0], post[1],
670 ERR_error_string(ERR_get_error(), NULL));
671 ENGINE_remove(engine);
684 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
685 * @pkcs11_so_path: pksc11_so_path from the configuration
686 * @pcks11_module_path: pkcs11_module_path from the configuration
688 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
689 const char *pkcs11_module_path)
691 char *engine_id = "pkcs11";
692 const char *pre_cmd[] = {
693 "SO_PATH", NULL /* pkcs11_so_path */,
694 "ID", NULL /* engine_id */,
696 /* "NO_VCHECK", "1", */
700 const char *post_cmd[] = {
701 "MODULE_PATH", NULL /* pkcs11_module_path */,
708 pre_cmd[1] = pkcs11_so_path;
709 pre_cmd[3] = engine_id;
710 if (pkcs11_module_path)
711 post_cmd[1] = pkcs11_module_path;
715 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
718 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
723 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
724 * @opensc_so_path: opensc_so_path from the configuration
726 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
728 char *engine_id = "opensc";
729 const char *pre_cmd[] = {
730 "SO_PATH", NULL /* opensc_so_path */,
731 "ID", NULL /* engine_id */,
740 pre_cmd[1] = opensc_so_path;
741 pre_cmd[3] = engine_id;
743 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
746 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
748 #endif /* OPENSSL_NO_ENGINE */
751 void * tls_init(const struct tls_config *conf)
753 struct tls_data *data;
755 struct tls_context *context;
758 if (tls_openssl_ref_count == 0) {
759 tls_global = context = tls_context_new(conf);
764 if (conf && conf->fips_mode) {
765 static int fips_enabled = 0;
767 if (!fips_enabled && !FIPS_mode_set(1)) {
768 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
770 ERR_load_crypto_strings();
771 ERR_print_errors_fp(stderr);
776 wpa_printf(MSG_INFO, "Running in FIPS mode");
780 #else /* OPENSSL_FIPS */
781 if (conf && conf->fips_mode) {
782 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
788 #endif /* OPENSSL_FIPS */
789 #endif /* CONFIG_FIPS */
790 SSL_load_error_strings();
792 #ifndef OPENSSL_NO_SHA256
793 EVP_add_digest(EVP_sha256());
794 #endif /* OPENSSL_NO_SHA256 */
795 /* TODO: if /dev/urandom is available, PRNG is seeded
796 * automatically. If this is not the case, random data should
800 #ifndef OPENSSL_NO_RC2
802 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
803 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
804 * versions, but it looks like OpenSSL 1.0.0 does not do that
807 EVP_add_cipher(EVP_rc2_40_cbc());
808 #endif /* OPENSSL_NO_RC2 */
810 #endif /* PKCS12_FUNCS */
812 context = tls_context_new(conf);
816 tls_openssl_ref_count++;
818 data = os_zalloc(sizeof(*data));
820 ssl = SSL_CTX_new(SSLv23_method());
824 tls_openssl_ref_count--;
825 if (context != tls_global)
827 if (tls_openssl_ref_count == 0) {
835 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
836 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
838 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
839 SSL_CTX_set_app_data(ssl, context);
841 #ifndef OPENSSL_NO_ENGINE
842 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
843 ERR_load_ENGINE_strings();
844 ENGINE_load_dynamic();
847 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
848 conf->pkcs11_module_path)) {
849 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
850 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
851 conf->pkcs11_module_path)) {
856 #endif /* OPENSSL_NO_ENGINE */
858 if (conf && conf->openssl_ciphers)
859 ciphers = conf->openssl_ciphers;
861 ciphers = "DEFAULT:!EXP:!LOW";
862 if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
863 wpa_printf(MSG_ERROR,
864 "OpenSSL: Failed to set cipher string '%s'",
874 void tls_deinit(void *ssl_ctx)
876 struct tls_data *data = ssl_ctx;
877 SSL_CTX *ssl = data->ssl;
878 struct tls_context *context = SSL_CTX_get_app_data(ssl);
879 if (context != tls_global)
883 tls_openssl_ref_count--;
884 if (tls_openssl_ref_count == 0) {
885 #ifndef OPENSSL_NO_ENGINE
887 #endif /* OPENSSL_NO_ENGINE */
888 CRYPTO_cleanup_all_ex_data();
889 ERR_remove_thread_state(NULL);
892 os_free(tls_global->ocsp_stapling_response);
893 tls_global->ocsp_stapling_response = NULL;
902 #ifndef OPENSSL_NO_ENGINE
904 /* Cryptoki return values */
905 #define CKR_PIN_INCORRECT 0x000000a0
906 #define CKR_PIN_INVALID 0x000000a1
907 #define CKR_PIN_LEN_RANGE 0x000000a2
910 #define ERR_LIB_PKCS11 ERR_LIB_USER
912 static int tls_is_pin_error(unsigned int err)
914 return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
915 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
916 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
917 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
920 #endif /* OPENSSL_NO_ENGINE */
923 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
924 const char *pin, const char *key_id,
925 const char *cert_id, const char *ca_cert_id)
927 #ifndef OPENSSL_NO_ENGINE
929 if (engine_id == NULL) {
930 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
936 ENGINE_load_dynamic();
938 conn->engine = ENGINE_by_id(engine_id);
940 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
941 engine_id, ERR_error_string(ERR_get_error(), NULL));
944 if (ENGINE_init(conn->engine) != 1) {
945 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
946 "(engine: %s) [%s]", engine_id,
947 ERR_error_string(ERR_get_error(), NULL));
950 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
953 if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
954 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
955 ERR_error_string(ERR_get_error(), NULL));
961 * Ensure that the ENGINE does not attempt to use the OpenSSL
962 * UI system to obtain a PIN, if we didn't provide one.
965 const void *password;
966 const char *prompt_info;
967 } key_cb = { "", NULL };
969 /* load private key first in-case PIN is required for cert */
970 conn->private_key = ENGINE_load_private_key(conn->engine,
973 if (!conn->private_key) {
974 unsigned long err = ERR_get_error();
976 wpa_printf(MSG_ERROR,
977 "ENGINE: cannot load private key with id '%s' [%s]",
979 ERR_error_string(err, NULL));
980 if (tls_is_pin_error(err))
981 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
983 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
988 /* handle a certificate and/or CA certificate */
989 if (cert_id || ca_cert_id) {
990 const char *cmd_name = "LOAD_CERT_CTRL";
992 /* test if the engine supports a LOAD_CERT_CTRL */
993 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
994 0, (void *)cmd_name, NULL)) {
995 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
996 " loading certificates");
997 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1006 ENGINE_free(conn->engine);
1007 conn->engine = NULL;
1010 if (conn->private_key) {
1011 EVP_PKEY_free(conn->private_key);
1012 conn->private_key = NULL;
1016 #else /* OPENSSL_NO_ENGINE */
1018 #endif /* OPENSSL_NO_ENGINE */
1022 static void tls_engine_deinit(struct tls_connection *conn)
1024 #ifndef OPENSSL_NO_ENGINE
1025 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1026 if (conn->private_key) {
1027 EVP_PKEY_free(conn->private_key);
1028 conn->private_key = NULL;
1031 ENGINE_finish(conn->engine);
1032 conn->engine = NULL;
1034 #endif /* OPENSSL_NO_ENGINE */
1038 int tls_get_errors(void *ssl_ctx)
1043 while ((err = ERR_get_error())) {
1044 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1045 ERR_error_string(err, NULL));
1053 static void tls_msg_cb(int write_p, int version, int content_type,
1054 const void *buf, size_t len, SSL *ssl, void *arg)
1056 struct tls_connection *conn = arg;
1057 const u8 *pos = buf;
1059 wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
1060 write_p ? "TX" : "RX", version, content_type);
1061 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1062 if (content_type == 24 && len >= 3 && pos[0] == 1) {
1063 size_t payload_len = WPA_GET_BE16(pos + 1);
1064 if (payload_len + 3 > len) {
1065 wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1066 conn->invalid_hb_used = 1;
1072 struct tls_connection * tls_connection_init(void *ssl_ctx)
1074 struct tls_data *data = ssl_ctx;
1075 SSL_CTX *ssl = data->ssl;
1076 struct tls_connection *conn;
1078 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1080 conn = os_zalloc(sizeof(*conn));
1083 conn->ssl_ctx = ssl;
1084 conn->ssl = SSL_new(ssl);
1085 if (conn->ssl == NULL) {
1086 tls_show_errors(MSG_INFO, __func__,
1087 "Failed to initialize new SSL connection");
1092 conn->context = context;
1093 SSL_set_app_data(conn->ssl, conn);
1094 SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1095 SSL_set_msg_callback_arg(conn->ssl, conn);
1096 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1097 SSL_OP_SINGLE_DH_USE;
1098 #ifdef SSL_OP_NO_COMPRESSION
1099 options |= SSL_OP_NO_COMPRESSION;
1100 #endif /* SSL_OP_NO_COMPRESSION */
1101 SSL_set_options(conn->ssl, options);
1103 conn->ssl_in = BIO_new(BIO_s_mem());
1104 if (!conn->ssl_in) {
1105 tls_show_errors(MSG_INFO, __func__,
1106 "Failed to create a new BIO for ssl_in");
1107 SSL_free(conn->ssl);
1112 conn->ssl_out = BIO_new(BIO_s_mem());
1113 if (!conn->ssl_out) {
1114 tls_show_errors(MSG_INFO, __func__,
1115 "Failed to create a new BIO for ssl_out");
1116 SSL_free(conn->ssl);
1117 BIO_free(conn->ssl_in);
1122 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1128 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1132 SSL_free(conn->ssl);
1133 tls_engine_deinit(conn);
1134 os_free(conn->subject_match);
1135 os_free(conn->altsubject_match);
1136 os_free(conn->suffix_match);
1137 os_free(conn->domain_match);
1138 os_free(conn->session_ticket);
1143 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1145 return conn ? SSL_is_init_finished(conn->ssl) : 0;
1149 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1154 /* Shutdown previous TLS connection without notifying the peer
1155 * because the connection was already terminated in practice
1156 * and "close notify" shutdown alert would confuse AS. */
1157 SSL_set_quiet_shutdown(conn->ssl, 1);
1158 SSL_shutdown(conn->ssl);
1159 return SSL_clear(conn->ssl) == 1 ? 0 : -1;
1163 static int tls_match_altsubject_component(X509 *cert, int type,
1164 const char *value, size_t len)
1171 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1173 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1174 gen = sk_GENERAL_NAME_value(ext, i);
1175 if (gen->type != type)
1177 if (os_strlen((char *) gen->d.ia5->data) == len &&
1178 os_memcmp(value, gen->d.ia5->data, len) == 0)
1186 static int tls_match_altsubject(X509 *cert, const char *match)
1189 const char *pos, *end;
1194 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1197 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1200 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1204 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1208 end = os_strchr(pos, ';');
1210 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1211 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1212 os_strncmp(end + 1, "URI:", 4) == 0)
1214 end = os_strchr(end + 1, ';');
1219 len = os_strlen(pos);
1220 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1229 #ifndef CONFIG_NATIVE_WINDOWS
1230 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1233 size_t i, match_len;
1235 /* Check for embedded nuls that could mess up suffix matching */
1236 for (i = 0; i < len; i++) {
1237 if (val[i] == '\0') {
1238 wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1243 match_len = os_strlen(match);
1244 if (match_len > len || (full && match_len != len))
1247 if (os_strncasecmp((const char *) val + len - match_len, match,
1249 return 0; /* no match */
1251 if (match_len == len)
1252 return 1; /* exact match */
1254 if (val[len - match_len - 1] == '.')
1255 return 1; /* full label match completes suffix match */
1257 wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1260 #endif /* CONFIG_NATIVE_WINDOWS */
1263 static int tls_match_suffix(X509 *cert, const char *match, int full)
1265 #ifdef CONFIG_NATIVE_WINDOWS
1266 /* wincrypt.h has conflicting X509_NAME definition */
1268 #else /* CONFIG_NATIVE_WINDOWS */
1276 wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1277 full ? "": "suffix ", match);
1279 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1281 for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1282 gen = sk_GENERAL_NAME_value(ext, j);
1283 if (gen->type != GEN_DNS)
1286 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1287 gen->d.dNSName->data,
1288 gen->d.dNSName->length);
1289 if (domain_suffix_match(gen->d.dNSName->data,
1290 gen->d.dNSName->length, match, full) ==
1292 wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
1293 full ? "Match" : "Suffix match");
1299 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1303 name = X509_get_subject_name(cert);
1309 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1312 e = X509_NAME_get_entry(name, i);
1315 cn = X509_NAME_ENTRY_get_data(e);
1318 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1319 cn->data, cn->length);
1320 if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
1322 wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
1323 full ? "Match" : "Suffix match");
1328 wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
1329 full ? "": "suffix ");
1331 #endif /* CONFIG_NATIVE_WINDOWS */
1335 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1338 case X509_V_ERR_CERT_REVOKED:
1339 return TLS_FAIL_REVOKED;
1340 case X509_V_ERR_CERT_NOT_YET_VALID:
1341 case X509_V_ERR_CRL_NOT_YET_VALID:
1342 return TLS_FAIL_NOT_YET_VALID;
1343 case X509_V_ERR_CERT_HAS_EXPIRED:
1344 case X509_V_ERR_CRL_HAS_EXPIRED:
1345 return TLS_FAIL_EXPIRED;
1346 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1347 case X509_V_ERR_UNABLE_TO_GET_CRL:
1348 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1349 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1350 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1351 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1352 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1353 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1354 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1355 case X509_V_ERR_INVALID_CA:
1356 return TLS_FAIL_UNTRUSTED;
1357 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1358 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1359 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1360 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1361 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1362 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1363 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1364 case X509_V_ERR_CERT_UNTRUSTED:
1365 case X509_V_ERR_CERT_REJECTED:
1366 return TLS_FAIL_BAD_CERTIFICATE;
1368 return TLS_FAIL_UNSPECIFIED;
1373 static struct wpabuf * get_x509_cert(X509 *cert)
1378 int cert_len = i2d_X509(cert, NULL);
1382 buf = wpabuf_alloc(cert_len);
1386 tmp = wpabuf_put(buf, cert_len);
1387 i2d_X509(cert, &tmp);
1392 static void openssl_tls_fail_event(struct tls_connection *conn,
1393 X509 *err_cert, int err, int depth,
1394 const char *subject, const char *err_str,
1395 enum tls_fail_reason reason)
1397 union tls_event_data ev;
1398 struct wpabuf *cert = NULL;
1399 struct tls_context *context = conn->context;
1401 if (context->event_cb == NULL)
1404 cert = get_x509_cert(err_cert);
1405 os_memset(&ev, 0, sizeof(ev));
1406 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1407 reason : openssl_tls_fail_reason(err);
1408 ev.cert_fail.depth = depth;
1409 ev.cert_fail.subject = subject;
1410 ev.cert_fail.reason_txt = err_str;
1411 ev.cert_fail.cert = cert;
1412 context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1417 static void openssl_tls_cert_event(struct tls_connection *conn,
1418 X509 *err_cert, int depth,
1419 const char *subject)
1421 struct wpabuf *cert = NULL;
1422 union tls_event_data ev;
1423 struct tls_context *context = conn->context;
1424 char *altsubject[TLS_MAX_ALT_SUBJECT];
1425 int alt, num_altsubject = 0;
1429 #ifdef CONFIG_SHA256
1431 #endif /* CONFIG_SHA256 */
1433 if (context->event_cb == NULL)
1436 os_memset(&ev, 0, sizeof(ev));
1437 if (conn->cert_probe || context->cert_in_cb) {
1438 cert = get_x509_cert(err_cert);
1439 ev.peer_cert.cert = cert;
1441 #ifdef CONFIG_SHA256
1445 addr[0] = wpabuf_head(cert);
1446 len[0] = wpabuf_len(cert);
1447 if (sha256_vector(1, addr, len, hash) == 0) {
1448 ev.peer_cert.hash = hash;
1449 ev.peer_cert.hash_len = sizeof(hash);
1452 #endif /* CONFIG_SHA256 */
1453 ev.peer_cert.depth = depth;
1454 ev.peer_cert.subject = subject;
1456 ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1457 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1460 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1462 gen = sk_GENERAL_NAME_value(ext, i);
1463 if (gen->type != GEN_EMAIL &&
1464 gen->type != GEN_DNS &&
1465 gen->type != GEN_URI)
1468 pos = os_malloc(10 + gen->d.ia5->length + 1);
1471 altsubject[num_altsubject++] = pos;
1473 switch (gen->type) {
1475 os_memcpy(pos, "EMAIL:", 6);
1479 os_memcpy(pos, "DNS:", 4);
1483 os_memcpy(pos, "URI:", 4);
1488 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1489 pos += gen->d.ia5->length;
1493 for (alt = 0; alt < num_altsubject; alt++)
1494 ev.peer_cert.altsubject[alt] = altsubject[alt];
1495 ev.peer_cert.num_altsubject = num_altsubject;
1497 context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1499 for (alt = 0; alt < num_altsubject; alt++)
1500 os_free(altsubject[alt]);
1504 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1510 struct tls_connection *conn;
1511 struct tls_context *context;
1512 char *match, *altmatch, *suffix_match, *domain_match;
1513 const char *err_str;
1515 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1519 err = X509_STORE_CTX_get_error(x509_ctx);
1520 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1521 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1522 SSL_get_ex_data_X509_STORE_CTX_idx());
1523 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1525 conn = SSL_get_app_data(ssl);
1530 conn->peer_cert = err_cert;
1531 else if (depth == 1)
1532 conn->peer_issuer = err_cert;
1533 else if (depth == 2)
1534 conn->peer_issuer_issuer = err_cert;
1536 context = conn->context;
1537 match = conn->subject_match;
1538 altmatch = conn->altsubject_match;
1539 suffix_match = conn->suffix_match;
1540 domain_match = conn->domain_match;
1542 if (!preverify_ok && !conn->ca_cert_verify)
1544 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1546 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1547 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1548 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1549 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1554 err_str = X509_verify_cert_error_string(err);
1556 #ifdef CONFIG_SHA256
1558 * Do not require preverify_ok so we can explicity allow otherwise
1559 * invalid pinned server certificates.
1561 if (depth == 0 && conn->server_cert_only) {
1562 struct wpabuf *cert;
1563 cert = get_x509_cert(err_cert);
1565 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1566 "server certificate data");
1572 addr[0] = wpabuf_head(cert);
1573 len[0] = wpabuf_len(cert);
1574 if (sha256_vector(1, addr, len, hash) < 0 ||
1575 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1576 err_str = "Server certificate mismatch";
1577 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1579 } else if (!preverify_ok) {
1581 * Certificate matches pinned certificate, allow
1582 * regardless of other problems.
1584 wpa_printf(MSG_DEBUG,
1585 "OpenSSL: Ignore validation issues for a pinned server certificate");
1591 #endif /* CONFIG_SHA256 */
1593 if (!preverify_ok) {
1594 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1595 " error %d (%s) depth %d for '%s'", err, err_str,
1597 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1598 err_str, TLS_FAIL_UNSPECIFIED);
1599 return preverify_ok;
1602 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1603 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1604 preverify_ok, err, err_str,
1605 conn->ca_cert_verify, depth, buf);
1606 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1607 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1608 "match with '%s'", buf, match);
1610 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1612 TLS_FAIL_SUBJECT_MISMATCH);
1613 } else if (depth == 0 && altmatch &&
1614 !tls_match_altsubject(err_cert, altmatch)) {
1615 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1616 "'%s' not found", altmatch);
1618 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1619 "AltSubject mismatch",
1620 TLS_FAIL_ALTSUBJECT_MISMATCH);
1621 } else if (depth == 0 && suffix_match &&
1622 !tls_match_suffix(err_cert, suffix_match, 0)) {
1623 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
1626 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1627 "Domain suffix mismatch",
1628 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1629 } else if (depth == 0 && domain_match &&
1630 !tls_match_suffix(err_cert, domain_match, 1)) {
1631 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
1634 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1636 TLS_FAIL_DOMAIN_MISMATCH);
1638 openssl_tls_cert_event(conn, err_cert, depth, buf);
1640 if (conn->cert_probe && preverify_ok && depth == 0) {
1641 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1642 "on probe-only run");
1644 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1645 "Server certificate chain probe",
1646 TLS_FAIL_SERVER_CHAIN_PROBE);
1649 if (preverify_ok && context->event_cb != NULL)
1650 context->event_cb(context->cb_ctx,
1651 TLS_CERT_CHAIN_SUCCESS, NULL);
1653 return preverify_ok;
1657 #ifndef OPENSSL_NO_STDIO
1658 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
1660 SSL_CTX *ssl_ctx = data->ssl;
1661 X509_LOOKUP *lookup;
1664 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
1665 X509_LOOKUP_file());
1666 if (lookup == NULL) {
1667 tls_show_errors(MSG_WARNING, __func__,
1668 "Failed add lookup for X509 store");
1672 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1673 unsigned long err = ERR_peek_error();
1674 tls_show_errors(MSG_WARNING, __func__,
1675 "Failed load CA in DER format");
1676 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1677 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1678 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1679 "cert already in hash table error",
1687 #endif /* OPENSSL_NO_STDIO */
1690 static int tls_connection_ca_cert(struct tls_data *data,
1691 struct tls_connection *conn,
1692 const char *ca_cert, const u8 *ca_cert_blob,
1693 size_t ca_cert_blob_len, const char *ca_path)
1695 SSL_CTX *ssl_ctx = data->ssl;
1699 * Remove previously configured trusted CA certificates before adding
1702 store = X509_STORE_new();
1703 if (store == NULL) {
1704 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1705 "certificate store", __func__);
1708 SSL_CTX_set_cert_store(ssl_ctx, store);
1710 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1711 conn->ca_cert_verify = 1;
1713 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1714 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1716 conn->cert_probe = 1;
1717 conn->ca_cert_verify = 0;
1721 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1722 #ifdef CONFIG_SHA256
1723 const char *pos = ca_cert + 7;
1724 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1725 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1726 "hash value '%s'", ca_cert);
1730 if (os_strlen(pos) != 32 * 2) {
1731 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1732 "hash length in ca_cert '%s'", ca_cert);
1735 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1736 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1737 "value in ca_cert '%s'", ca_cert);
1740 conn->server_cert_only = 1;
1741 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1742 "certificate match");
1744 #else /* CONFIG_SHA256 */
1745 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1746 "cannot validate server certificate hash");
1748 #endif /* CONFIG_SHA256 */
1752 X509 *cert = d2i_X509(NULL,
1753 (const unsigned char **) &ca_cert_blob,
1756 tls_show_errors(MSG_WARNING, __func__,
1757 "Failed to parse ca_cert_blob");
1761 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
1763 unsigned long err = ERR_peek_error();
1764 tls_show_errors(MSG_WARNING, __func__,
1765 "Failed to add ca_cert_blob to "
1766 "certificate store");
1767 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1768 ERR_GET_REASON(err) ==
1769 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1770 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1771 "cert already in hash table error",
1779 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1780 "to certificate store", __func__);
1785 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1786 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1787 STACK_OF(X509_INFO) *stack = NULL;
1791 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1797 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1798 X509_INFO *info = sk_X509_INFO_value(stack, i);
1800 X509_STORE_add_cert(ssl_ctx->cert_store,
1804 X509_STORE_add_crl(ssl_ctx->cert_store,
1808 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1809 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1812 #endif /* ANDROID */
1814 #ifdef CONFIG_NATIVE_WINDOWS
1815 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1817 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1818 "system certificate store");
1821 #endif /* CONFIG_NATIVE_WINDOWS */
1823 if (ca_cert || ca_path) {
1824 #ifndef OPENSSL_NO_STDIO
1825 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1827 tls_show_errors(MSG_WARNING, __func__,
1828 "Failed to load root certificates");
1830 tls_load_ca_der(data, ca_cert) == 0) {
1831 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1832 "DER format CA certificate",
1837 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1838 "certificate(s) loaded");
1839 tls_get_errors(data);
1841 #else /* OPENSSL_NO_STDIO */
1842 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1845 #endif /* OPENSSL_NO_STDIO */
1847 /* No ca_cert configured - do not try to verify server
1849 conn->ca_cert_verify = 0;
1856 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
1858 SSL_CTX *ssl_ctx = data->ssl;
1861 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1863 tls_show_errors(MSG_WARNING, __func__,
1864 "Failed to load root certificates");
1868 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1869 "certificate(s) loaded");
1871 #ifndef OPENSSL_NO_STDIO
1872 /* Add the same CAs to the client certificate requests */
1873 SSL_CTX_set_client_CA_list(ssl_ctx,
1874 SSL_load_client_CA_file(ca_cert));
1875 #endif /* OPENSSL_NO_STDIO */
1882 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1887 struct tls_data *data = ssl_ctx;
1888 X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
1890 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1891 "certificate store when enabling "
1895 flags = X509_V_FLAG_CRL_CHECK;
1897 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1898 X509_STORE_set_flags(cs, flags);
1904 static int tls_connection_set_subject_match(struct tls_connection *conn,
1905 const char *subject_match,
1906 const char *altsubject_match,
1907 const char *suffix_match,
1908 const char *domain_match)
1910 os_free(conn->subject_match);
1911 conn->subject_match = NULL;
1912 if (subject_match) {
1913 conn->subject_match = os_strdup(subject_match);
1914 if (conn->subject_match == NULL)
1918 os_free(conn->altsubject_match);
1919 conn->altsubject_match = NULL;
1920 if (altsubject_match) {
1921 conn->altsubject_match = os_strdup(altsubject_match);
1922 if (conn->altsubject_match == NULL)
1926 os_free(conn->suffix_match);
1927 conn->suffix_match = NULL;
1929 conn->suffix_match = os_strdup(suffix_match);
1930 if (conn->suffix_match == NULL)
1934 os_free(conn->domain_match);
1935 conn->domain_match = NULL;
1937 conn->domain_match = os_strdup(domain_match);
1938 if (conn->domain_match == NULL)
1946 static void tls_set_conn_flags(SSL *ssl, unsigned int flags)
1948 #ifdef SSL_OP_NO_TICKET
1949 if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
1950 SSL_set_options(ssl, SSL_OP_NO_TICKET);
1951 #ifdef SSL_clear_options
1953 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
1954 #endif /* SSL_clear_options */
1955 #endif /* SSL_OP_NO_TICKET */
1957 #ifdef SSL_OP_NO_TLSv1
1958 if (flags & TLS_CONN_DISABLE_TLSv1_0)
1959 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
1961 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
1962 #endif /* SSL_OP_NO_TLSv1 */
1963 #ifdef SSL_OP_NO_TLSv1_1
1964 if (flags & TLS_CONN_DISABLE_TLSv1_1)
1965 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
1967 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
1968 #endif /* SSL_OP_NO_TLSv1_1 */
1969 #ifdef SSL_OP_NO_TLSv1_2
1970 if (flags & TLS_CONN_DISABLE_TLSv1_2)
1971 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
1973 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
1974 #endif /* SSL_OP_NO_TLSv1_2 */
1978 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1979 int verify_peer, unsigned int flags,
1980 const u8 *session_ctx, size_t session_ctx_len)
1982 static int counter = 0;
1988 conn->ca_cert_verify = 1;
1989 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1990 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1991 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1993 conn->ca_cert_verify = 0;
1994 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1997 tls_set_conn_flags(conn->ssl, flags);
1998 conn->flags = flags;
2000 SSL_set_accept_state(conn->ssl);
2003 * Set session id context in order to avoid fatal errors when client
2004 * tries to resume a session. However, set the context to a unique
2005 * value in order to effectively disable session resumption for now
2006 * since not all areas of the server code are ready for it (e.g.,
2007 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
2011 SSL_set_session_id_context(conn->ssl,
2012 (const unsigned char *) &counter,
2019 static int tls_connection_client_cert(struct tls_connection *conn,
2020 const char *client_cert,
2021 const u8 *client_cert_blob,
2022 size_t client_cert_blob_len)
2024 if (client_cert == NULL && client_cert_blob == NULL)
2027 if (client_cert_blob &&
2028 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
2029 client_cert_blob_len) == 1) {
2030 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
2033 } else if (client_cert_blob) {
2034 tls_show_errors(MSG_DEBUG, __func__,
2035 "SSL_use_certificate_ASN1 failed");
2038 if (client_cert == NULL)
2042 if (os_strncmp("keystore://", client_cert, 11) == 0) {
2043 BIO *bio = BIO_from_keystore(&client_cert[11]);
2047 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2051 if (SSL_use_certificate(conn->ssl, x509) == 1)
2057 #endif /* ANDROID */
2059 #ifndef OPENSSL_NO_STDIO
2060 if (SSL_use_certificate_file(conn->ssl, client_cert,
2061 SSL_FILETYPE_ASN1) == 1) {
2062 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2067 if (SSL_use_certificate_file(conn->ssl, client_cert,
2068 SSL_FILETYPE_PEM) == 1) {
2070 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2075 tls_show_errors(MSG_DEBUG, __func__,
2076 "SSL_use_certificate_file failed");
2077 #else /* OPENSSL_NO_STDIO */
2078 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2079 #endif /* OPENSSL_NO_STDIO */
2085 static int tls_global_client_cert(struct tls_data *data,
2086 const char *client_cert)
2088 #ifndef OPENSSL_NO_STDIO
2089 SSL_CTX *ssl_ctx = data->ssl;
2091 if (client_cert == NULL)
2094 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2095 SSL_FILETYPE_ASN1) != 1 &&
2096 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2097 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2098 SSL_FILETYPE_PEM) != 1) {
2099 tls_show_errors(MSG_INFO, __func__,
2100 "Failed to load client certificate");
2104 #else /* OPENSSL_NO_STDIO */
2105 if (client_cert == NULL)
2107 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2109 #endif /* OPENSSL_NO_STDIO */
2113 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2115 if (password == NULL) {
2118 os_strlcpy(buf, (char *) password, size);
2119 return os_strlen(buf);
2124 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
2129 STACK_OF(X509) *certs;
2138 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2139 tls_show_errors(MSG_DEBUG, __func__,
2140 "Failed to parse PKCS12 file");
2144 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2147 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2149 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2150 "subject='%s'", buf);
2152 if (SSL_use_certificate(ssl, cert) != 1)
2155 if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
2162 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2164 if (SSL_use_PrivateKey(ssl, pkey) != 1)
2167 if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
2170 EVP_PKEY_free(pkey);
2174 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2175 SSL_clear_chain_certs(ssl);
2176 while ((cert = sk_X509_pop(certs)) != NULL) {
2177 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2179 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2180 " from PKCS12: subject='%s'", buf);
2181 if (SSL_add1_chain_cert(ssl, cert) != 1) {
2186 sk_X509_free(certs);
2187 #ifndef OPENSSL_IS_BORINGSSL
2188 res = SSL_build_cert_chain(ssl,
2189 SSL_BUILD_CHAIN_FLAG_CHECK |
2190 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2192 tls_show_errors(MSG_DEBUG, __func__,
2193 "Failed to build certificate chain");
2194 } else if (res == 2) {
2195 wpa_printf(MSG_DEBUG,
2196 "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2198 #endif /* OPENSSL_IS_BORINGSSL */
2200 * Try to continue regardless of result since it is possible for
2201 * the extra certificates not to be required.
2204 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2205 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2206 SSL_CTX_clear_extra_chain_certs(data->ssl);
2207 #endif /* OPENSSL_VERSION_NUMBER >= 0x10001000L */
2208 while ((cert = sk_X509_pop(certs)) != NULL) {
2209 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2211 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2212 " from PKCS12: subject='%s'", buf);
2214 * There is no SSL equivalent for the chain cert - so
2215 * always add it to the context...
2217 if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
2223 sk_X509_free(certs);
2224 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2230 tls_get_errors(data);
2234 #endif /* PKCS12_FUNCS */
2237 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
2238 const char *private_key, const char *passwd)
2244 f = fopen(private_key, "rb");
2248 p12 = d2i_PKCS12_fp(f, NULL);
2252 tls_show_errors(MSG_INFO, __func__,
2253 "Failed to use PKCS#12 file");
2257 return tls_parse_pkcs12(data, ssl, p12, passwd);
2259 #else /* PKCS12_FUNCS */
2260 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2263 #endif /* PKCS12_FUNCS */
2267 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
2268 const u8 *blob, size_t len, const char *passwd)
2273 p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2275 tls_show_errors(MSG_INFO, __func__,
2276 "Failed to use PKCS#12 blob");
2280 return tls_parse_pkcs12(data, ssl, p12, passwd);
2282 #else /* PKCS12_FUNCS */
2283 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2286 #endif /* PKCS12_FUNCS */
2290 #ifndef OPENSSL_NO_ENGINE
2291 static int tls_engine_get_cert(struct tls_connection *conn,
2292 const char *cert_id,
2295 /* this runs after the private key is loaded so no PIN is required */
2297 const char *cert_id;
2300 params.cert_id = cert_id;
2303 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2304 0, ¶ms, NULL, 1)) {
2305 unsigned long err = ERR_get_error();
2307 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2308 " '%s' [%s]", cert_id,
2309 ERR_error_string(err, NULL));
2310 if (tls_is_pin_error(err))
2311 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2312 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2315 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2317 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2319 *cert = params.cert;
2322 #endif /* OPENSSL_NO_ENGINE */
2325 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2326 const char *cert_id)
2328 #ifndef OPENSSL_NO_ENGINE
2331 if (tls_engine_get_cert(conn, cert_id, &cert))
2334 if (!SSL_use_certificate(conn->ssl, cert)) {
2335 tls_show_errors(MSG_ERROR, __func__,
2336 "SSL_use_certificate failed");
2341 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2345 #else /* OPENSSL_NO_ENGINE */
2347 #endif /* OPENSSL_NO_ENGINE */
2351 static int tls_connection_engine_ca_cert(struct tls_data *data,
2352 struct tls_connection *conn,
2353 const char *ca_cert_id)
2355 #ifndef OPENSSL_NO_ENGINE
2357 SSL_CTX *ssl_ctx = data->ssl;
2360 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2363 /* start off the same as tls_connection_ca_cert */
2364 store = X509_STORE_new();
2365 if (store == NULL) {
2366 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2367 "certificate store", __func__);
2371 SSL_CTX_set_cert_store(ssl_ctx, store);
2372 if (!X509_STORE_add_cert(store, cert)) {
2373 unsigned long err = ERR_peek_error();
2374 tls_show_errors(MSG_WARNING, __func__,
2375 "Failed to add CA certificate from engine "
2376 "to certificate store");
2377 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2378 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2379 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2380 " already in hash table error",
2388 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2389 "to certificate store", __func__);
2390 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2391 conn->ca_cert_verify = 1;
2395 #else /* OPENSSL_NO_ENGINE */
2397 #endif /* OPENSSL_NO_ENGINE */
2401 static int tls_connection_engine_private_key(struct tls_connection *conn)
2403 #ifndef OPENSSL_NO_ENGINE
2404 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2405 tls_show_errors(MSG_ERROR, __func__,
2406 "ENGINE: cannot use private key for TLS");
2409 if (!SSL_check_private_key(conn->ssl)) {
2410 tls_show_errors(MSG_INFO, __func__,
2411 "Private key failed verification");
2415 #else /* OPENSSL_NO_ENGINE */
2416 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2417 "engine support was not compiled in");
2419 #endif /* OPENSSL_NO_ENGINE */
2423 static int tls_connection_private_key(struct tls_data *data,
2424 struct tls_connection *conn,
2425 const char *private_key,
2426 const char *private_key_passwd,
2427 const u8 *private_key_blob,
2428 size_t private_key_blob_len)
2430 SSL_CTX *ssl_ctx = data->ssl;
2434 if (private_key == NULL && private_key_blob == NULL)
2437 if (private_key_passwd) {
2438 passwd = os_strdup(private_key_passwd);
2444 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2445 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2448 while (private_key_blob) {
2449 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2450 (u8 *) private_key_blob,
2451 private_key_blob_len) == 1) {
2452 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2453 "ASN1(EVP_PKEY_RSA) --> OK");
2458 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2459 (u8 *) private_key_blob,
2460 private_key_blob_len) == 1) {
2461 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2462 "ASN1(EVP_PKEY_DSA) --> OK");
2467 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2468 (u8 *) private_key_blob,
2469 private_key_blob_len) == 1) {
2470 wpa_printf(MSG_DEBUG, "OpenSSL: "
2471 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2476 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
2477 private_key_blob_len, passwd) == 0) {
2478 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2487 while (!ok && private_key) {
2488 #ifndef OPENSSL_NO_STDIO
2489 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2490 SSL_FILETYPE_ASN1) == 1) {
2491 wpa_printf(MSG_DEBUG, "OpenSSL: "
2492 "SSL_use_PrivateKey_File (DER) --> OK");
2497 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2498 SSL_FILETYPE_PEM) == 1) {
2499 wpa_printf(MSG_DEBUG, "OpenSSL: "
2500 "SSL_use_PrivateKey_File (PEM) --> OK");
2504 #else /* OPENSSL_NO_STDIO */
2505 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2507 #endif /* OPENSSL_NO_STDIO */
2509 if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
2511 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2517 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2518 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2519 "access certificate store --> OK");
2528 tls_show_errors(MSG_INFO, __func__,
2529 "Failed to load private key");
2534 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2537 if (!SSL_check_private_key(conn->ssl)) {
2538 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2543 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2548 static int tls_global_private_key(struct tls_data *data,
2549 const char *private_key,
2550 const char *private_key_passwd)
2552 SSL_CTX *ssl_ctx = data->ssl;
2555 if (private_key == NULL)
2558 if (private_key_passwd) {
2559 passwd = os_strdup(private_key_passwd);
2565 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2566 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2568 #ifndef OPENSSL_NO_STDIO
2569 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2570 SSL_FILETYPE_ASN1) != 1 &&
2571 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2572 SSL_FILETYPE_PEM) != 1 &&
2573 #endif /* OPENSSL_NO_STDIO */
2574 tls_read_pkcs12(data, NULL, private_key, passwd)) {
2575 tls_show_errors(MSG_INFO, __func__,
2576 "Failed to load private key");
2583 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2585 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2586 tls_show_errors(MSG_INFO, __func__,
2587 "Private key failed verification");
2595 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2597 #ifdef OPENSSL_NO_DH
2598 if (dh_file == NULL)
2600 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2601 "dh_file specified");
2603 #else /* OPENSSL_NO_DH */
2607 /* TODO: add support for dh_blob */
2608 if (dh_file == NULL)
2613 bio = BIO_new_file(dh_file, "r");
2615 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2616 dh_file, ERR_error_string(ERR_get_error(), NULL));
2619 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2621 #ifndef OPENSSL_NO_DSA
2622 while (dh == NULL) {
2624 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2625 " trying to parse as DSA params", dh_file,
2626 ERR_error_string(ERR_get_error(), NULL));
2627 bio = BIO_new_file(dh_file, "r");
2630 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2633 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2634 "'%s': %s", dh_file,
2635 ERR_error_string(ERR_get_error(), NULL));
2639 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2640 dh = DSA_dup_DH(dsa);
2643 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2644 "params into DH params");
2649 #endif /* !OPENSSL_NO_DSA */
2651 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2656 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2657 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2659 ERR_error_string(ERR_get_error(), NULL));
2665 #endif /* OPENSSL_NO_DH */
2669 static int tls_global_dh(struct tls_data *data, const char *dh_file)
2671 #ifdef OPENSSL_NO_DH
2672 if (dh_file == NULL)
2674 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2675 "dh_file specified");
2677 #else /* OPENSSL_NO_DH */
2678 SSL_CTX *ssl_ctx = data->ssl;
2682 /* TODO: add support for dh_blob */
2683 if (dh_file == NULL)
2685 if (ssl_ctx == NULL)
2688 bio = BIO_new_file(dh_file, "r");
2690 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2691 dh_file, ERR_error_string(ERR_get_error(), NULL));
2694 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2696 #ifndef OPENSSL_NO_DSA
2697 while (dh == NULL) {
2699 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2700 " trying to parse as DSA params", dh_file,
2701 ERR_error_string(ERR_get_error(), NULL));
2702 bio = BIO_new_file(dh_file, "r");
2705 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2708 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2709 "'%s': %s", dh_file,
2710 ERR_error_string(ERR_get_error(), NULL));
2714 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2715 dh = DSA_dup_DH(dsa);
2718 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2719 "params into DH params");
2724 #endif /* !OPENSSL_NO_DSA */
2726 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2731 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2732 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2734 ERR_error_string(ERR_get_error(), NULL));
2740 #endif /* OPENSSL_NO_DH */
2744 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
2745 struct tls_random *keys)
2749 if (conn == NULL || keys == NULL)
2752 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2753 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2756 os_memset(keys, 0, sizeof(*keys));
2757 keys->client_random = ssl->s3->client_random;
2758 keys->client_random_len = SSL3_RANDOM_SIZE;
2759 keys->server_random = ssl->s3->server_random;
2760 keys->server_random_len = SSL3_RANDOM_SIZE;
2765 os_memset(keys, 0, sizeof(*keys));
2766 keys->client_random = conn->client_random;
2767 keys->client_random_len = SSL_get_client_random(
2768 ssl, conn->client_random, sizeof(conn->client_random));
2769 keys->server_random = conn->server_random;
2770 keys->server_random_len = SSL_get_server_random(
2771 ssl, conn->server_random, sizeof(conn->server_random));
2779 static int openssl_get_keyblock_size(SSL *ssl)
2781 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2782 const EVP_CIPHER *c;
2786 if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2787 ssl->read_hash == NULL)
2790 c = ssl->enc_read_ctx->cipher;
2791 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2792 h = EVP_MD_CTX_md(ssl->read_hash);
2797 md_size = EVP_MD_size(h);
2798 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2800 md_size = ssl->s3->tmp.new_mac_secret_size;
2805 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2806 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2807 EVP_CIPHER_iv_length(c));
2808 return 2 * (EVP_CIPHER_key_length(c) +
2810 EVP_CIPHER_iv_length(c));
2812 const SSL_CIPHER *ssl_cipher;
2814 const EVP_CIPHER *c;
2817 ssl_cipher = SSL_get_current_cipher(ssl);
2820 cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
2821 digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
2822 wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
2824 if (cipher < 0 || digest < 0)
2826 c = EVP_get_cipherbynid(cipher);
2827 h = EVP_get_digestbynid(digest);
2831 wpa_printf(MSG_DEBUG,
2832 "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
2833 EVP_CIPHER_key_length(c), EVP_MD_size(h),
2834 EVP_CIPHER_iv_length(c));
2835 return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
2836 EVP_CIPHER_iv_length(c));
2839 #endif /* CONFIG_FIPS */
2842 static int openssl_tls_prf(struct tls_connection *conn,
2843 const char *label, int server_random_first,
2844 int skip_keyblock, u8 *out, size_t out_len)
2847 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2850 #else /* CONFIG_FIPS */
2851 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2861 * TLS library did not support key generation, so get the needed TLS
2862 * session parameters and use an internal implementation of TLS PRF to
2869 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2870 ssl->session->master_key_length <= 0)
2872 ver = SSL_get_version(ssl);
2874 if (skip_keyblock) {
2875 skip = openssl_get_keyblock_size(ssl);
2878 tmp_out = os_malloc(skip + out_len);
2884 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2890 if (server_random_first) {
2891 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2892 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2895 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2896 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2900 if (os_strcmp(ver, "TLSv1.2") == 0) {
2901 tls_prf_sha256(ssl->session->master_key,
2902 ssl->session->master_key_length,
2903 label, rnd, 2 * SSL3_RANDOM_SIZE,
2904 _out, skip + out_len);
2906 } else if (tls_prf_sha1_md5(ssl->session->master_key,
2907 ssl->session->master_key_length,
2908 label, rnd, 2 * SSL3_RANDOM_SIZE,
2909 _out, skip + out_len) == 0) {
2913 if (ret == 0 && skip_keyblock)
2914 os_memcpy(out, _out + skip, out_len);
2915 bin_clear_free(tmp_out, skip);
2926 unsigned char client_random[SSL3_RANDOM_SIZE];
2927 unsigned char server_random[SSL3_RANDOM_SIZE];
2928 unsigned char master_key[64];
2929 size_t master_key_len;
2933 * TLS library did not support key generation, so get the needed TLS
2934 * session parameters and use an internal implementation of TLS PRF to
2943 ver = SSL_get_version(ssl);
2944 sess = SSL_get_session(ssl);
2948 if (skip_keyblock) {
2949 skip = openssl_get_keyblock_size(ssl);
2952 tmp_out = os_malloc(skip + out_len);
2958 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2964 SSL_get_client_random(ssl, client_random, sizeof(client_random));
2965 SSL_get_server_random(ssl, server_random, sizeof(server_random));
2966 master_key_len = SSL_SESSION_get_master_key(sess, master_key,
2967 sizeof(master_key));
2969 if (server_random_first) {
2970 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
2971 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random,
2974 os_memcpy(rnd, client_random, SSL3_RANDOM_SIZE);
2975 os_memcpy(rnd + SSL3_RANDOM_SIZE, server_random,
2979 if (os_strcmp(ver, "TLSv1.2") == 0) {
2980 tls_prf_sha256(master_key, master_key_len,
2981 label, rnd, 2 * SSL3_RANDOM_SIZE,
2982 _out, skip + out_len);
2984 } else if (tls_prf_sha1_md5(master_key, master_key_len,
2985 label, rnd, 2 * SSL3_RANDOM_SIZE,
2986 _out, skip + out_len) == 0) {
2989 os_memset(master_key, 0, sizeof(master_key));
2991 if (ret == 0 && skip_keyblock)
2992 os_memcpy(out, _out + skip, out_len);
2993 bin_clear_free(tmp_out, skip);
2997 #endif /* CONFIG_FIPS */
3001 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
3002 const char *label, int server_random_first,
3003 int skip_keyblock, u8 *out, size_t out_len)
3005 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3009 if (server_random_first || skip_keyblock)
3010 return openssl_tls_prf(conn, label,
3011 server_random_first, skip_keyblock,
3014 if (SSL_export_keying_material(ssl, out, out_len, label,
3015 os_strlen(label), NULL, 0, 0) == 1) {
3016 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
3020 return openssl_tls_prf(conn, label, server_random_first,
3021 skip_keyblock, out, out_len);
3025 static struct wpabuf *
3026 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
3030 struct wpabuf *out_data;
3033 * Give TLS handshake data from the server (if available) to OpenSSL
3036 if (in_data && wpabuf_len(in_data) > 0 &&
3037 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
3039 tls_show_errors(MSG_INFO, __func__,
3040 "Handshake failed - BIO_write");
3044 /* Initiate TLS handshake or continue the existing handshake */
3046 res = SSL_accept(conn->ssl);
3048 res = SSL_connect(conn->ssl);
3050 int err = SSL_get_error(conn->ssl, res);
3051 if (err == SSL_ERROR_WANT_READ)
3052 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
3054 else if (err == SSL_ERROR_WANT_WRITE)
3055 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
3058 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
3063 /* Get the TLS handshake data to be sent to the server */
3064 res = BIO_ctrl_pending(conn->ssl_out);
3065 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
3066 out_data = wpabuf_alloc(res);
3067 if (out_data == NULL) {
3068 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
3069 "handshake output (%d bytes)", res);
3070 if (BIO_reset(conn->ssl_out) < 0) {
3071 tls_show_errors(MSG_INFO, __func__,
3072 "BIO_reset failed");
3076 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
3079 tls_show_errors(MSG_INFO, __func__,
3080 "Handshake failed - BIO_read");
3081 if (BIO_reset(conn->ssl_out) < 0) {
3082 tls_show_errors(MSG_INFO, __func__,
3083 "BIO_reset failed");
3085 wpabuf_free(out_data);
3088 wpabuf_put(out_data, res);
3094 static struct wpabuf *
3095 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
3097 struct wpabuf *appl_data;
3100 appl_data = wpabuf_alloc(max_len + 100);
3101 if (appl_data == NULL)
3104 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
3105 wpabuf_size(appl_data));
3107 int err = SSL_get_error(conn->ssl, res);
3108 if (err == SSL_ERROR_WANT_READ ||
3109 err == SSL_ERROR_WANT_WRITE) {
3110 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
3113 tls_show_errors(MSG_INFO, __func__,
3114 "Failed to read possible "
3115 "Application Data");
3117 wpabuf_free(appl_data);
3121 wpabuf_put(appl_data, res);
3122 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
3123 "message", appl_data);
3129 static struct wpabuf *
3130 openssl_connection_handshake(struct tls_connection *conn,
3131 const struct wpabuf *in_data,
3132 struct wpabuf **appl_data, int server)
3134 struct wpabuf *out_data;
3139 out_data = openssl_handshake(conn, in_data, server);
3140 if (out_data == NULL)
3142 if (conn->invalid_hb_used) {
3143 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3144 wpabuf_free(out_data);
3148 if (SSL_is_init_finished(conn->ssl)) {
3149 wpa_printf(MSG_DEBUG,
3150 "OpenSSL: Handshake finished - resumed=%d",
3151 tls_connection_resumed(conn->ssl_ctx, conn));
3152 if (appl_data && in_data)
3153 *appl_data = openssl_get_appl_data(conn,
3154 wpabuf_len(in_data));
3157 if (conn->invalid_hb_used) {
3158 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3160 wpabuf_free(*appl_data);
3163 wpabuf_free(out_data);
3172 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
3173 const struct wpabuf *in_data,
3174 struct wpabuf **appl_data)
3176 return openssl_connection_handshake(conn, in_data, appl_data, 0);
3180 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
3181 struct tls_connection *conn,
3182 const struct wpabuf *in_data,
3183 struct wpabuf **appl_data)
3185 return openssl_connection_handshake(conn, in_data, appl_data, 1);
3189 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
3190 struct tls_connection *conn,
3191 const struct wpabuf *in_data)
3199 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3200 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
3201 (res = BIO_reset(conn->ssl_out)) < 0) {
3202 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3205 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
3207 tls_show_errors(MSG_INFO, __func__,
3208 "Encryption failed - SSL_write");
3212 /* Read encrypted data to be sent to the server */
3213 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
3216 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
3218 tls_show_errors(MSG_INFO, __func__,
3219 "Encryption failed - BIO_read");
3223 wpabuf_put(buf, res);
3229 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3230 struct tls_connection *conn,
3231 const struct wpabuf *in_data)
3236 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3237 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3238 wpabuf_len(in_data));
3240 tls_show_errors(MSG_INFO, __func__,
3241 "Decryption failed - BIO_write");
3244 if (BIO_reset(conn->ssl_out) < 0) {
3245 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3249 /* Read decrypted data for further processing */
3251 * Even though we try to disable TLS compression, it is possible that
3252 * this cannot be done with all TLS libraries. Add extra buffer space
3253 * to handle the possibility of the decrypted data being longer than
3256 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3259 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3261 tls_show_errors(MSG_INFO, __func__,
3262 "Decryption failed - SSL_read");
3266 wpabuf_put(buf, res);
3268 if (conn->invalid_hb_used) {
3269 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3278 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3280 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3281 return conn ? SSL_cache_hit(conn->ssl) : 0;
3283 return conn ? conn->ssl->hit : 0;
3288 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3291 char buf[100], *pos, *end;
3295 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3300 end = pos + sizeof(buf);
3303 while (*c != TLS_CIPHER_NONE) {
3307 case TLS_CIPHER_RC4_SHA:
3310 case TLS_CIPHER_AES128_SHA:
3311 suite = "AES128-SHA";
3313 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3314 suite = "DHE-RSA-AES128-SHA";
3316 case TLS_CIPHER_ANON_DH_AES128_SHA:
3317 suite = "ADH-AES128-SHA";
3320 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3321 "cipher selection: %d", *c);
3324 ret = os_snprintf(pos, end - pos, ":%s", suite);
3325 if (os_snprintf_error(end - pos, ret))
3332 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3334 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3335 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3336 if (os_strstr(buf, ":ADH-")) {
3338 * Need to drop to security level 0 to allow anonymous
3339 * cipher suites for EAP-FAST.
3341 SSL_set_security_level(conn->ssl, 0);
3342 } else if (SSL_get_security_level(conn->ssl) == 0) {
3343 /* Force at least security level 1 */
3344 SSL_set_security_level(conn->ssl, 1);
3346 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3349 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3350 tls_show_errors(MSG_INFO, __func__,
3351 "Cipher suite configuration failed");
3359 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
3360 char *buf, size_t buflen)
3363 if (conn == NULL || conn->ssl == NULL)
3366 name = SSL_get_version(conn->ssl);
3370 os_strlcpy(buf, name, buflen);
3375 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3376 char *buf, size_t buflen)
3379 if (conn == NULL || conn->ssl == NULL)
3382 name = SSL_get_cipher(conn->ssl);
3386 os_strlcpy(buf, name, buflen);
3391 int tls_connection_enable_workaround(void *ssl_ctx,
3392 struct tls_connection *conn)
3394 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3400 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3401 /* ClientHello TLS extensions require a patch to openssl, so this function is
3402 * commented out unless explicitly needed for EAP-FAST in order to be able to
3403 * build this file with unmodified openssl. */
3404 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3405 int ext_type, const u8 *data,
3408 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3411 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3417 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3420 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3424 return conn->failed;
3428 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3432 return conn->read_alerts;
3436 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3440 return conn->write_alerts;
3446 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3448 #ifndef CONFIG_NO_STDOUT_DEBUG
3454 if (wpa_debug_level > MSG_DEBUG)
3457 out = BIO_new(BIO_s_mem());
3461 OCSP_RESPONSE_print(out, rsp, 0);
3462 rlen = BIO_ctrl_pending(out);
3463 txt = os_malloc(rlen + 1);
3469 res = BIO_read(out, txt, rlen);
3472 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3476 #endif /* CONFIG_NO_STDOUT_DEBUG */
3480 static void debug_print_cert(X509 *cert, const char *title)
3482 #ifndef CONFIG_NO_STDOUT_DEBUG
3488 if (wpa_debug_level > MSG_DEBUG)
3491 out = BIO_new(BIO_s_mem());
3495 X509_print(out, cert);
3496 rlen = BIO_ctrl_pending(out);
3497 txt = os_malloc(rlen + 1);
3503 res = BIO_read(out, txt, rlen);
3506 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3511 #endif /* CONFIG_NO_STDOUT_DEBUG */
3515 static int ocsp_resp_cb(SSL *s, void *arg)
3517 struct tls_connection *conn = arg;
3518 const unsigned char *p;
3519 int len, status, reason;
3521 OCSP_BASICRESP *basic;
3523 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3525 STACK_OF(X509) *certs = NULL;
3527 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3529 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3530 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3533 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3535 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3537 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3541 ocsp_debug_print_resp(rsp);
3543 status = OCSP_response_status(rsp);
3544 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3545 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3546 status, OCSP_response_status_str(status));
3550 basic = OCSP_response_get1_basic(rsp);
3552 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3556 store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3557 if (conn->peer_issuer) {
3558 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3560 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3561 tls_show_errors(MSG_INFO, __func__,
3562 "OpenSSL: Could not add issuer to certificate store");
3564 certs = sk_X509_new_null();
3567 cert = X509_dup(conn->peer_issuer);
3568 if (cert && !sk_X509_push(certs, cert)) {
3571 "OpenSSL: Could not add issuer to OCSP responder trust store");
3573 sk_X509_free(certs);
3576 if (certs && conn->peer_issuer_issuer) {
3577 cert = X509_dup(conn->peer_issuer_issuer);
3578 if (cert && !sk_X509_push(certs, cert)) {
3581 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3588 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3589 sk_X509_pop_free(certs, X509_free);
3591 tls_show_errors(MSG_INFO, __func__,
3592 "OpenSSL: OCSP response failed verification");
3593 OCSP_BASICRESP_free(basic);
3594 OCSP_RESPONSE_free(rsp);
3598 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3600 if (!conn->peer_cert) {
3601 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3602 OCSP_BASICRESP_free(basic);
3603 OCSP_RESPONSE_free(rsp);
3607 if (!conn->peer_issuer) {
3608 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3609 OCSP_BASICRESP_free(basic);
3610 OCSP_RESPONSE_free(rsp);
3614 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3616 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3617 OCSP_BASICRESP_free(basic);
3618 OCSP_RESPONSE_free(rsp);
3622 if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3623 &this_update, &next_update)) {
3624 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3625 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3626 " (OCSP not required)");
3627 OCSP_BASICRESP_free(basic);
3628 OCSP_RESPONSE_free(rsp);
3629 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3632 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3633 tls_show_errors(MSG_INFO, __func__,
3634 "OpenSSL: OCSP status times invalid");
3635 OCSP_BASICRESP_free(basic);
3636 OCSP_RESPONSE_free(rsp);
3640 OCSP_BASICRESP_free(basic);
3641 OCSP_RESPONSE_free(rsp);
3643 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3644 OCSP_cert_status_str(status));
3646 if (status == V_OCSP_CERTSTATUS_GOOD)
3648 if (status == V_OCSP_CERTSTATUS_REVOKED)
3650 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3651 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3654 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3659 static int ocsp_status_cb(SSL *s, void *arg)
3665 if (tls_global->ocsp_stapling_response == NULL) {
3666 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3667 return SSL_TLSEXT_ERR_OK;
3670 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3672 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3673 /* TODO: Build OCSPResponse with responseStatus = internalError
3675 return SSL_TLSEXT_ERR_OK;
3677 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3678 tmp = OPENSSL_malloc(len);
3681 return SSL_TLSEXT_ERR_ALERT_FATAL;
3684 os_memcpy(tmp, resp, len);
3686 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3688 return SSL_TLSEXT_ERR_OK;
3691 #endif /* HAVE_OCSP */
3694 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3695 const struct tls_connection_params *params)
3697 struct tls_data *data = tls_ctx;
3701 const char *key_id = params->key_id;
3702 const char *cert_id = params->cert_id;
3703 const char *ca_cert_id = params->ca_cert_id;
3704 const char *engine_id = params->engine ? params->engine_id : NULL;
3710 * If the engine isn't explicitly configured, and any of the
3711 * cert/key fields are actually PKCS#11 URIs, then automatically
3712 * use the PKCS#11 ENGINE.
3714 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3717 if (!key_id && params->private_key && can_pkcs11 &&
3718 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3720 key_id = params->private_key;
3723 if (!cert_id && params->client_cert && can_pkcs11 &&
3724 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3726 cert_id = params->client_cert;
3729 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3730 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3732 ca_cert_id = params->ca_cert;
3735 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3736 if (can_pkcs11 == 2 && !engine_id)
3737 engine_id = "pkcs11";
3739 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3740 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3741 if (params->flags & TLS_CONN_EAP_FAST) {
3742 wpa_printf(MSG_DEBUG,
3743 "OpenSSL: Use TLSv1_method() for EAP-FAST");
3744 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3745 tls_show_errors(MSG_INFO, __func__,
3746 "Failed to set TLSv1_method() for EAP-FAST");
3751 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3753 while ((err = ERR_get_error())) {
3754 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3755 __func__, ERR_error_string(err, NULL));
3759 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3760 ret = tls_engine_init(conn, engine_id, params->pin,
3761 key_id, cert_id, ca_cert_id);
3765 if (tls_connection_set_subject_match(conn,
3766 params->subject_match,
3767 params->altsubject_match,
3768 params->suffix_match,
3769 params->domain_match))
3772 if (engine_id && ca_cert_id) {
3773 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
3774 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3775 } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
3776 params->ca_cert_blob,
3777 params->ca_cert_blob_len,
3781 if (engine_id && cert_id) {
3782 if (tls_connection_engine_client_cert(conn, cert_id))
3783 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3784 } else if (tls_connection_client_cert(conn, params->client_cert,
3785 params->client_cert_blob,
3786 params->client_cert_blob_len))
3789 if (engine_id && key_id) {
3790 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3791 if (tls_connection_engine_private_key(conn))
3792 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3793 } else if (tls_connection_private_key(data, conn,
3794 params->private_key,
3795 params->private_key_passwd,
3796 params->private_key_blob,
3797 params->private_key_blob_len)) {
3798 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3799 params->private_key);
3803 if (tls_connection_dh(conn, params->dh_file)) {
3804 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3809 if (params->openssl_ciphers &&
3810 SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3811 wpa_printf(MSG_INFO,
3812 "OpenSSL: Failed to set cipher string '%s'",
3813 params->openssl_ciphers);
3817 tls_set_conn_flags(conn->ssl, params->flags);
3820 if (params->flags & TLS_CONN_REQUEST_OCSP) {
3821 SSL_CTX *ssl_ctx = data->ssl;
3822 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3823 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3824 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3826 #else /* HAVE_OCSP */
3827 if (params->flags & TLS_CONN_REQUIRE_OCSP) {
3828 wpa_printf(MSG_INFO,
3829 "OpenSSL: No OCSP support included - reject configuration");
3832 if (params->flags & TLS_CONN_REQUEST_OCSP) {
3833 wpa_printf(MSG_DEBUG,
3834 "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
3836 #endif /* HAVE_OCSP */
3838 conn->flags = params->flags;
3840 tls_get_errors(data);
3846 int tls_global_set_params(void *tls_ctx,
3847 const struct tls_connection_params *params)
3849 struct tls_data *data = tls_ctx;
3850 SSL_CTX *ssl_ctx = data->ssl;
3853 while ((err = ERR_get_error())) {
3854 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3855 __func__, ERR_error_string(err, NULL));
3858 if (tls_global_ca_cert(data, params->ca_cert) ||
3859 tls_global_client_cert(data, params->client_cert) ||
3860 tls_global_private_key(data, params->private_key,
3861 params->private_key_passwd) ||
3862 tls_global_dh(data, params->dh_file)) {
3863 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
3867 if (params->openssl_ciphers &&
3868 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3869 wpa_printf(MSG_INFO,
3870 "OpenSSL: Failed to set cipher string '%s'",
3871 params->openssl_ciphers);
3875 #ifdef SSL_OP_NO_TICKET
3876 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3877 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3878 #ifdef SSL_CTX_clear_options
3880 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3881 #endif /* SSL_clear_options */
3882 #endif /* SSL_OP_NO_TICKET */
3885 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3886 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3887 os_free(tls_global->ocsp_stapling_response);
3888 if (params->ocsp_stapling_response)
3889 tls_global->ocsp_stapling_response =
3890 os_strdup(params->ocsp_stapling_response);
3892 tls_global->ocsp_stapling_response = NULL;
3893 #endif /* HAVE_OCSP */
3899 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3900 /* Pre-shared secred requires a patch to openssl, so this function is
3901 * commented out unless explicitly needed for EAP-FAST in order to be able to
3902 * build this file with unmodified openssl. */
3904 #ifdef OPENSSL_IS_BORINGSSL
3905 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3906 STACK_OF(SSL_CIPHER) *peer_ciphers,
3907 const SSL_CIPHER **cipher, void *arg)
3908 #else /* OPENSSL_IS_BORINGSSL */
3909 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3910 STACK_OF(SSL_CIPHER) *peer_ciphers,
3911 SSL_CIPHER **cipher, void *arg)
3912 #endif /* OPENSSL_IS_BORINGSSL */
3914 struct tls_connection *conn = arg;
3917 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3918 if (conn == NULL || conn->session_ticket_cb == NULL)
3921 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3922 conn->session_ticket,
3923 conn->session_ticket_len,
3924 s->s3->client_random,
3925 s->s3->server_random, secret);
3927 unsigned char client_random[SSL3_RANDOM_SIZE];
3928 unsigned char server_random[SSL3_RANDOM_SIZE];
3930 if (conn == NULL || conn->session_ticket_cb == NULL)
3933 SSL_get_client_random(s, client_random, sizeof(client_random));
3934 SSL_get_server_random(s, server_random, sizeof(server_random));
3936 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3937 conn->session_ticket,
3938 conn->session_ticket_len,
3940 server_random, secret);
3943 os_free(conn->session_ticket);
3944 conn->session_ticket = NULL;
3949 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3954 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3957 struct tls_connection *conn = arg;
3959 if (conn == NULL || conn->session_ticket_cb == NULL)
3962 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3964 os_free(conn->session_ticket);
3965 conn->session_ticket = NULL;
3967 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3968 "extension", data, len);
3970 conn->session_ticket = os_malloc(len);
3971 if (conn->session_ticket == NULL)
3974 os_memcpy(conn->session_ticket, data, len);
3975 conn->session_ticket_len = len;
3979 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3982 int tls_connection_set_session_ticket_cb(void *tls_ctx,
3983 struct tls_connection *conn,
3984 tls_session_ticket_cb cb,
3987 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3988 conn->session_ticket_cb = cb;
3989 conn->session_ticket_cb_ctx = ctx;
3992 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3995 SSL_set_session_ticket_ext_cb(conn->ssl,
3996 tls_session_ticket_ext_cb, conn);
3998 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
4000 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
4004 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4006 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4010 int tls_get_library_version(char *buf, size_t buf_len)
4012 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
4013 OPENSSL_VERSION_TEXT,
4014 SSLeay_version(SSLEAY_VERSION));