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 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1949 static int counter = 0;
1955 conn->ca_cert_verify = 1;
1956 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1957 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1958 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1960 conn->ca_cert_verify = 0;
1961 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1964 SSL_set_accept_state(conn->ssl);
1967 * Set session id context in order to avoid fatal errors when client
1968 * tries to resume a session. However, set the context to a unique
1969 * value in order to effectively disable session resumption for now
1970 * since not all areas of the server code are ready for it (e.g.,
1971 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1975 SSL_set_session_id_context(conn->ssl,
1976 (const unsigned char *) &counter,
1983 static int tls_connection_client_cert(struct tls_connection *conn,
1984 const char *client_cert,
1985 const u8 *client_cert_blob,
1986 size_t client_cert_blob_len)
1988 if (client_cert == NULL && client_cert_blob == NULL)
1991 if (client_cert_blob &&
1992 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1993 client_cert_blob_len) == 1) {
1994 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1997 } else if (client_cert_blob) {
1998 tls_show_errors(MSG_DEBUG, __func__,
1999 "SSL_use_certificate_ASN1 failed");
2002 if (client_cert == NULL)
2006 if (os_strncmp("keystore://", client_cert, 11) == 0) {
2007 BIO *bio = BIO_from_keystore(&client_cert[11]);
2011 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2015 if (SSL_use_certificate(conn->ssl, x509) == 1)
2021 #endif /* ANDROID */
2023 #ifndef OPENSSL_NO_STDIO
2024 if (SSL_use_certificate_file(conn->ssl, client_cert,
2025 SSL_FILETYPE_ASN1) == 1) {
2026 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2031 if (SSL_use_certificate_file(conn->ssl, client_cert,
2032 SSL_FILETYPE_PEM) == 1) {
2034 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2039 tls_show_errors(MSG_DEBUG, __func__,
2040 "SSL_use_certificate_file failed");
2041 #else /* OPENSSL_NO_STDIO */
2042 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2043 #endif /* OPENSSL_NO_STDIO */
2049 static int tls_global_client_cert(struct tls_data *data,
2050 const char *client_cert)
2052 #ifndef OPENSSL_NO_STDIO
2053 SSL_CTX *ssl_ctx = data->ssl;
2055 if (client_cert == NULL)
2058 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2059 SSL_FILETYPE_ASN1) != 1 &&
2060 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2061 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2062 SSL_FILETYPE_PEM) != 1) {
2063 tls_show_errors(MSG_INFO, __func__,
2064 "Failed to load client certificate");
2068 #else /* OPENSSL_NO_STDIO */
2069 if (client_cert == NULL)
2071 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2073 #endif /* OPENSSL_NO_STDIO */
2077 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2079 if (password == NULL) {
2082 os_strlcpy(buf, (char *) password, size);
2083 return os_strlen(buf);
2088 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
2093 STACK_OF(X509) *certs;
2102 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2103 tls_show_errors(MSG_DEBUG, __func__,
2104 "Failed to parse PKCS12 file");
2108 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2111 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2113 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2114 "subject='%s'", buf);
2116 if (SSL_use_certificate(ssl, cert) != 1)
2119 if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
2126 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2128 if (SSL_use_PrivateKey(ssl, pkey) != 1)
2131 if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
2134 EVP_PKEY_free(pkey);
2138 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2139 SSL_clear_chain_certs(ssl);
2140 while ((cert = sk_X509_pop(certs)) != NULL) {
2141 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2143 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2144 " from PKCS12: subject='%s'", buf);
2145 if (SSL_add1_chain_cert(ssl, cert) != 1) {
2150 sk_X509_free(certs);
2151 #ifndef OPENSSL_IS_BORINGSSL
2152 res = SSL_build_cert_chain(ssl,
2153 SSL_BUILD_CHAIN_FLAG_CHECK |
2154 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2156 tls_show_errors(MSG_DEBUG, __func__,
2157 "Failed to build certificate chain");
2158 } else if (res == 2) {
2159 wpa_printf(MSG_DEBUG,
2160 "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2162 #endif /* OPENSSL_IS_BORINGSSL */
2164 * Try to continue regardless of result since it is possible for
2165 * the extra certificates not to be required.
2168 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2169 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2170 SSL_CTX_clear_extra_chain_certs(data->ssl);
2171 #endif /* OPENSSL_VERSION_NUMBER >= 0x10001000L */
2172 while ((cert = sk_X509_pop(certs)) != NULL) {
2173 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2175 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2176 " from PKCS12: subject='%s'", buf);
2178 * There is no SSL equivalent for the chain cert - so
2179 * always add it to the context...
2181 if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
2187 sk_X509_free(certs);
2188 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2194 tls_get_errors(data);
2198 #endif /* PKCS12_FUNCS */
2201 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
2202 const char *private_key, const char *passwd)
2208 f = fopen(private_key, "rb");
2212 p12 = d2i_PKCS12_fp(f, NULL);
2216 tls_show_errors(MSG_INFO, __func__,
2217 "Failed to use PKCS#12 file");
2221 return tls_parse_pkcs12(data, ssl, p12, passwd);
2223 #else /* PKCS12_FUNCS */
2224 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2227 #endif /* PKCS12_FUNCS */
2231 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
2232 const u8 *blob, size_t len, const char *passwd)
2237 p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2239 tls_show_errors(MSG_INFO, __func__,
2240 "Failed to use PKCS#12 blob");
2244 return tls_parse_pkcs12(data, ssl, p12, passwd);
2246 #else /* PKCS12_FUNCS */
2247 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2250 #endif /* PKCS12_FUNCS */
2254 #ifndef OPENSSL_NO_ENGINE
2255 static int tls_engine_get_cert(struct tls_connection *conn,
2256 const char *cert_id,
2259 /* this runs after the private key is loaded so no PIN is required */
2261 const char *cert_id;
2264 params.cert_id = cert_id;
2267 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2268 0, ¶ms, NULL, 1)) {
2269 unsigned long err = ERR_get_error();
2271 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2272 " '%s' [%s]", cert_id,
2273 ERR_error_string(err, NULL));
2274 if (tls_is_pin_error(err))
2275 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2276 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2279 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2281 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2283 *cert = params.cert;
2286 #endif /* OPENSSL_NO_ENGINE */
2289 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2290 const char *cert_id)
2292 #ifndef OPENSSL_NO_ENGINE
2295 if (tls_engine_get_cert(conn, cert_id, &cert))
2298 if (!SSL_use_certificate(conn->ssl, cert)) {
2299 tls_show_errors(MSG_ERROR, __func__,
2300 "SSL_use_certificate failed");
2305 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2309 #else /* OPENSSL_NO_ENGINE */
2311 #endif /* OPENSSL_NO_ENGINE */
2315 static int tls_connection_engine_ca_cert(struct tls_data *data,
2316 struct tls_connection *conn,
2317 const char *ca_cert_id)
2319 #ifndef OPENSSL_NO_ENGINE
2321 SSL_CTX *ssl_ctx = data->ssl;
2324 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2327 /* start off the same as tls_connection_ca_cert */
2328 store = X509_STORE_new();
2329 if (store == NULL) {
2330 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2331 "certificate store", __func__);
2335 SSL_CTX_set_cert_store(ssl_ctx, store);
2336 if (!X509_STORE_add_cert(store, cert)) {
2337 unsigned long err = ERR_peek_error();
2338 tls_show_errors(MSG_WARNING, __func__,
2339 "Failed to add CA certificate from engine "
2340 "to certificate store");
2341 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2342 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2343 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2344 " already in hash table error",
2352 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2353 "to certificate store", __func__);
2354 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2355 conn->ca_cert_verify = 1;
2359 #else /* OPENSSL_NO_ENGINE */
2361 #endif /* OPENSSL_NO_ENGINE */
2365 static int tls_connection_engine_private_key(struct tls_connection *conn)
2367 #ifndef OPENSSL_NO_ENGINE
2368 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2369 tls_show_errors(MSG_ERROR, __func__,
2370 "ENGINE: cannot use private key for TLS");
2373 if (!SSL_check_private_key(conn->ssl)) {
2374 tls_show_errors(MSG_INFO, __func__,
2375 "Private key failed verification");
2379 #else /* OPENSSL_NO_ENGINE */
2380 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2381 "engine support was not compiled in");
2383 #endif /* OPENSSL_NO_ENGINE */
2387 static int tls_connection_private_key(struct tls_data *data,
2388 struct tls_connection *conn,
2389 const char *private_key,
2390 const char *private_key_passwd,
2391 const u8 *private_key_blob,
2392 size_t private_key_blob_len)
2394 SSL_CTX *ssl_ctx = data->ssl;
2398 if (private_key == NULL && private_key_blob == NULL)
2401 if (private_key_passwd) {
2402 passwd = os_strdup(private_key_passwd);
2408 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2409 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2412 while (private_key_blob) {
2413 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2414 (u8 *) private_key_blob,
2415 private_key_blob_len) == 1) {
2416 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2417 "ASN1(EVP_PKEY_RSA) --> OK");
2422 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2423 (u8 *) private_key_blob,
2424 private_key_blob_len) == 1) {
2425 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2426 "ASN1(EVP_PKEY_DSA) --> OK");
2431 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2432 (u8 *) private_key_blob,
2433 private_key_blob_len) == 1) {
2434 wpa_printf(MSG_DEBUG, "OpenSSL: "
2435 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2440 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
2441 private_key_blob_len, passwd) == 0) {
2442 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2451 while (!ok && private_key) {
2452 #ifndef OPENSSL_NO_STDIO
2453 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2454 SSL_FILETYPE_ASN1) == 1) {
2455 wpa_printf(MSG_DEBUG, "OpenSSL: "
2456 "SSL_use_PrivateKey_File (DER) --> OK");
2461 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2462 SSL_FILETYPE_PEM) == 1) {
2463 wpa_printf(MSG_DEBUG, "OpenSSL: "
2464 "SSL_use_PrivateKey_File (PEM) --> OK");
2468 #else /* OPENSSL_NO_STDIO */
2469 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2471 #endif /* OPENSSL_NO_STDIO */
2473 if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
2475 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2481 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2482 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2483 "access certificate store --> OK");
2492 tls_show_errors(MSG_INFO, __func__,
2493 "Failed to load private key");
2498 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2501 if (!SSL_check_private_key(conn->ssl)) {
2502 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2507 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2512 static int tls_global_private_key(struct tls_data *data,
2513 const char *private_key,
2514 const char *private_key_passwd)
2516 SSL_CTX *ssl_ctx = data->ssl;
2519 if (private_key == NULL)
2522 if (private_key_passwd) {
2523 passwd = os_strdup(private_key_passwd);
2529 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2530 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2532 #ifndef OPENSSL_NO_STDIO
2533 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2534 SSL_FILETYPE_ASN1) != 1 &&
2535 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2536 SSL_FILETYPE_PEM) != 1 &&
2537 #endif /* OPENSSL_NO_STDIO */
2538 tls_read_pkcs12(data, NULL, private_key, passwd)) {
2539 tls_show_errors(MSG_INFO, __func__,
2540 "Failed to load private key");
2547 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2549 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2550 tls_show_errors(MSG_INFO, __func__,
2551 "Private key failed verification");
2559 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2561 #ifdef OPENSSL_NO_DH
2562 if (dh_file == NULL)
2564 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2565 "dh_file specified");
2567 #else /* OPENSSL_NO_DH */
2571 /* TODO: add support for dh_blob */
2572 if (dh_file == NULL)
2577 bio = BIO_new_file(dh_file, "r");
2579 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2580 dh_file, ERR_error_string(ERR_get_error(), NULL));
2583 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2585 #ifndef OPENSSL_NO_DSA
2586 while (dh == NULL) {
2588 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2589 " trying to parse as DSA params", dh_file,
2590 ERR_error_string(ERR_get_error(), NULL));
2591 bio = BIO_new_file(dh_file, "r");
2594 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2597 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2598 "'%s': %s", dh_file,
2599 ERR_error_string(ERR_get_error(), NULL));
2603 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2604 dh = DSA_dup_DH(dsa);
2607 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2608 "params into DH params");
2613 #endif /* !OPENSSL_NO_DSA */
2615 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2620 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2621 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2623 ERR_error_string(ERR_get_error(), NULL));
2629 #endif /* OPENSSL_NO_DH */
2633 static int tls_global_dh(struct tls_data *data, const char *dh_file)
2635 #ifdef OPENSSL_NO_DH
2636 if (dh_file == NULL)
2638 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2639 "dh_file specified");
2641 #else /* OPENSSL_NO_DH */
2642 SSL_CTX *ssl_ctx = data->ssl;
2646 /* TODO: add support for dh_blob */
2647 if (dh_file == NULL)
2649 if (ssl_ctx == NULL)
2652 bio = BIO_new_file(dh_file, "r");
2654 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2655 dh_file, ERR_error_string(ERR_get_error(), NULL));
2658 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2660 #ifndef OPENSSL_NO_DSA
2661 while (dh == NULL) {
2663 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2664 " trying to parse as DSA params", dh_file,
2665 ERR_error_string(ERR_get_error(), NULL));
2666 bio = BIO_new_file(dh_file, "r");
2669 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2672 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2673 "'%s': %s", dh_file,
2674 ERR_error_string(ERR_get_error(), NULL));
2678 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2679 dh = DSA_dup_DH(dsa);
2682 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2683 "params into DH params");
2688 #endif /* !OPENSSL_NO_DSA */
2690 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2695 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2696 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2698 ERR_error_string(ERR_get_error(), NULL));
2704 #endif /* OPENSSL_NO_DH */
2708 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
2709 struct tls_random *keys)
2713 if (conn == NULL || keys == NULL)
2716 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2717 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2720 os_memset(keys, 0, sizeof(*keys));
2721 keys->client_random = ssl->s3->client_random;
2722 keys->client_random_len = SSL3_RANDOM_SIZE;
2723 keys->server_random = ssl->s3->server_random;
2724 keys->server_random_len = SSL3_RANDOM_SIZE;
2729 os_memset(keys, 0, sizeof(*keys));
2730 keys->client_random = conn->client_random;
2731 keys->client_random_len = SSL_get_client_random(
2732 ssl, conn->client_random, sizeof(conn->client_random));
2733 keys->server_random = conn->server_random;
2734 keys->server_random_len = SSL_get_server_random(
2735 ssl, conn->server_random, sizeof(conn->server_random));
2743 static int openssl_get_keyblock_size(SSL *ssl)
2745 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2746 const EVP_CIPHER *c;
2750 if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2751 ssl->read_hash == NULL)
2754 c = ssl->enc_read_ctx->cipher;
2755 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2756 h = EVP_MD_CTX_md(ssl->read_hash);
2761 md_size = EVP_MD_size(h);
2762 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2764 md_size = ssl->s3->tmp.new_mac_secret_size;
2769 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2770 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2771 EVP_CIPHER_iv_length(c));
2772 return 2 * (EVP_CIPHER_key_length(c) +
2774 EVP_CIPHER_iv_length(c));
2776 const SSL_CIPHER *ssl_cipher;
2778 const EVP_CIPHER *c;
2781 ssl_cipher = SSL_get_current_cipher(ssl);
2784 cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
2785 digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
2786 wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
2788 if (cipher < 0 || digest < 0)
2790 c = EVP_get_cipherbynid(cipher);
2791 h = EVP_get_digestbynid(digest);
2795 wpa_printf(MSG_DEBUG,
2796 "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
2797 EVP_CIPHER_key_length(c), EVP_MD_size(h),
2798 EVP_CIPHER_iv_length(c));
2799 return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
2800 EVP_CIPHER_iv_length(c));
2803 #endif /* CONFIG_FIPS */
2806 static int openssl_tls_prf(struct tls_connection *conn,
2807 const char *label, int server_random_first,
2808 int skip_keyblock, u8 *out, size_t out_len)
2811 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2814 #else /* CONFIG_FIPS */
2815 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2825 * TLS library did not support key generation, so get the needed TLS
2826 * session parameters and use an internal implementation of TLS PRF to
2833 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2834 ssl->session->master_key_length <= 0)
2836 ver = SSL_get_version(ssl);
2838 if (skip_keyblock) {
2839 skip = openssl_get_keyblock_size(ssl);
2842 tmp_out = os_malloc(skip + out_len);
2848 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2854 if (server_random_first) {
2855 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2856 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2859 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2860 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2864 if (os_strcmp(ver, "TLSv1.2") == 0) {
2865 tls_prf_sha256(ssl->session->master_key,
2866 ssl->session->master_key_length,
2867 label, rnd, 2 * SSL3_RANDOM_SIZE,
2868 _out, skip + out_len);
2870 } else if (tls_prf_sha1_md5(ssl->session->master_key,
2871 ssl->session->master_key_length,
2872 label, rnd, 2 * SSL3_RANDOM_SIZE,
2873 _out, skip + out_len) == 0) {
2877 if (ret == 0 && skip_keyblock)
2878 os_memcpy(out, _out + skip, out_len);
2879 bin_clear_free(tmp_out, skip);
2890 unsigned char client_random[SSL3_RANDOM_SIZE];
2891 unsigned char server_random[SSL3_RANDOM_SIZE];
2892 unsigned char master_key[64];
2893 size_t master_key_len;
2897 * TLS library did not support key generation, so get the needed TLS
2898 * session parameters and use an internal implementation of TLS PRF to
2907 ver = SSL_get_version(ssl);
2908 sess = SSL_get_session(ssl);
2912 if (skip_keyblock) {
2913 skip = openssl_get_keyblock_size(ssl);
2916 tmp_out = os_malloc(skip + out_len);
2922 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2928 SSL_get_client_random(ssl, client_random, sizeof(client_random));
2929 SSL_get_server_random(ssl, server_random, sizeof(server_random));
2930 master_key_len = SSL_SESSION_get_master_key(sess, master_key,
2931 sizeof(master_key));
2933 if (server_random_first) {
2934 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
2935 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random,
2938 os_memcpy(rnd, client_random, SSL3_RANDOM_SIZE);
2939 os_memcpy(rnd + SSL3_RANDOM_SIZE, server_random,
2943 if (os_strcmp(ver, "TLSv1.2") == 0) {
2944 tls_prf_sha256(master_key, master_key_len,
2945 label, rnd, 2 * SSL3_RANDOM_SIZE,
2946 _out, skip + out_len);
2948 } else if (tls_prf_sha1_md5(master_key, master_key_len,
2949 label, rnd, 2 * SSL3_RANDOM_SIZE,
2950 _out, skip + out_len) == 0) {
2953 os_memset(master_key, 0, sizeof(master_key));
2955 if (ret == 0 && skip_keyblock)
2956 os_memcpy(out, _out + skip, out_len);
2957 bin_clear_free(tmp_out, skip);
2961 #endif /* CONFIG_FIPS */
2965 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2966 const char *label, int server_random_first,
2967 int skip_keyblock, u8 *out, size_t out_len)
2969 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2973 if (server_random_first || skip_keyblock)
2974 return openssl_tls_prf(conn, label,
2975 server_random_first, skip_keyblock,
2978 if (SSL_export_keying_material(ssl, out, out_len, label,
2979 os_strlen(label), NULL, 0, 0) == 1) {
2980 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2984 return openssl_tls_prf(conn, label, server_random_first,
2985 skip_keyblock, out, out_len);
2989 static struct wpabuf *
2990 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2994 struct wpabuf *out_data;
2997 * Give TLS handshake data from the server (if available) to OpenSSL
3000 if (in_data && wpabuf_len(in_data) > 0 &&
3001 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
3003 tls_show_errors(MSG_INFO, __func__,
3004 "Handshake failed - BIO_write");
3008 /* Initiate TLS handshake or continue the existing handshake */
3010 res = SSL_accept(conn->ssl);
3012 res = SSL_connect(conn->ssl);
3014 int err = SSL_get_error(conn->ssl, res);
3015 if (err == SSL_ERROR_WANT_READ)
3016 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
3018 else if (err == SSL_ERROR_WANT_WRITE)
3019 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
3022 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
3027 /* Get the TLS handshake data to be sent to the server */
3028 res = BIO_ctrl_pending(conn->ssl_out);
3029 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
3030 out_data = wpabuf_alloc(res);
3031 if (out_data == NULL) {
3032 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
3033 "handshake output (%d bytes)", res);
3034 if (BIO_reset(conn->ssl_out) < 0) {
3035 tls_show_errors(MSG_INFO, __func__,
3036 "BIO_reset failed");
3040 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
3043 tls_show_errors(MSG_INFO, __func__,
3044 "Handshake failed - BIO_read");
3045 if (BIO_reset(conn->ssl_out) < 0) {
3046 tls_show_errors(MSG_INFO, __func__,
3047 "BIO_reset failed");
3049 wpabuf_free(out_data);
3052 wpabuf_put(out_data, res);
3058 static struct wpabuf *
3059 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
3061 struct wpabuf *appl_data;
3064 appl_data = wpabuf_alloc(max_len + 100);
3065 if (appl_data == NULL)
3068 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
3069 wpabuf_size(appl_data));
3071 int err = SSL_get_error(conn->ssl, res);
3072 if (err == SSL_ERROR_WANT_READ ||
3073 err == SSL_ERROR_WANT_WRITE) {
3074 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
3077 tls_show_errors(MSG_INFO, __func__,
3078 "Failed to read possible "
3079 "Application Data");
3081 wpabuf_free(appl_data);
3085 wpabuf_put(appl_data, res);
3086 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
3087 "message", appl_data);
3093 static struct wpabuf *
3094 openssl_connection_handshake(struct tls_connection *conn,
3095 const struct wpabuf *in_data,
3096 struct wpabuf **appl_data, int server)
3098 struct wpabuf *out_data;
3103 out_data = openssl_handshake(conn, in_data, server);
3104 if (out_data == NULL)
3106 if (conn->invalid_hb_used) {
3107 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3108 wpabuf_free(out_data);
3112 if (SSL_is_init_finished(conn->ssl)) {
3113 wpa_printf(MSG_DEBUG,
3114 "OpenSSL: Handshake finished - resumed=%d",
3115 tls_connection_resumed(conn->ssl_ctx, conn));
3116 if (appl_data && in_data)
3117 *appl_data = openssl_get_appl_data(conn,
3118 wpabuf_len(in_data));
3121 if (conn->invalid_hb_used) {
3122 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3124 wpabuf_free(*appl_data);
3127 wpabuf_free(out_data);
3136 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
3137 const struct wpabuf *in_data,
3138 struct wpabuf **appl_data)
3140 return openssl_connection_handshake(conn, in_data, appl_data, 0);
3144 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
3145 struct tls_connection *conn,
3146 const struct wpabuf *in_data,
3147 struct wpabuf **appl_data)
3149 return openssl_connection_handshake(conn, in_data, appl_data, 1);
3153 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
3154 struct tls_connection *conn,
3155 const struct wpabuf *in_data)
3163 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3164 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
3165 (res = BIO_reset(conn->ssl_out)) < 0) {
3166 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3169 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
3171 tls_show_errors(MSG_INFO, __func__,
3172 "Encryption failed - SSL_write");
3176 /* Read encrypted data to be sent to the server */
3177 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
3180 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
3182 tls_show_errors(MSG_INFO, __func__,
3183 "Encryption failed - BIO_read");
3187 wpabuf_put(buf, res);
3193 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3194 struct tls_connection *conn,
3195 const struct wpabuf *in_data)
3200 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3201 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3202 wpabuf_len(in_data));
3204 tls_show_errors(MSG_INFO, __func__,
3205 "Decryption failed - BIO_write");
3208 if (BIO_reset(conn->ssl_out) < 0) {
3209 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3213 /* Read decrypted data for further processing */
3215 * Even though we try to disable TLS compression, it is possible that
3216 * this cannot be done with all TLS libraries. Add extra buffer space
3217 * to handle the possibility of the decrypted data being longer than
3220 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3223 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3225 tls_show_errors(MSG_INFO, __func__,
3226 "Decryption failed - SSL_read");
3230 wpabuf_put(buf, res);
3232 if (conn->invalid_hb_used) {
3233 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3242 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3244 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3245 return conn ? SSL_cache_hit(conn->ssl) : 0;
3247 return conn ? conn->ssl->hit : 0;
3252 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3255 char buf[100], *pos, *end;
3259 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3264 end = pos + sizeof(buf);
3267 while (*c != TLS_CIPHER_NONE) {
3271 case TLS_CIPHER_RC4_SHA:
3274 case TLS_CIPHER_AES128_SHA:
3275 suite = "AES128-SHA";
3277 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3278 suite = "DHE-RSA-AES128-SHA";
3280 case TLS_CIPHER_ANON_DH_AES128_SHA:
3281 suite = "ADH-AES128-SHA";
3284 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3285 "cipher selection: %d", *c);
3288 ret = os_snprintf(pos, end - pos, ":%s", suite);
3289 if (os_snprintf_error(end - pos, ret))
3296 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3298 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3299 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3300 if (os_strstr(buf, ":ADH-")) {
3302 * Need to drop to security level 0 to allow anonymous
3303 * cipher suites for EAP-FAST.
3305 SSL_set_security_level(conn->ssl, 0);
3306 } else if (SSL_get_security_level(conn->ssl) == 0) {
3307 /* Force at least security level 1 */
3308 SSL_set_security_level(conn->ssl, 1);
3310 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3313 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3314 tls_show_errors(MSG_INFO, __func__,
3315 "Cipher suite configuration failed");
3323 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
3324 char *buf, size_t buflen)
3327 if (conn == NULL || conn->ssl == NULL)
3330 name = SSL_get_version(conn->ssl);
3334 os_strlcpy(buf, name, buflen);
3339 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3340 char *buf, size_t buflen)
3343 if (conn == NULL || conn->ssl == NULL)
3346 name = SSL_get_cipher(conn->ssl);
3350 os_strlcpy(buf, name, buflen);
3355 int tls_connection_enable_workaround(void *ssl_ctx,
3356 struct tls_connection *conn)
3358 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3364 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3365 /* ClientHello TLS extensions require a patch to openssl, so this function is
3366 * commented out unless explicitly needed for EAP-FAST in order to be able to
3367 * build this file with unmodified openssl. */
3368 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3369 int ext_type, const u8 *data,
3372 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3375 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3381 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3384 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3388 return conn->failed;
3392 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3396 return conn->read_alerts;
3400 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3404 return conn->write_alerts;
3410 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3412 #ifndef CONFIG_NO_STDOUT_DEBUG
3418 if (wpa_debug_level > MSG_DEBUG)
3421 out = BIO_new(BIO_s_mem());
3425 OCSP_RESPONSE_print(out, rsp, 0);
3426 rlen = BIO_ctrl_pending(out);
3427 txt = os_malloc(rlen + 1);
3433 res = BIO_read(out, txt, rlen);
3436 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3440 #endif /* CONFIG_NO_STDOUT_DEBUG */
3444 static void debug_print_cert(X509 *cert, const char *title)
3446 #ifndef CONFIG_NO_STDOUT_DEBUG
3452 if (wpa_debug_level > MSG_DEBUG)
3455 out = BIO_new(BIO_s_mem());
3459 X509_print(out, cert);
3460 rlen = BIO_ctrl_pending(out);
3461 txt = os_malloc(rlen + 1);
3467 res = BIO_read(out, txt, rlen);
3470 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3475 #endif /* CONFIG_NO_STDOUT_DEBUG */
3479 static int ocsp_resp_cb(SSL *s, void *arg)
3481 struct tls_connection *conn = arg;
3482 const unsigned char *p;
3483 int len, status, reason;
3485 OCSP_BASICRESP *basic;
3487 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3489 STACK_OF(X509) *certs = NULL;
3491 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3493 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3494 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3497 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3499 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3501 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3505 ocsp_debug_print_resp(rsp);
3507 status = OCSP_response_status(rsp);
3508 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3509 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3510 status, OCSP_response_status_str(status));
3514 basic = OCSP_response_get1_basic(rsp);
3516 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3520 store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3521 if (conn->peer_issuer) {
3522 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3524 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3525 tls_show_errors(MSG_INFO, __func__,
3526 "OpenSSL: Could not add issuer to certificate store");
3528 certs = sk_X509_new_null();
3531 cert = X509_dup(conn->peer_issuer);
3532 if (cert && !sk_X509_push(certs, cert)) {
3535 "OpenSSL: Could not add issuer to OCSP responder trust store");
3537 sk_X509_free(certs);
3540 if (certs && conn->peer_issuer_issuer) {
3541 cert = X509_dup(conn->peer_issuer_issuer);
3542 if (cert && !sk_X509_push(certs, cert)) {
3545 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3552 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3553 sk_X509_pop_free(certs, X509_free);
3555 tls_show_errors(MSG_INFO, __func__,
3556 "OpenSSL: OCSP response failed verification");
3557 OCSP_BASICRESP_free(basic);
3558 OCSP_RESPONSE_free(rsp);
3562 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3564 if (!conn->peer_cert) {
3565 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3566 OCSP_BASICRESP_free(basic);
3567 OCSP_RESPONSE_free(rsp);
3571 if (!conn->peer_issuer) {
3572 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3573 OCSP_BASICRESP_free(basic);
3574 OCSP_RESPONSE_free(rsp);
3578 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3580 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3581 OCSP_BASICRESP_free(basic);
3582 OCSP_RESPONSE_free(rsp);
3586 if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3587 &this_update, &next_update)) {
3588 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3589 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3590 " (OCSP not required)");
3591 OCSP_BASICRESP_free(basic);
3592 OCSP_RESPONSE_free(rsp);
3593 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3596 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3597 tls_show_errors(MSG_INFO, __func__,
3598 "OpenSSL: OCSP status times invalid");
3599 OCSP_BASICRESP_free(basic);
3600 OCSP_RESPONSE_free(rsp);
3604 OCSP_BASICRESP_free(basic);
3605 OCSP_RESPONSE_free(rsp);
3607 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3608 OCSP_cert_status_str(status));
3610 if (status == V_OCSP_CERTSTATUS_GOOD)
3612 if (status == V_OCSP_CERTSTATUS_REVOKED)
3614 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3615 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3618 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3623 static int ocsp_status_cb(SSL *s, void *arg)
3629 if (tls_global->ocsp_stapling_response == NULL) {
3630 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3631 return SSL_TLSEXT_ERR_OK;
3634 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3636 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3637 /* TODO: Build OCSPResponse with responseStatus = internalError
3639 return SSL_TLSEXT_ERR_OK;
3641 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3642 tmp = OPENSSL_malloc(len);
3645 return SSL_TLSEXT_ERR_ALERT_FATAL;
3648 os_memcpy(tmp, resp, len);
3650 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3652 return SSL_TLSEXT_ERR_OK;
3655 #endif /* HAVE_OCSP */
3658 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3659 const struct tls_connection_params *params)
3661 struct tls_data *data = tls_ctx;
3665 const char *key_id = params->key_id;
3666 const char *cert_id = params->cert_id;
3667 const char *ca_cert_id = params->ca_cert_id;
3668 const char *engine_id = params->engine ? params->engine_id : NULL;
3674 * If the engine isn't explicitly configured, and any of the
3675 * cert/key fields are actually PKCS#11 URIs, then automatically
3676 * use the PKCS#11 ENGINE.
3678 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3681 if (!key_id && params->private_key && can_pkcs11 &&
3682 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3684 key_id = params->private_key;
3687 if (!cert_id && params->client_cert && can_pkcs11 &&
3688 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3690 cert_id = params->client_cert;
3693 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3694 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3696 ca_cert_id = params->ca_cert;
3699 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3700 if (can_pkcs11 == 2 && !engine_id)
3701 engine_id = "pkcs11";
3703 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3704 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3705 if (params->flags & TLS_CONN_EAP_FAST) {
3706 wpa_printf(MSG_DEBUG,
3707 "OpenSSL: Use TLSv1_method() for EAP-FAST");
3708 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3709 tls_show_errors(MSG_INFO, __func__,
3710 "Failed to set TLSv1_method() for EAP-FAST");
3715 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3717 while ((err = ERR_get_error())) {
3718 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3719 __func__, ERR_error_string(err, NULL));
3723 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3724 ret = tls_engine_init(conn, engine_id, params->pin,
3725 key_id, cert_id, ca_cert_id);
3729 if (tls_connection_set_subject_match(conn,
3730 params->subject_match,
3731 params->altsubject_match,
3732 params->suffix_match,
3733 params->domain_match))
3736 if (engine_id && ca_cert_id) {
3737 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
3738 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3739 } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
3740 params->ca_cert_blob,
3741 params->ca_cert_blob_len,
3745 if (engine_id && cert_id) {
3746 if (tls_connection_engine_client_cert(conn, cert_id))
3747 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3748 } else if (tls_connection_client_cert(conn, params->client_cert,
3749 params->client_cert_blob,
3750 params->client_cert_blob_len))
3753 if (engine_id && key_id) {
3754 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3755 if (tls_connection_engine_private_key(conn))
3756 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3757 } else if (tls_connection_private_key(data, conn,
3758 params->private_key,
3759 params->private_key_passwd,
3760 params->private_key_blob,
3761 params->private_key_blob_len)) {
3762 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3763 params->private_key);
3767 if (tls_connection_dh(conn, params->dh_file)) {
3768 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3773 if (params->openssl_ciphers &&
3774 SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3775 wpa_printf(MSG_INFO,
3776 "OpenSSL: Failed to set cipher string '%s'",
3777 params->openssl_ciphers);
3781 #ifdef SSL_OP_NO_TICKET
3782 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3783 SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
3784 #ifdef SSL_clear_options
3786 SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
3787 #endif /* SSL_clear_options */
3788 #endif /* SSL_OP_NO_TICKET */
3790 #ifdef SSL_OP_NO_TLSv1
3791 if (params->flags & TLS_CONN_DISABLE_TLSv1_0)
3792 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1);
3794 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1);
3795 #endif /* SSL_OP_NO_TLSv1 */
3796 #ifdef SSL_OP_NO_TLSv1_1
3797 if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
3798 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3800 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3801 #endif /* SSL_OP_NO_TLSv1_1 */
3802 #ifdef SSL_OP_NO_TLSv1_2
3803 if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
3804 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3806 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3807 #endif /* SSL_OP_NO_TLSv1_2 */
3810 if (params->flags & TLS_CONN_REQUEST_OCSP) {
3811 SSL_CTX *ssl_ctx = data->ssl;
3812 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3813 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3814 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3816 #else /* HAVE_OCSP */
3817 if (params->flags & TLS_CONN_REQUIRE_OCSP) {
3818 wpa_printf(MSG_INFO,
3819 "OpenSSL: No OCSP support included - reject configuration");
3822 if (params->flags & TLS_CONN_REQUEST_OCSP) {
3823 wpa_printf(MSG_DEBUG,
3824 "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
3826 #endif /* HAVE_OCSP */
3828 conn->flags = params->flags;
3830 tls_get_errors(data);
3836 int tls_global_set_params(void *tls_ctx,
3837 const struct tls_connection_params *params)
3839 struct tls_data *data = tls_ctx;
3840 SSL_CTX *ssl_ctx = data->ssl;
3843 while ((err = ERR_get_error())) {
3844 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3845 __func__, ERR_error_string(err, NULL));
3848 if (tls_global_ca_cert(data, params->ca_cert) ||
3849 tls_global_client_cert(data, params->client_cert) ||
3850 tls_global_private_key(data, params->private_key,
3851 params->private_key_passwd) ||
3852 tls_global_dh(data, params->dh_file)) {
3853 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
3857 if (params->openssl_ciphers &&
3858 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3859 wpa_printf(MSG_INFO,
3860 "OpenSSL: Failed to set cipher string '%s'",
3861 params->openssl_ciphers);
3865 #ifdef SSL_OP_NO_TICKET
3866 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3867 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3868 #ifdef SSL_CTX_clear_options
3870 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3871 #endif /* SSL_clear_options */
3872 #endif /* SSL_OP_NO_TICKET */
3875 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3876 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3877 os_free(tls_global->ocsp_stapling_response);
3878 if (params->ocsp_stapling_response)
3879 tls_global->ocsp_stapling_response =
3880 os_strdup(params->ocsp_stapling_response);
3882 tls_global->ocsp_stapling_response = NULL;
3883 #endif /* HAVE_OCSP */
3889 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3890 /* Pre-shared secred requires a patch to openssl, so this function is
3891 * commented out unless explicitly needed for EAP-FAST in order to be able to
3892 * build this file with unmodified openssl. */
3894 #ifdef OPENSSL_IS_BORINGSSL
3895 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3896 STACK_OF(SSL_CIPHER) *peer_ciphers,
3897 const SSL_CIPHER **cipher, void *arg)
3898 #else /* OPENSSL_IS_BORINGSSL */
3899 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3900 STACK_OF(SSL_CIPHER) *peer_ciphers,
3901 SSL_CIPHER **cipher, void *arg)
3902 #endif /* OPENSSL_IS_BORINGSSL */
3904 struct tls_connection *conn = arg;
3907 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3908 if (conn == NULL || conn->session_ticket_cb == NULL)
3911 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3912 conn->session_ticket,
3913 conn->session_ticket_len,
3914 s->s3->client_random,
3915 s->s3->server_random, secret);
3917 unsigned char client_random[SSL3_RANDOM_SIZE];
3918 unsigned char server_random[SSL3_RANDOM_SIZE];
3920 if (conn == NULL || conn->session_ticket_cb == NULL)
3923 SSL_get_client_random(s, client_random, sizeof(client_random));
3924 SSL_get_server_random(s, server_random, sizeof(server_random));
3926 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3927 conn->session_ticket,
3928 conn->session_ticket_len,
3930 server_random, secret);
3933 os_free(conn->session_ticket);
3934 conn->session_ticket = NULL;
3939 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3944 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3947 struct tls_connection *conn = arg;
3949 if (conn == NULL || conn->session_ticket_cb == NULL)
3952 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3954 os_free(conn->session_ticket);
3955 conn->session_ticket = NULL;
3957 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3958 "extension", data, len);
3960 conn->session_ticket = os_malloc(len);
3961 if (conn->session_ticket == NULL)
3964 os_memcpy(conn->session_ticket, data, len);
3965 conn->session_ticket_len = len;
3969 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3972 int tls_connection_set_session_ticket_cb(void *tls_ctx,
3973 struct tls_connection *conn,
3974 tls_session_ticket_cb cb,
3977 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3978 conn->session_ticket_cb = cb;
3979 conn->session_ticket_cb_ctx = ctx;
3982 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3985 SSL_set_session_ticket_ext_cb(conn->ssl,
3986 tls_session_ticket_ext_cb, conn);
3988 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3990 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3994 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3996 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4000 int tls_get_library_version(char *buf, size_t buf_len)
4002 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
4003 OPENSSL_VERSION_TEXT,
4004 SSLeay_version(SSLEAY_VERSION));