2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2013, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
11 #ifndef CONFIG_SMARTCARD
12 #ifndef OPENSSL_NO_ENGINE
14 #define OPENSSL_NO_ENGINE
19 #include <openssl/ssl.h>
20 #include <openssl/err.h>
21 #include <openssl/pkcs12.h>
22 #include <openssl/x509v3.h>
23 #ifndef OPENSSL_NO_ENGINE
24 #include <openssl/engine.h>
25 #endif /* OPENSSL_NO_ENGINE */
32 #if OPENSSL_VERSION_NUMBER < 0x10000000L
33 /* ERR_remove_thread_state replaces ERR_remove_state and the latter is
34 * deprecated. However, OpenSSL 0.9.8 doesn't include
35 * ERR_remove_thread_state. */
36 #define ERR_remove_thread_state(tid) ERR_remove_state(0)
39 #if defined(OPENSSL_IS_BORINGSSL)
40 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
41 typedef size_t stack_index_t;
43 typedef int stack_index_t;
46 #ifdef SSL_set_tlsext_status_type
47 #ifndef OPENSSL_NO_TLSEXT
49 #include <openssl/ocsp.h>
50 #endif /* OPENSSL_NO_TLSEXT */
51 #endif /* SSL_set_tlsext_status_type */
54 #include <openssl/pem.h>
55 #include <keystore/keystore_get.h>
57 static BIO * BIO_from_keystore(const char *key)
60 uint8_t *value = NULL;
61 int length = keystore_get(key, strlen(key), &value);
62 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
63 BIO_write(bio, value, length);
69 static int tls_openssl_ref_count = 0;
72 void (*event_cb)(void *ctx, enum tls_event ev,
73 union tls_event_data *data);
76 char *ocsp_stapling_response;
79 static struct tls_context *tls_global = NULL;
82 struct tls_connection {
83 struct tls_context *context;
86 BIO *ssl_in, *ssl_out;
87 #ifndef OPENSSL_NO_ENGINE
88 ENGINE *engine; /* functional reference to the engine */
89 EVP_PKEY *private_key; /* the private key if using engine */
90 #endif /* OPENSSL_NO_ENGINE */
91 char *subject_match, *altsubject_match, *suffix_match, *domain_match;
92 int read_alerts, write_alerts, failed;
94 tls_session_ticket_cb session_ticket_cb;
95 void *session_ticket_cb_ctx;
97 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
99 size_t session_ticket_len;
101 unsigned int ca_cert_verify:1;
102 unsigned int cert_probe:1;
103 unsigned int server_cert_only:1;
104 unsigned int invalid_hb_used:1;
106 u8 srv_cert_hash[32];
112 X509 *peer_issuer_issuer;
116 static struct tls_context * tls_context_new(const struct tls_config *conf)
118 struct tls_context *context = os_zalloc(sizeof(*context));
122 context->event_cb = conf->event_cb;
123 context->cb_ctx = conf->cb_ctx;
124 context->cert_in_cb = conf->cert_in_cb;
130 #ifdef CONFIG_NO_STDOUT_DEBUG
132 static void _tls_show_errors(void)
136 while ((err = ERR_get_error())) {
137 /* Just ignore the errors, since stdout is disabled */
140 #define tls_show_errors(l, f, t) _tls_show_errors()
142 #else /* CONFIG_NO_STDOUT_DEBUG */
144 static void tls_show_errors(int level, const char *func, const char *txt)
148 wpa_printf(level, "OpenSSL: %s - %s %s",
149 func, txt, ERR_error_string(ERR_get_error(), NULL));
151 while ((err = ERR_get_error())) {
152 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
153 ERR_error_string(err, NULL));
157 #endif /* CONFIG_NO_STDOUT_DEBUG */
160 #ifdef CONFIG_NATIVE_WINDOWS
162 /* Windows CryptoAPI and access to certificate stores */
163 #include <wincrypt.h>
165 #ifdef __MINGW32_VERSION
167 * MinGW does not yet include all the needed definitions for CryptoAPI, so
168 * define here whatever extra is needed.
170 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
171 #define CERT_STORE_READONLY_FLAG 0x00008000
172 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
174 #endif /* __MINGW32_VERSION */
177 struct cryptoapi_rsa_data {
178 const CERT_CONTEXT *cert;
179 HCRYPTPROV crypt_prov;
181 BOOL free_crypt_prov;
185 static void cryptoapi_error(const char *msg)
187 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
188 msg, (unsigned int) GetLastError());
192 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
193 unsigned char *to, RSA *rsa, int padding)
195 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
200 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
201 unsigned char *to, RSA *rsa, int padding)
203 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
208 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
209 unsigned char *to, RSA *rsa, int padding)
211 struct cryptoapi_rsa_data *priv =
212 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
214 DWORD hash_size, len, i;
215 unsigned char *buf = NULL;
219 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
220 ERR_R_PASSED_NULL_PARAMETER);
224 if (padding != RSA_PKCS1_PADDING) {
225 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
226 RSA_R_UNKNOWN_PADDING_TYPE);
230 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
231 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
233 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
234 RSA_R_INVALID_MESSAGE_LENGTH);
238 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
240 cryptoapi_error("CryptCreateHash failed");
244 len = sizeof(hash_size);
245 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
247 cryptoapi_error("CryptGetHashParam failed");
251 if ((int) hash_size != flen) {
252 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
253 (unsigned) hash_size, flen);
254 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
255 RSA_R_INVALID_MESSAGE_LENGTH);
258 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
259 cryptoapi_error("CryptSetHashParam failed");
264 buf = os_malloc(len);
266 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
270 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
271 cryptoapi_error("CryptSignHash failed");
275 for (i = 0; i < len; i++)
276 to[i] = buf[len - i - 1];
281 CryptDestroyHash(hash);
287 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
288 unsigned char *to, RSA *rsa, int padding)
290 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
295 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
299 if (priv->crypt_prov && priv->free_crypt_prov)
300 CryptReleaseContext(priv->crypt_prov, 0);
302 CertFreeCertificateContext(priv->cert);
307 static int cryptoapi_finish(RSA *rsa)
309 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
310 os_free((void *) rsa->meth);
316 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
319 const CERT_CONTEXT *ret = NULL;
321 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
322 store | CERT_STORE_OPEN_EXISTING_FLAG |
323 CERT_STORE_READONLY_FLAG, L"MY");
325 cryptoapi_error("Failed to open 'My system store'");
329 if (strncmp(name, "cert://", 7) == 0) {
330 unsigned short wbuf[255];
331 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
332 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
334 0, CERT_FIND_SUBJECT_STR,
336 } else if (strncmp(name, "hash://", 7) == 0) {
337 CRYPT_HASH_BLOB blob;
339 const char *hash = name + 7;
342 len = os_strlen(hash) / 2;
343 buf = os_malloc(len);
344 if (buf && hexstr2bin(hash, buf, len) == 0) {
347 ret = CertFindCertificateInStore(cs,
356 CertCloseStore(cs, 0);
362 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
365 RSA *rsa = NULL, *pub_rsa;
366 struct cryptoapi_rsa_data *priv;
367 RSA_METHOD *rsa_meth;
370 (strncmp(name, "cert://", 7) != 0 &&
371 strncmp(name, "hash://", 7) != 0))
374 priv = os_zalloc(sizeof(*priv));
375 rsa_meth = os_zalloc(sizeof(*rsa_meth));
376 if (priv == NULL || rsa_meth == NULL) {
377 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
378 "for CryptoAPI RSA method");
384 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
385 if (priv->cert == NULL) {
386 priv->cert = cryptoapi_find_cert(
387 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
389 if (priv->cert == NULL) {
390 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
395 cert = d2i_X509(NULL,
396 (const unsigned char **) &priv->cert->pbCertEncoded,
397 priv->cert->cbCertEncoded);
399 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
404 if (!CryptAcquireCertificatePrivateKey(priv->cert,
405 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
406 NULL, &priv->crypt_prov,
408 &priv->free_crypt_prov)) {
409 cryptoapi_error("Failed to acquire a private key for the "
414 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
415 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
416 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
417 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
418 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
419 rsa_meth->finish = cryptoapi_finish;
420 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
421 rsa_meth->app_data = (char *) priv;
425 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
426 ERR_R_MALLOC_FAILURE);
430 if (!SSL_use_certificate(ssl, cert)) {
435 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
439 rsa->n = BN_dup(pub_rsa->n);
440 rsa->e = BN_dup(pub_rsa->e);
441 if (!RSA_set_method(rsa, rsa_meth))
444 if (!SSL_use_RSAPrivateKey(ssl, rsa))
457 cryptoapi_free_data(priv);
463 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
466 PCCERT_CONTEXT ctx = NULL;
474 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
479 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
482 wsprintf(wstore, L"%S", store);
483 cs = CertOpenSystemStore(0, wstore);
486 cs = CertOpenSystemStore(0, store);
489 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
490 "'%s': error=%d", __func__, store,
491 (int) GetLastError());
495 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
496 cert = d2i_X509(NULL,
497 (const unsigned char **) &ctx->pbCertEncoded,
500 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
501 "X509 DER encoding for CA cert");
505 X509_NAME_oneline(X509_get_subject_name(cert), buf,
507 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
508 "system certificate store: subject='%s'", buf);
510 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
511 tls_show_errors(MSG_WARNING, __func__,
512 "Failed to add ca_cert to OpenSSL "
513 "certificate store");
519 if (!CertCloseStore(cs, 0)) {
520 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
521 "'%s': error=%d", __func__, name + 13,
522 (int) GetLastError());
529 #else /* CONFIG_NATIVE_WINDOWS */
531 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
536 #endif /* CONFIG_NATIVE_WINDOWS */
539 static void ssl_info_cb(const SSL *ssl, int where, int ret)
544 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
545 w = where & ~SSL_ST_MASK;
546 if (w & SSL_ST_CONNECT)
548 else if (w & SSL_ST_ACCEPT)
553 if (where & SSL_CB_LOOP) {
554 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
555 str, SSL_state_string_long(ssl));
556 } else if (where & SSL_CB_ALERT) {
557 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
558 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
559 where & SSL_CB_READ ?
560 "read (remote end reported an error)" :
561 "write (local SSL3 detected an error)",
562 SSL_alert_type_string_long(ret),
563 SSL_alert_desc_string_long(ret));
564 if ((ret >> 8) == SSL3_AL_FATAL) {
565 if (where & SSL_CB_READ)
568 conn->write_alerts++;
570 if (conn->context->event_cb != NULL) {
571 union tls_event_data ev;
572 struct tls_context *context = conn->context;
573 os_memset(&ev, 0, sizeof(ev));
574 ev.alert.is_local = !(where & SSL_CB_READ);
575 ev.alert.type = SSL_alert_type_string_long(ret);
576 ev.alert.description = SSL_alert_desc_string_long(ret);
577 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
579 } else if (where & SSL_CB_EXIT && ret <= 0) {
580 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
581 str, ret == 0 ? "failed" : "error",
582 SSL_state_string_long(ssl));
587 #ifndef OPENSSL_NO_ENGINE
589 * tls_engine_load_dynamic_generic - load any openssl engine
590 * @pre: an array of commands and values that load an engine initialized
591 * in the engine specific function
592 * @post: an array of commands and values that initialize an already loaded
593 * engine (or %NULL if not required)
594 * @id: the engine id of the engine to load (only required if post is not %NULL
596 * This function is a generic function that loads any openssl engine.
598 * Returns: 0 on success, -1 on failure
600 static int tls_engine_load_dynamic_generic(const char *pre[],
601 const char *post[], const char *id)
604 const char *dynamic_id = "dynamic";
606 engine = ENGINE_by_id(id);
609 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
615 engine = ENGINE_by_id(dynamic_id);
616 if (engine == NULL) {
617 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
619 ERR_error_string(ERR_get_error(), NULL));
623 /* Perform the pre commands. This will load the engine. */
624 while (pre && pre[0]) {
625 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
626 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
627 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
628 "%s %s [%s]", pre[0], pre[1],
629 ERR_error_string(ERR_get_error(), NULL));
637 * Free the reference to the "dynamic" engine. The loaded engine can
638 * now be looked up using ENGINE_by_id().
642 engine = ENGINE_by_id(id);
643 if (engine == NULL) {
644 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
645 id, ERR_error_string(ERR_get_error(), NULL));
649 while (post && post[0]) {
650 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
651 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
652 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
653 " %s %s [%s]", post[0], post[1],
654 ERR_error_string(ERR_get_error(), NULL));
655 ENGINE_remove(engine);
668 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
669 * @pkcs11_so_path: pksc11_so_path from the configuration
670 * @pcks11_module_path: pkcs11_module_path from the configuration
672 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
673 const char *pkcs11_module_path)
675 char *engine_id = "pkcs11";
676 const char *pre_cmd[] = {
677 "SO_PATH", NULL /* pkcs11_so_path */,
678 "ID", NULL /* engine_id */,
680 /* "NO_VCHECK", "1", */
684 const char *post_cmd[] = {
685 "MODULE_PATH", NULL /* pkcs11_module_path */,
692 pre_cmd[1] = pkcs11_so_path;
693 pre_cmd[3] = engine_id;
694 if (pkcs11_module_path)
695 post_cmd[1] = pkcs11_module_path;
699 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
702 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
707 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
708 * @opensc_so_path: opensc_so_path from the configuration
710 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
712 char *engine_id = "opensc";
713 const char *pre_cmd[] = {
714 "SO_PATH", NULL /* opensc_so_path */,
715 "ID", NULL /* engine_id */,
724 pre_cmd[1] = opensc_so_path;
725 pre_cmd[3] = engine_id;
727 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
730 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
732 #endif /* OPENSSL_NO_ENGINE */
735 void * tls_init(const struct tls_config *conf)
738 struct tls_context *context;
741 if (tls_openssl_ref_count == 0) {
742 tls_global = context = tls_context_new(conf);
747 if (conf && conf->fips_mode) {
748 if (!FIPS_mode_set(1)) {
749 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
751 ERR_load_crypto_strings();
752 ERR_print_errors_fp(stderr);
757 wpa_printf(MSG_INFO, "Running in FIPS mode");
759 #else /* OPENSSL_FIPS */
760 if (conf && conf->fips_mode) {
761 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
767 #endif /* OPENSSL_FIPS */
768 #endif /* CONFIG_FIPS */
769 SSL_load_error_strings();
771 #ifndef OPENSSL_NO_SHA256
772 EVP_add_digest(EVP_sha256());
773 #endif /* OPENSSL_NO_SHA256 */
774 /* TODO: if /dev/urandom is available, PRNG is seeded
775 * automatically. If this is not the case, random data should
779 #ifndef OPENSSL_NO_RC2
781 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
782 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
783 * versions, but it looks like OpenSSL 1.0.0 does not do that
786 EVP_add_cipher(EVP_rc2_40_cbc());
787 #endif /* OPENSSL_NO_RC2 */
789 #endif /* PKCS12_FUNCS */
791 context = tls_context_new(conf);
795 tls_openssl_ref_count++;
797 ssl = SSL_CTX_new(SSLv23_method());
799 tls_openssl_ref_count--;
800 if (context != tls_global)
802 if (tls_openssl_ref_count == 0) {
809 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
810 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
812 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
813 SSL_CTX_set_app_data(ssl, context);
815 #ifndef OPENSSL_NO_ENGINE
816 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
817 ERR_load_ENGINE_strings();
818 ENGINE_load_dynamic();
821 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
822 conf->pkcs11_module_path)) {
823 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
824 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
825 conf->pkcs11_module_path)) {
830 #endif /* OPENSSL_NO_ENGINE */
832 if (conf && conf->openssl_ciphers)
833 ciphers = conf->openssl_ciphers;
835 ciphers = "DEFAULT:!EXP:!LOW";
836 if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
837 wpa_printf(MSG_ERROR,
838 "OpenSSL: Failed to set cipher string '%s'",
848 void tls_deinit(void *ssl_ctx)
850 SSL_CTX *ssl = ssl_ctx;
851 struct tls_context *context = SSL_CTX_get_app_data(ssl);
852 if (context != tls_global)
856 tls_openssl_ref_count--;
857 if (tls_openssl_ref_count == 0) {
858 #ifndef OPENSSL_NO_ENGINE
860 #endif /* OPENSSL_NO_ENGINE */
861 CRYPTO_cleanup_all_ex_data();
862 ERR_remove_thread_state(NULL);
865 os_free(tls_global->ocsp_stapling_response);
866 tls_global->ocsp_stapling_response = NULL;
873 #ifndef OPENSSL_NO_ENGINE
875 /* Cryptoki return values */
876 #define CKR_PIN_INCORRECT 0x000000a0
877 #define CKR_PIN_INVALID 0x000000a1
878 #define CKR_PIN_LEN_RANGE 0x000000a2
881 #define ERR_LIB_PKCS11 ERR_LIB_USER
883 static int tls_is_pin_error(unsigned int err)
885 return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
886 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
887 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
888 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
891 #endif /* OPENSSL_NO_ENGINE */
894 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
895 const char *pin, const char *key_id,
896 const char *cert_id, const char *ca_cert_id)
898 #ifndef OPENSSL_NO_ENGINE
900 if (engine_id == NULL) {
901 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
907 ENGINE_load_dynamic();
909 conn->engine = ENGINE_by_id(engine_id);
911 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
912 engine_id, ERR_error_string(ERR_get_error(), NULL));
915 if (ENGINE_init(conn->engine) != 1) {
916 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
917 "(engine: %s) [%s]", engine_id,
918 ERR_error_string(ERR_get_error(), NULL));
921 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
924 if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
925 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
926 ERR_error_string(ERR_get_error(), NULL));
932 * Ensure that the ENGINE does not attempt to use the OpenSSL
933 * UI system to obtain a PIN, if we didn't provide one.
936 const void *password;
937 const char *prompt_info;
938 } key_cb = { "", NULL };
940 /* load private key first in-case PIN is required for cert */
941 conn->private_key = ENGINE_load_private_key(conn->engine,
944 if (!conn->private_key) {
945 unsigned long err = ERR_get_error();
947 wpa_printf(MSG_ERROR,
948 "ENGINE: cannot load private key with id '%s' [%s]",
950 ERR_error_string(err, NULL));
951 if (tls_is_pin_error(err))
952 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
954 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
959 /* handle a certificate and/or CA certificate */
960 if (cert_id || ca_cert_id) {
961 const char *cmd_name = "LOAD_CERT_CTRL";
963 /* test if the engine supports a LOAD_CERT_CTRL */
964 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
965 0, (void *)cmd_name, NULL)) {
966 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
967 " loading certificates");
968 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
977 ENGINE_free(conn->engine);
981 if (conn->private_key) {
982 EVP_PKEY_free(conn->private_key);
983 conn->private_key = NULL;
987 #else /* OPENSSL_NO_ENGINE */
989 #endif /* OPENSSL_NO_ENGINE */
993 static void tls_engine_deinit(struct tls_connection *conn)
995 #ifndef OPENSSL_NO_ENGINE
996 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
997 if (conn->private_key) {
998 EVP_PKEY_free(conn->private_key);
999 conn->private_key = NULL;
1002 ENGINE_finish(conn->engine);
1003 conn->engine = NULL;
1005 #endif /* OPENSSL_NO_ENGINE */
1009 int tls_get_errors(void *ssl_ctx)
1014 while ((err = ERR_get_error())) {
1015 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1016 ERR_error_string(err, NULL));
1024 static void tls_msg_cb(int write_p, int version, int content_type,
1025 const void *buf, size_t len, SSL *ssl, void *arg)
1027 struct tls_connection *conn = arg;
1028 const u8 *pos = buf;
1030 wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
1031 write_p ? "TX" : "RX", version, content_type);
1032 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1033 if (content_type == 24 && len >= 3 && pos[0] == 1) {
1034 size_t payload_len = WPA_GET_BE16(pos + 1);
1035 if (payload_len + 3 > len) {
1036 wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1037 conn->invalid_hb_used = 1;
1043 struct tls_connection * tls_connection_init(void *ssl_ctx)
1045 SSL_CTX *ssl = ssl_ctx;
1046 struct tls_connection *conn;
1048 struct tls_context *context = SSL_CTX_get_app_data(ssl);
1050 conn = os_zalloc(sizeof(*conn));
1053 conn->ssl_ctx = ssl_ctx;
1054 conn->ssl = SSL_new(ssl);
1055 if (conn->ssl == NULL) {
1056 tls_show_errors(MSG_INFO, __func__,
1057 "Failed to initialize new SSL connection");
1062 conn->context = context;
1063 SSL_set_app_data(conn->ssl, conn);
1064 SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1065 SSL_set_msg_callback_arg(conn->ssl, conn);
1066 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1067 SSL_OP_SINGLE_DH_USE;
1068 #ifdef SSL_OP_NO_COMPRESSION
1069 options |= SSL_OP_NO_COMPRESSION;
1070 #endif /* SSL_OP_NO_COMPRESSION */
1071 SSL_set_options(conn->ssl, options);
1073 conn->ssl_in = BIO_new(BIO_s_mem());
1074 if (!conn->ssl_in) {
1075 tls_show_errors(MSG_INFO, __func__,
1076 "Failed to create a new BIO for ssl_in");
1077 SSL_free(conn->ssl);
1082 conn->ssl_out = BIO_new(BIO_s_mem());
1083 if (!conn->ssl_out) {
1084 tls_show_errors(MSG_INFO, __func__,
1085 "Failed to create a new BIO for ssl_out");
1086 SSL_free(conn->ssl);
1087 BIO_free(conn->ssl_in);
1092 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1098 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1102 SSL_free(conn->ssl);
1103 tls_engine_deinit(conn);
1104 os_free(conn->subject_match);
1105 os_free(conn->altsubject_match);
1106 os_free(conn->suffix_match);
1107 os_free(conn->domain_match);
1108 os_free(conn->session_ticket);
1113 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1115 return conn ? SSL_is_init_finished(conn->ssl) : 0;
1119 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1124 /* Shutdown previous TLS connection without notifying the peer
1125 * because the connection was already terminated in practice
1126 * and "close notify" shutdown alert would confuse AS. */
1127 SSL_set_quiet_shutdown(conn->ssl, 1);
1128 SSL_shutdown(conn->ssl);
1133 static int tls_match_altsubject_component(X509 *cert, int type,
1134 const char *value, size_t len)
1141 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1143 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1144 gen = sk_GENERAL_NAME_value(ext, i);
1145 if (gen->type != type)
1147 if (os_strlen((char *) gen->d.ia5->data) == len &&
1148 os_memcmp(value, gen->d.ia5->data, len) == 0)
1156 static int tls_match_altsubject(X509 *cert, const char *match)
1159 const char *pos, *end;
1164 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1167 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1170 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1174 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1178 end = os_strchr(pos, ';');
1180 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1181 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1182 os_strncmp(end + 1, "URI:", 4) == 0)
1184 end = os_strchr(end + 1, ';');
1189 len = os_strlen(pos);
1190 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1199 #ifndef CONFIG_NATIVE_WINDOWS
1200 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1203 size_t i, match_len;
1205 /* Check for embedded nuls that could mess up suffix matching */
1206 for (i = 0; i < len; i++) {
1207 if (val[i] == '\0') {
1208 wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1213 match_len = os_strlen(match);
1214 if (match_len > len || (full && match_len != len))
1217 if (os_strncasecmp((const char *) val + len - match_len, match,
1219 return 0; /* no match */
1221 if (match_len == len)
1222 return 1; /* exact match */
1224 if (val[len - match_len - 1] == '.')
1225 return 1; /* full label match completes suffix match */
1227 wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1230 #endif /* CONFIG_NATIVE_WINDOWS */
1233 static int tls_match_suffix(X509 *cert, const char *match, int full)
1235 #ifdef CONFIG_NATIVE_WINDOWS
1236 /* wincrypt.h has conflicting X509_NAME definition */
1238 #else /* CONFIG_NATIVE_WINDOWS */
1246 wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1247 full ? "": "suffix ", match);
1249 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1251 for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1252 gen = sk_GENERAL_NAME_value(ext, j);
1253 if (gen->type != GEN_DNS)
1256 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1257 gen->d.dNSName->data,
1258 gen->d.dNSName->length);
1259 if (domain_suffix_match(gen->d.dNSName->data,
1260 gen->d.dNSName->length, match, full) ==
1262 wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
1263 full ? "Match" : "Suffix match");
1269 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1273 name = X509_get_subject_name(cert);
1279 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1282 e = X509_NAME_get_entry(name, i);
1285 cn = X509_NAME_ENTRY_get_data(e);
1288 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1289 cn->data, cn->length);
1290 if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
1292 wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
1293 full ? "Match" : "Suffix match");
1298 wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
1299 full ? "": "suffix ");
1301 #endif /* CONFIG_NATIVE_WINDOWS */
1305 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1308 case X509_V_ERR_CERT_REVOKED:
1309 return TLS_FAIL_REVOKED;
1310 case X509_V_ERR_CERT_NOT_YET_VALID:
1311 case X509_V_ERR_CRL_NOT_YET_VALID:
1312 return TLS_FAIL_NOT_YET_VALID;
1313 case X509_V_ERR_CERT_HAS_EXPIRED:
1314 case X509_V_ERR_CRL_HAS_EXPIRED:
1315 return TLS_FAIL_EXPIRED;
1316 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1317 case X509_V_ERR_UNABLE_TO_GET_CRL:
1318 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1319 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1320 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1321 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1322 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1323 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1324 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1325 case X509_V_ERR_INVALID_CA:
1326 return TLS_FAIL_UNTRUSTED;
1327 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1328 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1329 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1330 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1331 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1332 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1333 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1334 case X509_V_ERR_CERT_UNTRUSTED:
1335 case X509_V_ERR_CERT_REJECTED:
1336 return TLS_FAIL_BAD_CERTIFICATE;
1338 return TLS_FAIL_UNSPECIFIED;
1343 static struct wpabuf * get_x509_cert(X509 *cert)
1348 int cert_len = i2d_X509(cert, NULL);
1352 buf = wpabuf_alloc(cert_len);
1356 tmp = wpabuf_put(buf, cert_len);
1357 i2d_X509(cert, &tmp);
1362 static void openssl_tls_fail_event(struct tls_connection *conn,
1363 X509 *err_cert, int err, int depth,
1364 const char *subject, const char *err_str,
1365 enum tls_fail_reason reason)
1367 union tls_event_data ev;
1368 struct wpabuf *cert = NULL;
1369 struct tls_context *context = conn->context;
1371 if (context->event_cb == NULL)
1374 cert = get_x509_cert(err_cert);
1375 os_memset(&ev, 0, sizeof(ev));
1376 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1377 reason : openssl_tls_fail_reason(err);
1378 ev.cert_fail.depth = depth;
1379 ev.cert_fail.subject = subject;
1380 ev.cert_fail.reason_txt = err_str;
1381 ev.cert_fail.cert = cert;
1382 context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1387 static void openssl_tls_cert_event(struct tls_connection *conn,
1388 X509 *err_cert, int depth,
1389 const char *subject)
1391 struct wpabuf *cert = NULL;
1392 union tls_event_data ev;
1393 struct tls_context *context = conn->context;
1394 char *altsubject[TLS_MAX_ALT_SUBJECT];
1395 int alt, num_altsubject = 0;
1399 #ifdef CONFIG_SHA256
1401 #endif /* CONFIG_SHA256 */
1403 if (context->event_cb == NULL)
1406 os_memset(&ev, 0, sizeof(ev));
1407 if (conn->cert_probe || context->cert_in_cb) {
1408 cert = get_x509_cert(err_cert);
1409 ev.peer_cert.cert = cert;
1411 #ifdef CONFIG_SHA256
1415 addr[0] = wpabuf_head(cert);
1416 len[0] = wpabuf_len(cert);
1417 if (sha256_vector(1, addr, len, hash) == 0) {
1418 ev.peer_cert.hash = hash;
1419 ev.peer_cert.hash_len = sizeof(hash);
1422 #endif /* CONFIG_SHA256 */
1423 ev.peer_cert.depth = depth;
1424 ev.peer_cert.subject = subject;
1426 ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1427 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1430 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1432 gen = sk_GENERAL_NAME_value(ext, i);
1433 if (gen->type != GEN_EMAIL &&
1434 gen->type != GEN_DNS &&
1435 gen->type != GEN_URI)
1438 pos = os_malloc(10 + gen->d.ia5->length + 1);
1441 altsubject[num_altsubject++] = pos;
1443 switch (gen->type) {
1445 os_memcpy(pos, "EMAIL:", 6);
1449 os_memcpy(pos, "DNS:", 4);
1453 os_memcpy(pos, "URI:", 4);
1458 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1459 pos += gen->d.ia5->length;
1463 for (alt = 0; alt < num_altsubject; alt++)
1464 ev.peer_cert.altsubject[alt] = altsubject[alt];
1465 ev.peer_cert.num_altsubject = num_altsubject;
1467 context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1469 for (alt = 0; alt < num_altsubject; alt++)
1470 os_free(altsubject[alt]);
1474 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1480 struct tls_connection *conn;
1481 struct tls_context *context;
1482 char *match, *altmatch, *suffix_match, *domain_match;
1483 const char *err_str;
1485 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1489 err = X509_STORE_CTX_get_error(x509_ctx);
1490 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1491 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1492 SSL_get_ex_data_X509_STORE_CTX_idx());
1493 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1495 conn = SSL_get_app_data(ssl);
1500 conn->peer_cert = err_cert;
1501 else if (depth == 1)
1502 conn->peer_issuer = err_cert;
1503 else if (depth == 2)
1504 conn->peer_issuer_issuer = err_cert;
1506 context = conn->context;
1507 match = conn->subject_match;
1508 altmatch = conn->altsubject_match;
1509 suffix_match = conn->suffix_match;
1510 domain_match = conn->domain_match;
1512 if (!preverify_ok && !conn->ca_cert_verify)
1514 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1516 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1517 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1518 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1519 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1524 err_str = X509_verify_cert_error_string(err);
1526 #ifdef CONFIG_SHA256
1528 * Do not require preverify_ok so we can explicity allow otherwise
1529 * invalid pinned server certificates.
1531 if (depth == 0 && conn->server_cert_only) {
1532 struct wpabuf *cert;
1533 cert = get_x509_cert(err_cert);
1535 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1536 "server certificate data");
1542 addr[0] = wpabuf_head(cert);
1543 len[0] = wpabuf_len(cert);
1544 if (sha256_vector(1, addr, len, hash) < 0 ||
1545 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1546 err_str = "Server certificate mismatch";
1547 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1549 } else if (!preverify_ok) {
1551 * Certificate matches pinned certificate, allow
1552 * regardless of other problems.
1554 wpa_printf(MSG_DEBUG,
1555 "OpenSSL: Ignore validation issues for a pinned server certificate");
1561 #endif /* CONFIG_SHA256 */
1563 if (!preverify_ok) {
1564 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1565 " error %d (%s) depth %d for '%s'", err, err_str,
1567 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1568 err_str, TLS_FAIL_UNSPECIFIED);
1569 return preverify_ok;
1572 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1573 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1574 preverify_ok, err, err_str,
1575 conn->ca_cert_verify, depth, buf);
1576 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1577 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1578 "match with '%s'", buf, match);
1580 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1582 TLS_FAIL_SUBJECT_MISMATCH);
1583 } else if (depth == 0 && altmatch &&
1584 !tls_match_altsubject(err_cert, altmatch)) {
1585 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1586 "'%s' not found", altmatch);
1588 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1589 "AltSubject mismatch",
1590 TLS_FAIL_ALTSUBJECT_MISMATCH);
1591 } else if (depth == 0 && suffix_match &&
1592 !tls_match_suffix(err_cert, suffix_match, 0)) {
1593 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
1596 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1597 "Domain suffix mismatch",
1598 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1599 } else if (depth == 0 && domain_match &&
1600 !tls_match_suffix(err_cert, domain_match, 1)) {
1601 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
1604 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1606 TLS_FAIL_DOMAIN_MISMATCH);
1608 openssl_tls_cert_event(conn, err_cert, depth, buf);
1610 if (conn->cert_probe && preverify_ok && depth == 0) {
1611 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1612 "on probe-only run");
1614 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1615 "Server certificate chain probe",
1616 TLS_FAIL_SERVER_CHAIN_PROBE);
1619 if (preverify_ok && context->event_cb != NULL)
1620 context->event_cb(context->cb_ctx,
1621 TLS_CERT_CHAIN_SUCCESS, NULL);
1623 return preverify_ok;
1627 #ifndef OPENSSL_NO_STDIO
1628 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1630 SSL_CTX *ssl_ctx = _ssl_ctx;
1631 X509_LOOKUP *lookup;
1634 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
1635 X509_LOOKUP_file());
1636 if (lookup == NULL) {
1637 tls_show_errors(MSG_WARNING, __func__,
1638 "Failed add lookup for X509 store");
1642 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1643 unsigned long err = ERR_peek_error();
1644 tls_show_errors(MSG_WARNING, __func__,
1645 "Failed load CA in DER format");
1646 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1647 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1648 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1649 "cert already in hash table error",
1657 #endif /* OPENSSL_NO_STDIO */
1660 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1661 const char *ca_cert, const u8 *ca_cert_blob,
1662 size_t ca_cert_blob_len, const char *ca_path)
1664 SSL_CTX *ssl_ctx = _ssl_ctx;
1668 * Remove previously configured trusted CA certificates before adding
1671 store = X509_STORE_new();
1672 if (store == NULL) {
1673 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1674 "certificate store", __func__);
1677 SSL_CTX_set_cert_store(ssl_ctx, store);
1679 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1680 conn->ca_cert_verify = 1;
1682 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1683 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1685 conn->cert_probe = 1;
1686 conn->ca_cert_verify = 0;
1690 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1691 #ifdef CONFIG_SHA256
1692 const char *pos = ca_cert + 7;
1693 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1694 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1695 "hash value '%s'", ca_cert);
1699 if (os_strlen(pos) != 32 * 2) {
1700 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1701 "hash length in ca_cert '%s'", ca_cert);
1704 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1705 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1706 "value in ca_cert '%s'", ca_cert);
1709 conn->server_cert_only = 1;
1710 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1711 "certificate match");
1713 #else /* CONFIG_SHA256 */
1714 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1715 "cannot validate server certificate hash");
1717 #endif /* CONFIG_SHA256 */
1721 X509 *cert = d2i_X509(NULL,
1722 (const unsigned char **) &ca_cert_blob,
1725 tls_show_errors(MSG_WARNING, __func__,
1726 "Failed to parse ca_cert_blob");
1730 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
1732 unsigned long err = ERR_peek_error();
1733 tls_show_errors(MSG_WARNING, __func__,
1734 "Failed to add ca_cert_blob to "
1735 "certificate store");
1736 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1737 ERR_GET_REASON(err) ==
1738 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1739 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1740 "cert already in hash table error",
1748 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1749 "to certificate store", __func__);
1754 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1755 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1756 STACK_OF(X509_INFO) *stack = NULL;
1760 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1766 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1767 X509_INFO *info = sk_X509_INFO_value(stack, i);
1769 X509_STORE_add_cert(ssl_ctx->cert_store,
1773 X509_STORE_add_crl(ssl_ctx->cert_store,
1777 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1778 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1781 #endif /* ANDROID */
1783 #ifdef CONFIG_NATIVE_WINDOWS
1784 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1786 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1787 "system certificate store");
1790 #endif /* CONFIG_NATIVE_WINDOWS */
1792 if (ca_cert || ca_path) {
1793 #ifndef OPENSSL_NO_STDIO
1794 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1796 tls_show_errors(MSG_WARNING, __func__,
1797 "Failed to load root certificates");
1799 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1800 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1801 "DER format CA certificate",
1806 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1807 "certificate(s) loaded");
1808 tls_get_errors(ssl_ctx);
1810 #else /* OPENSSL_NO_STDIO */
1811 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1814 #endif /* OPENSSL_NO_STDIO */
1816 /* No ca_cert configured - do not try to verify server
1818 conn->ca_cert_verify = 0;
1825 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1828 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1830 tls_show_errors(MSG_WARNING, __func__,
1831 "Failed to load root certificates");
1835 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1836 "certificate(s) loaded");
1838 #ifndef OPENSSL_NO_STDIO
1839 /* Add the same CAs to the client certificate requests */
1840 SSL_CTX_set_client_CA_list(ssl_ctx,
1841 SSL_load_client_CA_file(ca_cert));
1842 #endif /* OPENSSL_NO_STDIO */
1849 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1854 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1856 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1857 "certificate store when enabling "
1861 flags = X509_V_FLAG_CRL_CHECK;
1863 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1864 X509_STORE_set_flags(cs, flags);
1870 static int tls_connection_set_subject_match(struct tls_connection *conn,
1871 const char *subject_match,
1872 const char *altsubject_match,
1873 const char *suffix_match,
1874 const char *domain_match)
1876 os_free(conn->subject_match);
1877 conn->subject_match = NULL;
1878 if (subject_match) {
1879 conn->subject_match = os_strdup(subject_match);
1880 if (conn->subject_match == NULL)
1884 os_free(conn->altsubject_match);
1885 conn->altsubject_match = NULL;
1886 if (altsubject_match) {
1887 conn->altsubject_match = os_strdup(altsubject_match);
1888 if (conn->altsubject_match == NULL)
1892 os_free(conn->suffix_match);
1893 conn->suffix_match = NULL;
1895 conn->suffix_match = os_strdup(suffix_match);
1896 if (conn->suffix_match == NULL)
1900 os_free(conn->domain_match);
1901 conn->domain_match = NULL;
1903 conn->domain_match = os_strdup(domain_match);
1904 if (conn->domain_match == NULL)
1912 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1915 static int counter = 0;
1921 conn->ca_cert_verify = 1;
1922 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1923 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1924 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1926 conn->ca_cert_verify = 0;
1927 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1930 SSL_set_accept_state(conn->ssl);
1933 * Set session id context in order to avoid fatal errors when client
1934 * tries to resume a session. However, set the context to a unique
1935 * value in order to effectively disable session resumption for now
1936 * since not all areas of the server code are ready for it (e.g.,
1937 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1941 SSL_set_session_id_context(conn->ssl,
1942 (const unsigned char *) &counter,
1949 static int tls_connection_client_cert(struct tls_connection *conn,
1950 const char *client_cert,
1951 const u8 *client_cert_blob,
1952 size_t client_cert_blob_len)
1954 if (client_cert == NULL && client_cert_blob == NULL)
1957 if (client_cert_blob &&
1958 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1959 client_cert_blob_len) == 1) {
1960 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1963 } else if (client_cert_blob) {
1964 tls_show_errors(MSG_DEBUG, __func__,
1965 "SSL_use_certificate_ASN1 failed");
1968 if (client_cert == NULL)
1972 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1973 BIO *bio = BIO_from_keystore(&client_cert[11]);
1977 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1981 if (SSL_use_certificate(conn->ssl, x509) == 1)
1987 #endif /* ANDROID */
1989 #ifndef OPENSSL_NO_STDIO
1990 if (SSL_use_certificate_file(conn->ssl, client_cert,
1991 SSL_FILETYPE_ASN1) == 1) {
1992 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1997 if (SSL_use_certificate_file(conn->ssl, client_cert,
1998 SSL_FILETYPE_PEM) == 1) {
2000 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2005 tls_show_errors(MSG_DEBUG, __func__,
2006 "SSL_use_certificate_file failed");
2007 #else /* OPENSSL_NO_STDIO */
2008 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2009 #endif /* OPENSSL_NO_STDIO */
2015 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
2017 #ifndef OPENSSL_NO_STDIO
2018 if (client_cert == NULL)
2021 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2022 SSL_FILETYPE_ASN1) != 1 &&
2023 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2024 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2025 SSL_FILETYPE_PEM) != 1) {
2026 tls_show_errors(MSG_INFO, __func__,
2027 "Failed to load client certificate");
2031 #else /* OPENSSL_NO_STDIO */
2032 if (client_cert == NULL)
2034 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2036 #endif /* OPENSSL_NO_STDIO */
2040 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2042 if (password == NULL) {
2045 os_strlcpy(buf, (char *) password, size);
2046 return os_strlen(buf);
2051 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
2056 STACK_OF(X509) *certs;
2063 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2064 tls_show_errors(MSG_DEBUG, __func__,
2065 "Failed to parse PKCS12 file");
2069 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2072 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2074 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2075 "subject='%s'", buf);
2077 if (SSL_use_certificate(ssl, cert) != 1)
2080 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
2087 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2089 if (SSL_use_PrivateKey(ssl, pkey) != 1)
2092 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
2095 EVP_PKEY_free(pkey);
2099 while ((cert = sk_X509_pop(certs)) != NULL) {
2100 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2102 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2103 " from PKCS12: subject='%s'", buf);
2105 * There is no SSL equivalent for the chain cert - so
2106 * always add it to the context...
2108 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
2113 sk_X509_free(certs);
2119 tls_get_errors(ssl_ctx);
2123 #endif /* PKCS12_FUNCS */
2126 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
2133 f = fopen(private_key, "rb");
2137 p12 = d2i_PKCS12_fp(f, NULL);
2141 tls_show_errors(MSG_INFO, __func__,
2142 "Failed to use PKCS#12 file");
2146 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2148 #else /* PKCS12_FUNCS */
2149 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2152 #endif /* PKCS12_FUNCS */
2156 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
2157 const u8 *blob, size_t len, const char *passwd)
2162 p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2164 tls_show_errors(MSG_INFO, __func__,
2165 "Failed to use PKCS#12 blob");
2169 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2171 #else /* PKCS12_FUNCS */
2172 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2175 #endif /* PKCS12_FUNCS */
2179 #ifndef OPENSSL_NO_ENGINE
2180 static int tls_engine_get_cert(struct tls_connection *conn,
2181 const char *cert_id,
2184 /* this runs after the private key is loaded so no PIN is required */
2186 const char *cert_id;
2189 params.cert_id = cert_id;
2192 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2193 0, ¶ms, NULL, 1)) {
2194 unsigned long err = ERR_get_error();
2196 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2197 " '%s' [%s]", cert_id,
2198 ERR_error_string(err, NULL));
2199 if (tls_is_pin_error(err))
2200 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2201 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2204 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2206 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2208 *cert = params.cert;
2211 #endif /* OPENSSL_NO_ENGINE */
2214 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2215 const char *cert_id)
2217 #ifndef OPENSSL_NO_ENGINE
2220 if (tls_engine_get_cert(conn, cert_id, &cert))
2223 if (!SSL_use_certificate(conn->ssl, cert)) {
2224 tls_show_errors(MSG_ERROR, __func__,
2225 "SSL_use_certificate failed");
2230 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2234 #else /* OPENSSL_NO_ENGINE */
2236 #endif /* OPENSSL_NO_ENGINE */
2240 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
2241 struct tls_connection *conn,
2242 const char *ca_cert_id)
2244 #ifndef OPENSSL_NO_ENGINE
2246 SSL_CTX *ssl_ctx = _ssl_ctx;
2249 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2252 /* start off the same as tls_connection_ca_cert */
2253 store = X509_STORE_new();
2254 if (store == NULL) {
2255 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2256 "certificate store", __func__);
2260 SSL_CTX_set_cert_store(ssl_ctx, store);
2261 if (!X509_STORE_add_cert(store, cert)) {
2262 unsigned long err = ERR_peek_error();
2263 tls_show_errors(MSG_WARNING, __func__,
2264 "Failed to add CA certificate from engine "
2265 "to certificate store");
2266 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2267 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2268 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2269 " already in hash table error",
2277 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2278 "to certificate store", __func__);
2279 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2280 conn->ca_cert_verify = 1;
2284 #else /* OPENSSL_NO_ENGINE */
2286 #endif /* OPENSSL_NO_ENGINE */
2290 static int tls_connection_engine_private_key(struct tls_connection *conn)
2292 #ifndef OPENSSL_NO_ENGINE
2293 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2294 tls_show_errors(MSG_ERROR, __func__,
2295 "ENGINE: cannot use private key for TLS");
2298 if (!SSL_check_private_key(conn->ssl)) {
2299 tls_show_errors(MSG_INFO, __func__,
2300 "Private key failed verification");
2304 #else /* OPENSSL_NO_ENGINE */
2305 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2306 "engine support was not compiled in");
2308 #endif /* OPENSSL_NO_ENGINE */
2312 static int tls_connection_private_key(void *_ssl_ctx,
2313 struct tls_connection *conn,
2314 const char *private_key,
2315 const char *private_key_passwd,
2316 const u8 *private_key_blob,
2317 size_t private_key_blob_len)
2319 SSL_CTX *ssl_ctx = _ssl_ctx;
2323 if (private_key == NULL && private_key_blob == NULL)
2326 if (private_key_passwd) {
2327 passwd = os_strdup(private_key_passwd);
2333 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2334 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2337 while (private_key_blob) {
2338 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2339 (u8 *) private_key_blob,
2340 private_key_blob_len) == 1) {
2341 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2342 "ASN1(EVP_PKEY_RSA) --> OK");
2347 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2348 (u8 *) private_key_blob,
2349 private_key_blob_len) == 1) {
2350 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2351 "ASN1(EVP_PKEY_DSA) --> OK");
2356 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2357 (u8 *) private_key_blob,
2358 private_key_blob_len) == 1) {
2359 wpa_printf(MSG_DEBUG, "OpenSSL: "
2360 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2365 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2366 private_key_blob_len, passwd) == 0) {
2367 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2376 while (!ok && private_key) {
2377 #ifndef OPENSSL_NO_STDIO
2378 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2379 SSL_FILETYPE_ASN1) == 1) {
2380 wpa_printf(MSG_DEBUG, "OpenSSL: "
2381 "SSL_use_PrivateKey_File (DER) --> OK");
2386 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2387 SSL_FILETYPE_PEM) == 1) {
2388 wpa_printf(MSG_DEBUG, "OpenSSL: "
2389 "SSL_use_PrivateKey_File (PEM) --> OK");
2393 #else /* OPENSSL_NO_STDIO */
2394 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2396 #endif /* OPENSSL_NO_STDIO */
2398 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2400 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2406 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2407 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2408 "access certificate store --> OK");
2417 tls_show_errors(MSG_INFO, __func__,
2418 "Failed to load private key");
2423 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2426 if (!SSL_check_private_key(conn->ssl)) {
2427 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2432 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2437 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2438 const char *private_key_passwd)
2442 if (private_key == NULL)
2445 if (private_key_passwd) {
2446 passwd = os_strdup(private_key_passwd);
2452 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2453 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2455 #ifndef OPENSSL_NO_STDIO
2456 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2457 SSL_FILETYPE_ASN1) != 1 &&
2458 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2459 SSL_FILETYPE_PEM) != 1 &&
2460 #endif /* OPENSSL_NO_STDIO */
2461 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2462 tls_show_errors(MSG_INFO, __func__,
2463 "Failed to load private key");
2470 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2472 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2473 tls_show_errors(MSG_INFO, __func__,
2474 "Private key failed verification");
2482 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2484 #ifdef OPENSSL_NO_DH
2485 if (dh_file == NULL)
2487 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2488 "dh_file specified");
2490 #else /* OPENSSL_NO_DH */
2494 /* TODO: add support for dh_blob */
2495 if (dh_file == NULL)
2500 bio = BIO_new_file(dh_file, "r");
2502 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2503 dh_file, ERR_error_string(ERR_get_error(), NULL));
2506 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2508 #ifndef OPENSSL_NO_DSA
2509 while (dh == NULL) {
2511 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2512 " trying to parse as DSA params", dh_file,
2513 ERR_error_string(ERR_get_error(), NULL));
2514 bio = BIO_new_file(dh_file, "r");
2517 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2520 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2521 "'%s': %s", dh_file,
2522 ERR_error_string(ERR_get_error(), NULL));
2526 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2527 dh = DSA_dup_DH(dsa);
2530 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2531 "params into DH params");
2536 #endif /* !OPENSSL_NO_DSA */
2538 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2543 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2544 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2546 ERR_error_string(ERR_get_error(), NULL));
2552 #endif /* OPENSSL_NO_DH */
2556 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2558 #ifdef OPENSSL_NO_DH
2559 if (dh_file == NULL)
2561 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2562 "dh_file specified");
2564 #else /* OPENSSL_NO_DH */
2568 /* TODO: add support for dh_blob */
2569 if (dh_file == NULL)
2571 if (ssl_ctx == NULL)
2574 bio = BIO_new_file(dh_file, "r");
2576 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2577 dh_file, ERR_error_string(ERR_get_error(), NULL));
2580 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2582 #ifndef OPENSSL_NO_DSA
2583 while (dh == NULL) {
2585 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2586 " trying to parse as DSA params", dh_file,
2587 ERR_error_string(ERR_get_error(), NULL));
2588 bio = BIO_new_file(dh_file, "r");
2591 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2594 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2595 "'%s': %s", dh_file,
2596 ERR_error_string(ERR_get_error(), NULL));
2600 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2601 dh = DSA_dup_DH(dsa);
2604 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2605 "params into DH params");
2610 #endif /* !OPENSSL_NO_DSA */
2612 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2617 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2618 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2620 ERR_error_string(ERR_get_error(), NULL));
2626 #endif /* OPENSSL_NO_DH */
2630 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2631 struct tls_keys *keys)
2634 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2637 #else /* CONFIG_FIPS */
2640 if (conn == NULL || keys == NULL)
2643 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2646 os_memset(keys, 0, sizeof(*keys));
2647 keys->client_random = ssl->s3->client_random;
2648 keys->client_random_len = SSL3_RANDOM_SIZE;
2649 keys->server_random = ssl->s3->server_random;
2650 keys->server_random_len = SSL3_RANDOM_SIZE;
2653 #endif /* CONFIG_FIPS */
2657 static int openssl_get_keyblock_size(SSL *ssl)
2659 const EVP_CIPHER *c;
2663 if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2664 ssl->read_hash == NULL)
2667 c = ssl->enc_read_ctx->cipher;
2668 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2669 h = EVP_MD_CTX_md(ssl->read_hash);
2674 md_size = EVP_MD_size(h);
2675 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2677 md_size = ssl->s3->tmp.new_mac_secret_size;
2682 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2683 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2684 EVP_CIPHER_iv_length(c));
2685 return 2 * (EVP_CIPHER_key_length(c) +
2687 EVP_CIPHER_iv_length(c));
2691 static int openssl_tls_prf(void *tls_ctx, struct tls_connection *conn,
2692 const char *label, int server_random_first,
2693 int skip_keyblock, u8 *out, size_t out_len)
2696 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2699 #else /* CONFIG_FIPS */
2708 * TLS library did not support key generation, so get the needed TLS
2709 * session parameters and use an internal implementation of TLS PRF to
2716 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2717 ssl->session->master_key_length <= 0)
2720 if (skip_keyblock) {
2721 skip = openssl_get_keyblock_size(ssl);
2724 tmp_out = os_malloc(skip + out_len);
2730 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2736 if (server_random_first) {
2737 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2738 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2741 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2742 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2746 /* TODO: TLSv1.2 may need another PRF. This could use something closer
2747 * to SSL_export_keying_material() design. */
2748 if (tls_prf_sha1_md5(ssl->session->master_key,
2749 ssl->session->master_key_length,
2750 label, rnd, 2 * SSL3_RANDOM_SIZE,
2751 _out, skip + out_len) == 0)
2754 if (ret == 0 && skip_keyblock)
2755 os_memcpy(out, _out + skip, out_len);
2756 bin_clear_free(tmp_out, skip);
2759 #endif /* CONFIG_FIPS */
2763 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2764 const char *label, int server_random_first,
2765 int skip_keyblock, u8 *out, size_t out_len)
2767 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2771 if (server_random_first || skip_keyblock)
2772 return openssl_tls_prf(tls_ctx, conn, label,
2773 server_random_first, skip_keyblock,
2776 if (SSL_export_keying_material(ssl, out, out_len, label,
2777 os_strlen(label), NULL, 0, 0) == 1) {
2778 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2782 return openssl_tls_prf(tls_ctx, conn, label, server_random_first,
2783 skip_keyblock, out, out_len);
2787 static struct wpabuf *
2788 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2792 struct wpabuf *out_data;
2795 * Give TLS handshake data from the server (if available) to OpenSSL
2799 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2801 tls_show_errors(MSG_INFO, __func__,
2802 "Handshake failed - BIO_write");
2806 /* Initiate TLS handshake or continue the existing handshake */
2808 res = SSL_accept(conn->ssl);
2810 res = SSL_connect(conn->ssl);
2812 int err = SSL_get_error(conn->ssl, res);
2813 if (err == SSL_ERROR_WANT_READ)
2814 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2816 else if (err == SSL_ERROR_WANT_WRITE)
2817 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2820 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2825 /* Get the TLS handshake data to be sent to the server */
2826 res = BIO_ctrl_pending(conn->ssl_out);
2827 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2828 out_data = wpabuf_alloc(res);
2829 if (out_data == NULL) {
2830 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2831 "handshake output (%d bytes)", res);
2832 if (BIO_reset(conn->ssl_out) < 0) {
2833 tls_show_errors(MSG_INFO, __func__,
2834 "BIO_reset failed");
2838 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2841 tls_show_errors(MSG_INFO, __func__,
2842 "Handshake failed - BIO_read");
2843 if (BIO_reset(conn->ssl_out) < 0) {
2844 tls_show_errors(MSG_INFO, __func__,
2845 "BIO_reset failed");
2847 wpabuf_free(out_data);
2850 wpabuf_put(out_data, res);
2856 static struct wpabuf *
2857 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2859 struct wpabuf *appl_data;
2862 appl_data = wpabuf_alloc(max_len + 100);
2863 if (appl_data == NULL)
2866 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2867 wpabuf_size(appl_data));
2869 int err = SSL_get_error(conn->ssl, res);
2870 if (err == SSL_ERROR_WANT_READ ||
2871 err == SSL_ERROR_WANT_WRITE) {
2872 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2875 tls_show_errors(MSG_INFO, __func__,
2876 "Failed to read possible "
2877 "Application Data");
2879 wpabuf_free(appl_data);
2883 wpabuf_put(appl_data, res);
2884 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2885 "message", appl_data);
2891 static struct wpabuf *
2892 openssl_connection_handshake(struct tls_connection *conn,
2893 const struct wpabuf *in_data,
2894 struct wpabuf **appl_data, int server)
2896 struct wpabuf *out_data;
2901 out_data = openssl_handshake(conn, in_data, server);
2902 if (out_data == NULL)
2904 if (conn->invalid_hb_used) {
2905 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2906 wpabuf_free(out_data);
2910 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2911 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2913 if (conn->invalid_hb_used) {
2914 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
2916 wpabuf_free(*appl_data);
2919 wpabuf_free(out_data);
2928 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2929 const struct wpabuf *in_data,
2930 struct wpabuf **appl_data)
2932 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2936 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2937 struct tls_connection *conn,
2938 const struct wpabuf *in_data,
2939 struct wpabuf **appl_data)
2941 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2945 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2946 struct tls_connection *conn,
2947 const struct wpabuf *in_data)
2955 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2956 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2957 (res = BIO_reset(conn->ssl_out)) < 0) {
2958 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2961 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2963 tls_show_errors(MSG_INFO, __func__,
2964 "Encryption failed - SSL_write");
2968 /* Read encrypted data to be sent to the server */
2969 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2972 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2974 tls_show_errors(MSG_INFO, __func__,
2975 "Encryption failed - BIO_read");
2979 wpabuf_put(buf, res);
2985 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2986 struct tls_connection *conn,
2987 const struct wpabuf *in_data)
2992 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2993 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2994 wpabuf_len(in_data));
2996 tls_show_errors(MSG_INFO, __func__,
2997 "Decryption failed - BIO_write");
3000 if (BIO_reset(conn->ssl_out) < 0) {
3001 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3005 /* Read decrypted data for further processing */
3007 * Even though we try to disable TLS compression, it is possible that
3008 * this cannot be done with all TLS libraries. Add extra buffer space
3009 * to handle the possibility of the decrypted data being longer than
3012 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3015 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3017 tls_show_errors(MSG_INFO, __func__,
3018 "Decryption failed - SSL_read");
3022 wpabuf_put(buf, res);
3024 if (conn->invalid_hb_used) {
3025 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3034 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3036 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3037 return conn ? SSL_cache_hit(conn->ssl) : 0;
3039 return conn ? conn->ssl->hit : 0;
3044 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3047 char buf[100], *pos, *end;
3051 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3056 end = pos + sizeof(buf);
3059 while (*c != TLS_CIPHER_NONE) {
3063 case TLS_CIPHER_RC4_SHA:
3066 case TLS_CIPHER_AES128_SHA:
3067 suite = "AES128-SHA";
3069 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3070 suite = "DHE-RSA-AES128-SHA";
3072 case TLS_CIPHER_ANON_DH_AES128_SHA:
3073 suite = "ADH-AES128-SHA";
3076 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3077 "cipher selection: %d", *c);
3080 ret = os_snprintf(pos, end - pos, ":%s", suite);
3081 if (os_snprintf_error(end - pos, ret))
3088 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3090 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3091 tls_show_errors(MSG_INFO, __func__,
3092 "Cipher suite configuration failed");
3100 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3101 char *buf, size_t buflen)
3104 if (conn == NULL || conn->ssl == NULL)
3107 name = SSL_get_cipher(conn->ssl);
3111 os_strlcpy(buf, name, buflen);
3116 int tls_connection_enable_workaround(void *ssl_ctx,
3117 struct tls_connection *conn)
3119 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3125 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3126 /* ClientHello TLS extensions require a patch to openssl, so this function is
3127 * commented out unless explicitly needed for EAP-FAST in order to be able to
3128 * build this file with unmodified openssl. */
3129 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3130 int ext_type, const u8 *data,
3133 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3136 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3142 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3145 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3149 return conn->failed;
3153 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3157 return conn->read_alerts;
3161 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3165 return conn->write_alerts;
3171 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3173 #ifndef CONFIG_NO_STDOUT_DEBUG
3179 if (wpa_debug_level > MSG_DEBUG)
3182 out = BIO_new(BIO_s_mem());
3186 OCSP_RESPONSE_print(out, rsp, 0);
3187 rlen = BIO_ctrl_pending(out);
3188 txt = os_malloc(rlen + 1);
3194 res = BIO_read(out, txt, rlen);
3197 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3201 #endif /* CONFIG_NO_STDOUT_DEBUG */
3205 static void debug_print_cert(X509 *cert, const char *title)
3207 #ifndef CONFIG_NO_STDOUT_DEBUG
3213 if (wpa_debug_level > MSG_DEBUG)
3216 out = BIO_new(BIO_s_mem());
3220 X509_print(out, cert);
3221 rlen = BIO_ctrl_pending(out);
3222 txt = os_malloc(rlen + 1);
3228 res = BIO_read(out, txt, rlen);
3231 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3236 #endif /* CONFIG_NO_STDOUT_DEBUG */
3240 static int ocsp_resp_cb(SSL *s, void *arg)
3242 struct tls_connection *conn = arg;
3243 const unsigned char *p;
3244 int len, status, reason;
3246 OCSP_BASICRESP *basic;
3248 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3250 STACK_OF(X509) *certs = NULL;
3252 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3254 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3255 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3258 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3260 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3262 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3266 ocsp_debug_print_resp(rsp);
3268 status = OCSP_response_status(rsp);
3269 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3270 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3271 status, OCSP_response_status_str(status));
3275 basic = OCSP_response_get1_basic(rsp);
3277 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3281 store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3282 if (conn->peer_issuer) {
3283 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3285 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3286 tls_show_errors(MSG_INFO, __func__,
3287 "OpenSSL: Could not add issuer to certificate store");
3289 certs = sk_X509_new_null();
3292 cert = X509_dup(conn->peer_issuer);
3293 if (cert && !sk_X509_push(certs, cert)) {
3296 "OpenSSL: Could not add issuer to OCSP responder trust store");
3298 sk_X509_free(certs);
3301 if (certs && conn->peer_issuer_issuer) {
3302 cert = X509_dup(conn->peer_issuer_issuer);
3303 if (cert && !sk_X509_push(certs, cert)) {
3306 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3313 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3314 sk_X509_pop_free(certs, X509_free);
3316 tls_show_errors(MSG_INFO, __func__,
3317 "OpenSSL: OCSP response failed verification");
3318 OCSP_BASICRESP_free(basic);
3319 OCSP_RESPONSE_free(rsp);
3323 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3325 if (!conn->peer_cert) {
3326 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3327 OCSP_BASICRESP_free(basic);
3328 OCSP_RESPONSE_free(rsp);
3332 if (!conn->peer_issuer) {
3333 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3334 OCSP_BASICRESP_free(basic);
3335 OCSP_RESPONSE_free(rsp);
3339 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3341 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3342 OCSP_BASICRESP_free(basic);
3343 OCSP_RESPONSE_free(rsp);
3347 if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3348 &this_update, &next_update)) {
3349 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3350 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3351 " (OCSP not required)");
3352 OCSP_BASICRESP_free(basic);
3353 OCSP_RESPONSE_free(rsp);
3354 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3357 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3358 tls_show_errors(MSG_INFO, __func__,
3359 "OpenSSL: OCSP status times invalid");
3360 OCSP_BASICRESP_free(basic);
3361 OCSP_RESPONSE_free(rsp);
3365 OCSP_BASICRESP_free(basic);
3366 OCSP_RESPONSE_free(rsp);
3368 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3369 OCSP_cert_status_str(status));
3371 if (status == V_OCSP_CERTSTATUS_GOOD)
3373 if (status == V_OCSP_CERTSTATUS_REVOKED)
3375 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3376 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3379 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3384 static int ocsp_status_cb(SSL *s, void *arg)
3390 if (tls_global->ocsp_stapling_response == NULL) {
3391 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3392 return SSL_TLSEXT_ERR_OK;
3395 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3397 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3398 /* TODO: Build OCSPResponse with responseStatus = internalError
3400 return SSL_TLSEXT_ERR_OK;
3402 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3403 tmp = OPENSSL_malloc(len);
3406 return SSL_TLSEXT_ERR_ALERT_FATAL;
3409 os_memcpy(tmp, resp, len);
3411 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3413 return SSL_TLSEXT_ERR_OK;
3416 #endif /* HAVE_OCSP */
3419 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3420 const struct tls_connection_params *params)
3425 const char *key_id = params->key_id;
3426 const char *cert_id = params->cert_id;
3427 const char *ca_cert_id = params->ca_cert_id;
3428 const char *engine_id = params->engine ? params->engine_id : NULL;
3434 * If the engine isn't explicitly configured, and any of the
3435 * cert/key fields are actually PKCS#11 URIs, then automatically
3436 * use the PKCS#11 ENGINE.
3438 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3441 if (!key_id && params->private_key && can_pkcs11 &&
3442 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3444 key_id = params->private_key;
3447 if (!cert_id && params->client_cert && can_pkcs11 &&
3448 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3450 cert_id = params->client_cert;
3453 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3454 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3456 ca_cert_id = params->ca_cert;
3459 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3460 if (can_pkcs11 == 2 && !engine_id)
3461 engine_id = "pkcs11";
3463 if (params->flags & TLS_CONN_EAP_FAST) {
3464 wpa_printf(MSG_DEBUG,
3465 "OpenSSL: Use TLSv1_method() for EAP-FAST");
3466 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3467 tls_show_errors(MSG_INFO, __func__,
3468 "Failed to set TLSv1_method() for EAP-FAST");
3473 while ((err = ERR_get_error())) {
3474 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3475 __func__, ERR_error_string(err, NULL));
3479 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3480 ret = tls_engine_init(conn, engine_id, params->pin,
3481 key_id, cert_id, ca_cert_id);
3485 if (tls_connection_set_subject_match(conn,
3486 params->subject_match,
3487 params->altsubject_match,
3488 params->suffix_match,
3489 params->domain_match))
3492 if (engine_id && ca_cert_id) {
3493 if (tls_connection_engine_ca_cert(tls_ctx, conn,
3495 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3496 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
3497 params->ca_cert_blob,
3498 params->ca_cert_blob_len,
3502 if (engine_id && cert_id) {
3503 if (tls_connection_engine_client_cert(conn, cert_id))
3504 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3505 } else if (tls_connection_client_cert(conn, params->client_cert,
3506 params->client_cert_blob,
3507 params->client_cert_blob_len))
3510 if (engine_id && key_id) {
3511 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3512 if (tls_connection_engine_private_key(conn))
3513 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3514 } else if (tls_connection_private_key(tls_ctx, conn,
3515 params->private_key,
3516 params->private_key_passwd,
3517 params->private_key_blob,
3518 params->private_key_blob_len)) {
3519 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3520 params->private_key);
3524 if (tls_connection_dh(conn, params->dh_file)) {
3525 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3530 if (params->openssl_ciphers &&
3531 SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3532 wpa_printf(MSG_INFO,
3533 "OpenSSL: Failed to set cipher string '%s'",
3534 params->openssl_ciphers);
3538 #ifdef SSL_OP_NO_TICKET
3539 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3540 SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
3541 #ifdef SSL_clear_options
3543 SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
3544 #endif /* SSL_clear_options */
3545 #endif /* SSL_OP_NO_TICKET */
3547 #ifdef SSL_OP_NO_TLSv1_1
3548 if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
3549 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3551 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3552 #endif /* SSL_OP_NO_TLSv1_1 */
3553 #ifdef SSL_OP_NO_TLSv1_2
3554 if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
3555 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3557 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3558 #endif /* SSL_OP_NO_TLSv1_2 */
3561 if (params->flags & TLS_CONN_REQUEST_OCSP) {
3562 SSL_CTX *ssl_ctx = tls_ctx;
3563 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3564 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3565 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3567 #endif /* HAVE_OCSP */
3569 conn->flags = params->flags;
3571 tls_get_errors(tls_ctx);
3577 int tls_global_set_params(void *tls_ctx,
3578 const struct tls_connection_params *params)
3580 SSL_CTX *ssl_ctx = tls_ctx;
3583 while ((err = ERR_get_error())) {
3584 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3585 __func__, ERR_error_string(err, NULL));
3588 if (tls_global_ca_cert(ssl_ctx, params->ca_cert) ||
3589 tls_global_client_cert(ssl_ctx, params->client_cert) ||
3590 tls_global_private_key(ssl_ctx, params->private_key,
3591 params->private_key_passwd) ||
3592 tls_global_dh(ssl_ctx, params->dh_file)) {
3593 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
3597 if (params->openssl_ciphers &&
3598 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3599 wpa_printf(MSG_INFO,
3600 "OpenSSL: Failed to set cipher string '%s'",
3601 params->openssl_ciphers);
3605 #ifdef SSL_OP_NO_TICKET
3606 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3607 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3608 #ifdef SSL_CTX_clear_options
3610 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3611 #endif /* SSL_clear_options */
3612 #endif /* SSL_OP_NO_TICKET */
3615 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3616 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3617 os_free(tls_global->ocsp_stapling_response);
3618 if (params->ocsp_stapling_response)
3619 tls_global->ocsp_stapling_response =
3620 os_strdup(params->ocsp_stapling_response);
3622 tls_global->ocsp_stapling_response = NULL;
3623 #endif /* HAVE_OCSP */
3629 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3630 /* Pre-shared secred requires a patch to openssl, so this function is
3631 * commented out unless explicitly needed for EAP-FAST in order to be able to
3632 * build this file with unmodified openssl. */
3634 #ifdef OPENSSL_IS_BORINGSSL
3635 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3636 STACK_OF(SSL_CIPHER) *peer_ciphers,
3637 const SSL_CIPHER **cipher, void *arg)
3638 #else /* OPENSSL_IS_BORINGSSL */
3639 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3640 STACK_OF(SSL_CIPHER) *peer_ciphers,
3641 SSL_CIPHER **cipher, void *arg)
3642 #endif /* OPENSSL_IS_BORINGSSL */
3644 struct tls_connection *conn = arg;
3647 if (conn == NULL || conn->session_ticket_cb == NULL)
3650 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3651 conn->session_ticket,
3652 conn->session_ticket_len,
3653 s->s3->client_random,
3654 s->s3->server_random, secret);
3655 os_free(conn->session_ticket);
3656 conn->session_ticket = NULL;
3661 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3666 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3669 struct tls_connection *conn = arg;
3671 if (conn == NULL || conn->session_ticket_cb == NULL)
3674 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3676 os_free(conn->session_ticket);
3677 conn->session_ticket = NULL;
3679 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3680 "extension", data, len);
3682 conn->session_ticket = os_malloc(len);
3683 if (conn->session_ticket == NULL)
3686 os_memcpy(conn->session_ticket, data, len);
3687 conn->session_ticket_len = len;
3691 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3694 int tls_connection_set_session_ticket_cb(void *tls_ctx,
3695 struct tls_connection *conn,
3696 tls_session_ticket_cb cb,
3699 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3700 conn->session_ticket_cb = cb;
3701 conn->session_ticket_cb_ctx = ctx;
3704 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3707 SSL_set_session_ticket_ext_cb(conn->ssl,
3708 tls_session_ticket_ext_cb, conn);
3710 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3712 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3716 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3718 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3722 int tls_get_library_version(char *buf, size_t buf_len)
3724 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
3725 OPENSSL_VERSION_TEXT,
3726 SSLeay_version(SSLEAY_VERSION));