2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2011, Jouni Malinen <j@w1.fi>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
9 * Alternatively, this software may be distributed under the terms of BSD
12 * See README and COPYING for more details.
17 #ifndef CONFIG_SMARTCARD
18 #ifndef OPENSSL_NO_ENGINE
19 #define OPENSSL_NO_ENGINE
23 #include <openssl/ssl.h>
24 #include <openssl/err.h>
25 #include <openssl/pkcs12.h>
26 #include <openssl/x509v3.h>
27 #ifndef OPENSSL_NO_ENGINE
28 #include <openssl/engine.h>
29 #endif /* OPENSSL_NO_ENGINE */
32 #include <openssl/pem.h>
33 #include "keystore_get.h"
40 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
41 #define OPENSSL_d2i_TYPE const unsigned char **
43 #define OPENSSL_d2i_TYPE unsigned char **
46 #ifdef SSL_F_SSL_SET_SESSION_TICKET_EXT
47 #ifdef SSL_OP_NO_TICKET
49 * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
50 * 2008-11-15. This version uses a bit different API compared to the old patch.
52 #define CONFIG_OPENSSL_TICKET_OVERRIDE
56 static int tls_openssl_ref_count = 0;
59 void (*event_cb)(void *ctx, enum tls_event ev,
60 union tls_event_data *data);
65 static struct tls_global *tls_global = NULL;
68 struct tls_connection {
70 BIO *ssl_in, *ssl_out;
71 #ifndef OPENSSL_NO_ENGINE
72 ENGINE *engine; /* functional reference to the engine */
73 EVP_PKEY *private_key; /* the private key if using engine */
74 #endif /* OPENSSL_NO_ENGINE */
75 char *subject_match, *altsubject_match;
76 int read_alerts, write_alerts, failed;
78 tls_session_ticket_cb session_ticket_cb;
79 void *session_ticket_cb_ctx;
81 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
83 size_t session_ticket_len;
85 unsigned int ca_cert_verify:1;
86 unsigned int cert_probe:1;
87 unsigned int server_cert_only:1;
95 #ifdef CONFIG_NO_STDOUT_DEBUG
97 static void _tls_show_errors(void)
101 while ((err = ERR_get_error())) {
102 /* Just ignore the errors, since stdout is disabled */
105 #define tls_show_errors(l, f, t) _tls_show_errors()
107 #else /* CONFIG_NO_STDOUT_DEBUG */
109 static void tls_show_errors(int level, const char *func, const char *txt)
113 wpa_printf(level, "OpenSSL: %s - %s %s",
114 func, txt, ERR_error_string(ERR_get_error(), NULL));
116 while ((err = ERR_get_error())) {
117 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
118 ERR_error_string(err, NULL));
122 #endif /* CONFIG_NO_STDOUT_DEBUG */
125 #ifdef CONFIG_NATIVE_WINDOWS
127 /* Windows CryptoAPI and access to certificate stores */
128 #include <wincrypt.h>
130 #ifdef __MINGW32_VERSION
132 * MinGW does not yet include all the needed definitions for CryptoAPI, so
133 * define here whatever extra is needed.
135 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
136 #define CERT_STORE_READONLY_FLAG 0x00008000
137 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
139 #endif /* __MINGW32_VERSION */
142 struct cryptoapi_rsa_data {
143 const CERT_CONTEXT *cert;
144 HCRYPTPROV crypt_prov;
146 BOOL free_crypt_prov;
150 static void cryptoapi_error(const char *msg)
152 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
153 msg, (unsigned int) GetLastError());
157 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
158 unsigned char *to, RSA *rsa, int padding)
160 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
165 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
166 unsigned char *to, RSA *rsa, int padding)
168 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
173 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
174 unsigned char *to, RSA *rsa, int padding)
176 struct cryptoapi_rsa_data *priv =
177 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
179 DWORD hash_size, len, i;
180 unsigned char *buf = NULL;
184 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
185 ERR_R_PASSED_NULL_PARAMETER);
189 if (padding != RSA_PKCS1_PADDING) {
190 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
191 RSA_R_UNKNOWN_PADDING_TYPE);
195 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
196 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
198 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
199 RSA_R_INVALID_MESSAGE_LENGTH);
203 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
205 cryptoapi_error("CryptCreateHash failed");
209 len = sizeof(hash_size);
210 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
212 cryptoapi_error("CryptGetHashParam failed");
216 if ((int) hash_size != flen) {
217 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
218 (unsigned) hash_size, flen);
219 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
220 RSA_R_INVALID_MESSAGE_LENGTH);
223 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
224 cryptoapi_error("CryptSetHashParam failed");
229 buf = os_malloc(len);
231 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
235 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
236 cryptoapi_error("CryptSignHash failed");
240 for (i = 0; i < len; i++)
241 to[i] = buf[len - i - 1];
246 CryptDestroyHash(hash);
252 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
253 unsigned char *to, RSA *rsa, int padding)
255 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
260 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
264 if (priv->crypt_prov && priv->free_crypt_prov)
265 CryptReleaseContext(priv->crypt_prov, 0);
267 CertFreeCertificateContext(priv->cert);
272 static int cryptoapi_finish(RSA *rsa)
274 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
275 os_free((void *) rsa->meth);
281 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
284 const CERT_CONTEXT *ret = NULL;
286 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
287 store | CERT_STORE_OPEN_EXISTING_FLAG |
288 CERT_STORE_READONLY_FLAG, L"MY");
290 cryptoapi_error("Failed to open 'My system store'");
294 if (strncmp(name, "cert://", 7) == 0) {
295 unsigned short wbuf[255];
296 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
297 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
299 0, CERT_FIND_SUBJECT_STR,
301 } else if (strncmp(name, "hash://", 7) == 0) {
302 CRYPT_HASH_BLOB blob;
304 const char *hash = name + 7;
307 len = os_strlen(hash) / 2;
308 buf = os_malloc(len);
309 if (buf && hexstr2bin(hash, buf, len) == 0) {
312 ret = CertFindCertificateInStore(cs,
321 CertCloseStore(cs, 0);
327 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
330 RSA *rsa = NULL, *pub_rsa;
331 struct cryptoapi_rsa_data *priv;
332 RSA_METHOD *rsa_meth;
335 (strncmp(name, "cert://", 7) != 0 &&
336 strncmp(name, "hash://", 7) != 0))
339 priv = os_zalloc(sizeof(*priv));
340 rsa_meth = os_zalloc(sizeof(*rsa_meth));
341 if (priv == NULL || rsa_meth == NULL) {
342 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
343 "for CryptoAPI RSA method");
349 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
350 if (priv->cert == NULL) {
351 priv->cert = cryptoapi_find_cert(
352 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
354 if (priv->cert == NULL) {
355 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
360 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
361 priv->cert->cbCertEncoded);
363 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
368 if (!CryptAcquireCertificatePrivateKey(priv->cert,
369 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
370 NULL, &priv->crypt_prov,
372 &priv->free_crypt_prov)) {
373 cryptoapi_error("Failed to acquire a private key for the "
378 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
379 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
380 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
381 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
382 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
383 rsa_meth->finish = cryptoapi_finish;
384 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
385 rsa_meth->app_data = (char *) priv;
389 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
390 ERR_R_MALLOC_FAILURE);
394 if (!SSL_use_certificate(ssl, cert)) {
399 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
403 rsa->n = BN_dup(pub_rsa->n);
404 rsa->e = BN_dup(pub_rsa->e);
405 if (!RSA_set_method(rsa, rsa_meth))
408 if (!SSL_use_RSAPrivateKey(ssl, rsa))
421 cryptoapi_free_data(priv);
427 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
430 PCCERT_CONTEXT ctx = NULL;
438 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
443 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
446 wsprintf(wstore, L"%S", store);
447 cs = CertOpenSystemStore(0, wstore);
450 cs = CertOpenSystemStore(0, store);
453 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
454 "'%s': error=%d", __func__, store,
455 (int) GetLastError());
459 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
460 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
463 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
464 "X509 DER encoding for CA cert");
468 X509_NAME_oneline(X509_get_subject_name(cert), buf,
470 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
471 "system certificate store: subject='%s'", buf);
473 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
474 tls_show_errors(MSG_WARNING, __func__,
475 "Failed to add ca_cert to OpenSSL "
476 "certificate store");
482 if (!CertCloseStore(cs, 0)) {
483 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
484 "'%s': error=%d", __func__, name + 13,
485 (int) GetLastError());
492 #else /* CONFIG_NATIVE_WINDOWS */
494 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
499 #endif /* CONFIG_NATIVE_WINDOWS */
502 static void ssl_info_cb(const SSL *ssl, int where, int ret)
507 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
508 w = where & ~SSL_ST_MASK;
509 if (w & SSL_ST_CONNECT)
511 else if (w & SSL_ST_ACCEPT)
516 if (where & SSL_CB_LOOP) {
517 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
518 str, SSL_state_string_long(ssl));
519 } else if (where & SSL_CB_ALERT) {
520 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
521 where & SSL_CB_READ ?
522 "read (remote end reported an error)" :
523 "write (local SSL3 detected an error)",
524 SSL_alert_type_string_long(ret),
525 SSL_alert_desc_string_long(ret));
526 if ((ret >> 8) == SSL3_AL_FATAL) {
527 struct tls_connection *conn =
528 SSL_get_app_data((SSL *) ssl);
529 if (where & SSL_CB_READ)
532 conn->write_alerts++;
534 } else if (where & SSL_CB_EXIT && ret <= 0) {
535 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
536 str, ret == 0 ? "failed" : "error",
537 SSL_state_string_long(ssl));
542 #ifndef OPENSSL_NO_ENGINE
544 * tls_engine_load_dynamic_generic - load any openssl engine
545 * @pre: an array of commands and values that load an engine initialized
546 * in the engine specific function
547 * @post: an array of commands and values that initialize an already loaded
548 * engine (or %NULL if not required)
549 * @id: the engine id of the engine to load (only required if post is not %NULL
551 * This function is a generic function that loads any openssl engine.
553 * Returns: 0 on success, -1 on failure
555 static int tls_engine_load_dynamic_generic(const char *pre[],
556 const char *post[], const char *id)
559 const char *dynamic_id = "dynamic";
561 engine = ENGINE_by_id(id);
564 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
570 engine = ENGINE_by_id(dynamic_id);
571 if (engine == NULL) {
572 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
574 ERR_error_string(ERR_get_error(), NULL));
578 /* Perform the pre commands. This will load the engine. */
579 while (pre && pre[0]) {
580 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
581 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
582 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
583 "%s %s [%s]", pre[0], pre[1],
584 ERR_error_string(ERR_get_error(), NULL));
592 * Free the reference to the "dynamic" engine. The loaded engine can
593 * now be looked up using ENGINE_by_id().
597 engine = ENGINE_by_id(id);
598 if (engine == NULL) {
599 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
600 id, ERR_error_string(ERR_get_error(), NULL));
604 while (post && post[0]) {
605 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
606 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
607 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
608 " %s %s [%s]", post[0], post[1],
609 ERR_error_string(ERR_get_error(), NULL));
610 ENGINE_remove(engine);
623 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
624 * @pkcs11_so_path: pksc11_so_path from the configuration
625 * @pcks11_module_path: pkcs11_module_path from the configuration
627 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
628 const char *pkcs11_module_path)
630 char *engine_id = "pkcs11";
631 const char *pre_cmd[] = {
632 "SO_PATH", NULL /* pkcs11_so_path */,
633 "ID", NULL /* engine_id */,
635 /* "NO_VCHECK", "1", */
639 const char *post_cmd[] = {
640 "MODULE_PATH", NULL /* pkcs11_module_path */,
644 if (!pkcs11_so_path || !pkcs11_module_path)
647 pre_cmd[1] = pkcs11_so_path;
648 pre_cmd[3] = engine_id;
649 post_cmd[1] = pkcs11_module_path;
651 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
654 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
659 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
660 * @opensc_so_path: opensc_so_path from the configuration
662 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
664 char *engine_id = "opensc";
665 const char *pre_cmd[] = {
666 "SO_PATH", NULL /* opensc_so_path */,
667 "ID", NULL /* engine_id */,
676 pre_cmd[1] = opensc_so_path;
677 pre_cmd[3] = engine_id;
679 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
682 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
684 #endif /* OPENSSL_NO_ENGINE */
687 void * tls_init(const struct tls_config *conf)
691 if (tls_openssl_ref_count == 0) {
692 tls_global = os_zalloc(sizeof(*tls_global));
693 if (tls_global == NULL)
696 tls_global->event_cb = conf->event_cb;
697 tls_global->cb_ctx = conf->cb_ctx;
698 tls_global->cert_in_cb = conf->cert_in_cb;
703 if (conf && conf->fips_mode) {
704 if (!FIPS_mode_set(1)) {
705 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
707 ERR_load_crypto_strings();
708 ERR_print_errors_fp(stderr);
711 wpa_printf(MSG_INFO, "Running in FIPS mode");
713 #else /* OPENSSL_FIPS */
714 if (conf && conf->fips_mode) {
715 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
719 #endif /* OPENSSL_FIPS */
720 #endif /* CONFIG_FIPS */
721 SSL_load_error_strings();
723 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
724 EVP_add_digest(EVP_sha256());
725 #endif /* OPENSSL_NO_SHA256 */
726 /* TODO: if /dev/urandom is available, PRNG is seeded
727 * automatically. If this is not the case, random data should
731 #ifndef OPENSSL_NO_RC2
733 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
734 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
735 * versions, but it looks like OpenSSL 1.0.0 does not do that
738 EVP_add_cipher(EVP_rc2_40_cbc());
739 #endif /* OPENSSL_NO_RC2 */
741 #endif /* PKCS12_FUNCS */
743 tls_openssl_ref_count++;
745 ssl = SSL_CTX_new(TLSv1_method());
749 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
751 #ifndef OPENSSL_NO_ENGINE
753 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
754 conf->pkcs11_module_path)) {
755 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
756 ERR_load_ENGINE_strings();
757 ENGINE_load_dynamic();
759 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
760 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
761 conf->pkcs11_module_path)) {
766 #endif /* OPENSSL_NO_ENGINE */
772 void tls_deinit(void *ssl_ctx)
774 SSL_CTX *ssl = ssl_ctx;
777 tls_openssl_ref_count--;
778 if (tls_openssl_ref_count == 0) {
779 #ifndef OPENSSL_NO_ENGINE
781 #endif /* OPENSSL_NO_ENGINE */
782 CRYPTO_cleanup_all_ex_data();
792 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
793 const char *pin, const char *key_id,
794 const char *cert_id, const char *ca_cert_id)
796 #ifndef OPENSSL_NO_ENGINE
798 if (engine_id == NULL) {
799 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
803 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
806 if (key_id == NULL) {
807 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
812 conn->engine = ENGINE_by_id(engine_id);
814 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
815 engine_id, ERR_error_string(ERR_get_error(), NULL));
818 if (ENGINE_init(conn->engine) != 1) {
819 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
820 "(engine: %s) [%s]", engine_id,
821 ERR_error_string(ERR_get_error(), NULL));
824 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
826 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
827 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
828 ERR_error_string(ERR_get_error(), NULL));
831 /* load private key first in-case PIN is required for cert */
832 conn->private_key = ENGINE_load_private_key(conn->engine,
834 if (!conn->private_key) {
835 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
836 " '%s' [%s]", key_id,
837 ERR_error_string(ERR_get_error(), NULL));
838 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
842 /* handle a certificate and/or CA certificate */
843 if (cert_id || ca_cert_id) {
844 const char *cmd_name = "LOAD_CERT_CTRL";
846 /* test if the engine supports a LOAD_CERT_CTRL */
847 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
848 0, (void *)cmd_name, NULL)) {
849 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
850 " loading certificates");
851 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
860 ENGINE_free(conn->engine);
864 if (conn->private_key) {
865 EVP_PKEY_free(conn->private_key);
866 conn->private_key = NULL;
870 #else /* OPENSSL_NO_ENGINE */
872 #endif /* OPENSSL_NO_ENGINE */
876 static void tls_engine_deinit(struct tls_connection *conn)
878 #ifndef OPENSSL_NO_ENGINE
879 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
880 if (conn->private_key) {
881 EVP_PKEY_free(conn->private_key);
882 conn->private_key = NULL;
885 ENGINE_finish(conn->engine);
888 #endif /* OPENSSL_NO_ENGINE */
892 int tls_get_errors(void *ssl_ctx)
897 while ((err = ERR_get_error())) {
898 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
899 ERR_error_string(err, NULL));
906 struct tls_connection * tls_connection_init(void *ssl_ctx)
908 SSL_CTX *ssl = ssl_ctx;
909 struct tls_connection *conn;
912 conn = os_zalloc(sizeof(*conn));
915 conn->ssl = SSL_new(ssl);
916 if (conn->ssl == NULL) {
917 tls_show_errors(MSG_INFO, __func__,
918 "Failed to initialize new SSL connection");
923 SSL_set_app_data(conn->ssl, conn);
924 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
925 SSL_OP_SINGLE_DH_USE;
926 #ifdef SSL_OP_NO_COMPRESSION
927 options |= SSL_OP_NO_COMPRESSION;
928 #endif /* SSL_OP_NO_COMPRESSION */
929 SSL_set_options(conn->ssl, options);
931 conn->ssl_in = BIO_new(BIO_s_mem());
933 tls_show_errors(MSG_INFO, __func__,
934 "Failed to create a new BIO for ssl_in");
940 conn->ssl_out = BIO_new(BIO_s_mem());
941 if (!conn->ssl_out) {
942 tls_show_errors(MSG_INFO, __func__,
943 "Failed to create a new BIO for ssl_out");
945 BIO_free(conn->ssl_in);
950 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
956 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
961 tls_engine_deinit(conn);
962 os_free(conn->subject_match);
963 os_free(conn->altsubject_match);
964 os_free(conn->session_ticket);
969 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
971 return conn ? SSL_is_init_finished(conn->ssl) : 0;
975 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
980 /* Shutdown previous TLS connection without notifying the peer
981 * because the connection was already terminated in practice
982 * and "close notify" shutdown alert would confuse AS. */
983 SSL_set_quiet_shutdown(conn->ssl, 1);
984 SSL_shutdown(conn->ssl);
989 static int tls_match_altsubject_component(X509 *cert, int type,
990 const char *value, size_t len)
996 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
998 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
999 gen = sk_GENERAL_NAME_value(ext, i);
1000 if (gen->type != type)
1002 if (os_strlen((char *) gen->d.ia5->data) == len &&
1003 os_memcmp(value, gen->d.ia5->data, len) == 0)
1011 static int tls_match_altsubject(X509 *cert, const char *match)
1014 const char *pos, *end;
1019 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1022 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1025 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1029 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1033 end = os_strchr(pos, ';');
1035 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1036 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1037 os_strncmp(end + 1, "URI:", 4) == 0)
1039 end = os_strchr(end + 1, ';');
1044 len = os_strlen(pos);
1045 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1054 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1057 case X509_V_ERR_CERT_REVOKED:
1058 return TLS_FAIL_REVOKED;
1059 case X509_V_ERR_CERT_NOT_YET_VALID:
1060 case X509_V_ERR_CRL_NOT_YET_VALID:
1061 return TLS_FAIL_NOT_YET_VALID;
1062 case X509_V_ERR_CERT_HAS_EXPIRED:
1063 case X509_V_ERR_CRL_HAS_EXPIRED:
1064 return TLS_FAIL_EXPIRED;
1065 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1066 case X509_V_ERR_UNABLE_TO_GET_CRL:
1067 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1068 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1069 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1070 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1071 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1072 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1073 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1074 case X509_V_ERR_INVALID_CA:
1075 return TLS_FAIL_UNTRUSTED;
1076 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1077 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1078 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1079 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1080 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1081 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1082 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1083 case X509_V_ERR_CERT_UNTRUSTED:
1084 case X509_V_ERR_CERT_REJECTED:
1085 return TLS_FAIL_BAD_CERTIFICATE;
1087 return TLS_FAIL_UNSPECIFIED;
1092 static struct wpabuf * get_x509_cert(X509 *cert)
1097 int cert_len = i2d_X509(cert, NULL);
1101 buf = wpabuf_alloc(cert_len);
1105 tmp = wpabuf_put(buf, cert_len);
1106 i2d_X509(cert, &tmp);
1111 static void openssl_tls_fail_event(struct tls_connection *conn,
1112 X509 *err_cert, int err, int depth,
1113 const char *subject, const char *err_str,
1114 enum tls_fail_reason reason)
1116 union tls_event_data ev;
1117 struct wpabuf *cert = NULL;
1119 if (tls_global->event_cb == NULL)
1122 cert = get_x509_cert(err_cert);
1123 os_memset(&ev, 0, sizeof(ev));
1124 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1125 reason : openssl_tls_fail_reason(err);
1126 ev.cert_fail.depth = depth;
1127 ev.cert_fail.subject = subject;
1128 ev.cert_fail.reason_txt = err_str;
1129 ev.cert_fail.cert = cert;
1130 tls_global->event_cb(tls_global->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1135 static void openssl_tls_cert_event(struct tls_connection *conn,
1136 X509 *err_cert, int depth,
1137 const char *subject)
1139 struct wpabuf *cert = NULL;
1140 union tls_event_data ev;
1141 #ifdef CONFIG_SHA256
1143 #endif /* CONFIG_SHA256 */
1145 if (tls_global->event_cb == NULL)
1148 os_memset(&ev, 0, sizeof(ev));
1149 if (conn->cert_probe || tls_global->cert_in_cb) {
1150 cert = get_x509_cert(err_cert);
1151 ev.peer_cert.cert = cert;
1153 #ifdef CONFIG_SHA256
1157 addr[0] = wpabuf_head(cert);
1158 len[0] = wpabuf_len(cert);
1159 if (sha256_vector(1, addr, len, hash) == 0) {
1160 ev.peer_cert.hash = hash;
1161 ev.peer_cert.hash_len = sizeof(hash);
1164 #endif /* CONFIG_SHA256 */
1165 ev.peer_cert.depth = depth;
1166 ev.peer_cert.subject = subject;
1167 tls_global->event_cb(tls_global->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1172 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1178 struct tls_connection *conn;
1179 char *match, *altmatch;
1180 const char *err_str;
1182 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1183 err = X509_STORE_CTX_get_error(x509_ctx);
1184 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1185 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1186 SSL_get_ex_data_X509_STORE_CTX_idx());
1187 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1189 conn = SSL_get_app_data(ssl);
1192 match = conn->subject_match;
1193 altmatch = conn->altsubject_match;
1195 if (!preverify_ok && !conn->ca_cert_verify)
1197 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1199 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1200 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1201 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1202 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1207 err_str = X509_verify_cert_error_string(err);
1209 #ifdef CONFIG_SHA256
1210 if (preverify_ok && depth == 0 && conn->server_cert_only) {
1211 struct wpabuf *cert;
1212 cert = get_x509_cert(err_cert);
1214 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1215 "server certificate data");
1221 addr[0] = wpabuf_head(cert);
1222 len[0] = wpabuf_len(cert);
1223 if (sha256_vector(1, addr, len, hash) < 0 ||
1224 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1225 err_str = "Server certificate mismatch";
1226 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1232 #endif /* CONFIG_SHA256 */
1234 if (!preverify_ok) {
1235 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1236 " error %d (%s) depth %d for '%s'", err, err_str,
1238 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1239 err_str, TLS_FAIL_UNSPECIFIED);
1240 return preverify_ok;
1243 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1244 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1245 preverify_ok, err, err_str,
1246 conn->ca_cert_verify, depth, buf);
1247 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1248 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1249 "match with '%s'", buf, match);
1251 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1253 TLS_FAIL_SUBJECT_MISMATCH);
1254 } else if (depth == 0 && altmatch &&
1255 !tls_match_altsubject(err_cert, altmatch)) {
1256 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1257 "'%s' not found", altmatch);
1259 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1260 "AltSubject mismatch",
1261 TLS_FAIL_ALTSUBJECT_MISMATCH);
1263 openssl_tls_cert_event(conn, err_cert, depth, buf);
1265 if (conn->cert_probe && preverify_ok && depth == 0) {
1266 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1267 "on probe-only run");
1269 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1270 "Server certificate chain probe",
1271 TLS_FAIL_SERVER_CHAIN_PROBE);
1274 return preverify_ok;
1278 #ifndef OPENSSL_NO_STDIO
1279 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1281 SSL_CTX *ssl_ctx = _ssl_ctx;
1282 X509_LOOKUP *lookup;
1285 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1286 X509_LOOKUP_file());
1287 if (lookup == NULL) {
1288 tls_show_errors(MSG_WARNING, __func__,
1289 "Failed add lookup for X509 store");
1293 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1294 unsigned long err = ERR_peek_error();
1295 tls_show_errors(MSG_WARNING, __func__,
1296 "Failed load CA in DER format");
1297 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1298 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1299 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1300 "cert already in hash table error",
1308 #endif /* OPENSSL_NO_STDIO */
1312 static BIO * BIO_from_keystore(const char *key)
1315 char value[KEYSTORE_MESSAGE_SIZE];
1316 int length = keystore_get(key, strlen(key), value);
1317 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
1318 BIO_write(bio, value, length);
1321 #endif /* ANDROID */
1324 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1325 const char *ca_cert, const u8 *ca_cert_blob,
1326 size_t ca_cert_blob_len, const char *ca_path)
1328 SSL_CTX *ssl_ctx = _ssl_ctx;
1331 * Remove previously configured trusted CA certificates before adding
1334 X509_STORE_free(ssl_ctx->cert_store);
1335 ssl_ctx->cert_store = X509_STORE_new();
1336 if (ssl_ctx->cert_store == NULL) {
1337 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1338 "certificate store", __func__);
1342 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1343 conn->ca_cert_verify = 1;
1345 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1346 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1348 conn->cert_probe = 1;
1349 conn->ca_cert_verify = 0;
1353 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1354 #ifdef CONFIG_SHA256
1355 const char *pos = ca_cert + 7;
1356 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1357 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1358 "hash value '%s'", ca_cert);
1362 if (os_strlen(pos) != 32 * 2) {
1363 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1364 "hash length in ca_cert '%s'", ca_cert);
1367 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1368 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1369 "value in ca_cert '%s'", ca_cert);
1372 conn->server_cert_only = 1;
1373 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1374 "certificate match");
1376 #else /* CONFIG_SHA256 */
1377 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1378 "cannot validate server certificate hash");
1380 #endif /* CONFIG_SHA256 */
1384 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1387 tls_show_errors(MSG_WARNING, __func__,
1388 "Failed to parse ca_cert_blob");
1392 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1393 unsigned long err = ERR_peek_error();
1394 tls_show_errors(MSG_WARNING, __func__,
1395 "Failed to add ca_cert_blob to "
1396 "certificate store");
1397 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1398 ERR_GET_REASON(err) ==
1399 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1400 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1401 "cert already in hash table error",
1409 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1410 "to certificate store", __func__);
1415 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1416 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1417 STACK_OF(X509_INFO) *stack = NULL;
1421 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1427 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1428 X509_INFO *info = sk_X509_INFO_value(stack, i);
1430 X509_STORE_add_cert(ssl_ctx->cert_store,
1434 X509_STORE_add_crl(ssl_ctx->cert_store,
1438 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1439 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1442 #endif /* ANDROID */
1444 #ifdef CONFIG_NATIVE_WINDOWS
1445 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1447 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1448 "system certificate store");
1451 #endif /* CONFIG_NATIVE_WINDOWS */
1453 if (ca_cert || ca_path) {
1454 #ifndef OPENSSL_NO_STDIO
1455 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1457 tls_show_errors(MSG_WARNING, __func__,
1458 "Failed to load root certificates");
1460 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1461 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1462 "DER format CA certificate",
1467 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1468 "certificate(s) loaded");
1469 tls_get_errors(ssl_ctx);
1471 #else /* OPENSSL_NO_STDIO */
1472 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1475 #endif /* OPENSSL_NO_STDIO */
1477 /* No ca_cert configured - do not try to verify server
1479 conn->ca_cert_verify = 0;
1486 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1489 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1491 tls_show_errors(MSG_WARNING, __func__,
1492 "Failed to load root certificates");
1496 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1497 "certificate(s) loaded");
1499 #ifndef OPENSSL_NO_STDIO
1500 /* Add the same CAs to the client certificate requests */
1501 SSL_CTX_set_client_CA_list(ssl_ctx,
1502 SSL_load_client_CA_file(ca_cert));
1503 #endif /* OPENSSL_NO_STDIO */
1510 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1515 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1517 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1518 "certificate store when enabling "
1522 flags = X509_V_FLAG_CRL_CHECK;
1524 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1525 X509_STORE_set_flags(cs, flags);
1531 static int tls_connection_set_subject_match(struct tls_connection *conn,
1532 const char *subject_match,
1533 const char *altsubject_match)
1535 os_free(conn->subject_match);
1536 conn->subject_match = NULL;
1537 if (subject_match) {
1538 conn->subject_match = os_strdup(subject_match);
1539 if (conn->subject_match == NULL)
1543 os_free(conn->altsubject_match);
1544 conn->altsubject_match = NULL;
1545 if (altsubject_match) {
1546 conn->altsubject_match = os_strdup(altsubject_match);
1547 if (conn->altsubject_match == NULL)
1555 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1558 static int counter = 0;
1564 conn->ca_cert_verify = 1;
1565 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1566 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1567 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1569 conn->ca_cert_verify = 0;
1570 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1573 SSL_set_accept_state(conn->ssl);
1576 * Set session id context in order to avoid fatal errors when client
1577 * tries to resume a session. However, set the context to a unique
1578 * value in order to effectively disable session resumption for now
1579 * since not all areas of the server code are ready for it (e.g.,
1580 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1584 SSL_set_session_id_context(conn->ssl,
1585 (const unsigned char *) &counter,
1592 static int tls_connection_client_cert(struct tls_connection *conn,
1593 const char *client_cert,
1594 const u8 *client_cert_blob,
1595 size_t client_cert_blob_len)
1597 if (client_cert == NULL && client_cert_blob == NULL)
1600 if (client_cert_blob &&
1601 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1602 client_cert_blob_len) == 1) {
1603 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1606 } else if (client_cert_blob) {
1607 tls_show_errors(MSG_DEBUG, __func__,
1608 "SSL_use_certificate_ASN1 failed");
1611 if (client_cert == NULL)
1615 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1616 BIO *bio = BIO_from_keystore(&client_cert[11]);
1620 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1624 if (SSL_use_certificate(conn->ssl, x509) == 1)
1630 #endif /* ANDROID */
1632 #ifndef OPENSSL_NO_STDIO
1633 if (SSL_use_certificate_file(conn->ssl, client_cert,
1634 SSL_FILETYPE_ASN1) == 1) {
1635 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1640 if (SSL_use_certificate_file(conn->ssl, client_cert,
1641 SSL_FILETYPE_PEM) == 1) {
1643 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1648 tls_show_errors(MSG_DEBUG, __func__,
1649 "SSL_use_certificate_file failed");
1650 #else /* OPENSSL_NO_STDIO */
1651 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1652 #endif /* OPENSSL_NO_STDIO */
1658 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1660 #ifndef OPENSSL_NO_STDIO
1661 if (client_cert == NULL)
1664 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1665 SSL_FILETYPE_ASN1) != 1 &&
1666 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1667 SSL_FILETYPE_PEM) != 1) {
1668 tls_show_errors(MSG_INFO, __func__,
1669 "Failed to load client certificate");
1673 #else /* OPENSSL_NO_STDIO */
1674 if (client_cert == NULL)
1676 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1678 #endif /* OPENSSL_NO_STDIO */
1682 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1684 if (password == NULL) {
1687 os_strlcpy(buf, (char *) password, size);
1688 return os_strlen(buf);
1693 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1698 STACK_OF(X509) *certs;
1705 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1706 tls_show_errors(MSG_DEBUG, __func__,
1707 "Failed to parse PKCS12 file");
1711 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1714 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1716 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1717 "subject='%s'", buf);
1719 if (SSL_use_certificate(ssl, cert) != 1)
1722 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1729 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1731 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1734 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1737 EVP_PKEY_free(pkey);
1741 while ((cert = sk_X509_pop(certs)) != NULL) {
1742 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1744 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1745 " from PKCS12: subject='%s'", buf);
1747 * There is no SSL equivalent for the chain cert - so
1748 * always add it to the context...
1750 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1755 sk_X509_free(certs);
1761 tls_get_errors(ssl_ctx);
1765 #endif /* PKCS12_FUNCS */
1768 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1775 f = fopen(private_key, "rb");
1779 p12 = d2i_PKCS12_fp(f, NULL);
1783 tls_show_errors(MSG_INFO, __func__,
1784 "Failed to use PKCS#12 file");
1788 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1790 #else /* PKCS12_FUNCS */
1791 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1794 #endif /* PKCS12_FUNCS */
1798 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1799 const u8 *blob, size_t len, const char *passwd)
1804 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1806 tls_show_errors(MSG_INFO, __func__,
1807 "Failed to use PKCS#12 blob");
1811 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1813 #else /* PKCS12_FUNCS */
1814 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1817 #endif /* PKCS12_FUNCS */
1821 #ifndef OPENSSL_NO_ENGINE
1822 static int tls_engine_get_cert(struct tls_connection *conn,
1823 const char *cert_id,
1826 /* this runs after the private key is loaded so no PIN is required */
1828 const char *cert_id;
1831 params.cert_id = cert_id;
1834 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1835 0, ¶ms, NULL, 1)) {
1836 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1837 " '%s' [%s]", cert_id,
1838 ERR_error_string(ERR_get_error(), NULL));
1839 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1842 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1844 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1846 *cert = params.cert;
1849 #endif /* OPENSSL_NO_ENGINE */
1852 static int tls_connection_engine_client_cert(struct tls_connection *conn,
1853 const char *cert_id)
1855 #ifndef OPENSSL_NO_ENGINE
1858 if (tls_engine_get_cert(conn, cert_id, &cert))
1861 if (!SSL_use_certificate(conn->ssl, cert)) {
1862 tls_show_errors(MSG_ERROR, __func__,
1863 "SSL_use_certificate failed");
1868 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1872 #else /* OPENSSL_NO_ENGINE */
1874 #endif /* OPENSSL_NO_ENGINE */
1878 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1879 struct tls_connection *conn,
1880 const char *ca_cert_id)
1882 #ifndef OPENSSL_NO_ENGINE
1884 SSL_CTX *ssl_ctx = _ssl_ctx;
1886 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1889 /* start off the same as tls_connection_ca_cert */
1890 X509_STORE_free(ssl_ctx->cert_store);
1891 ssl_ctx->cert_store = X509_STORE_new();
1892 if (ssl_ctx->cert_store == NULL) {
1893 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1894 "certificate store", __func__);
1898 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1899 unsigned long err = ERR_peek_error();
1900 tls_show_errors(MSG_WARNING, __func__,
1901 "Failed to add CA certificate from engine "
1902 "to certificate store");
1903 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1904 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1905 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1906 " already in hash table error",
1914 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1915 "to certificate store", __func__);
1916 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1919 #else /* OPENSSL_NO_ENGINE */
1921 #endif /* OPENSSL_NO_ENGINE */
1925 static int tls_connection_engine_private_key(struct tls_connection *conn)
1927 #ifndef OPENSSL_NO_ENGINE
1928 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1929 tls_show_errors(MSG_ERROR, __func__,
1930 "ENGINE: cannot use private key for TLS");
1933 if (!SSL_check_private_key(conn->ssl)) {
1934 tls_show_errors(MSG_INFO, __func__,
1935 "Private key failed verification");
1939 #else /* OPENSSL_NO_ENGINE */
1940 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1941 "engine support was not compiled in");
1943 #endif /* OPENSSL_NO_ENGINE */
1947 static int tls_connection_private_key(void *_ssl_ctx,
1948 struct tls_connection *conn,
1949 const char *private_key,
1950 const char *private_key_passwd,
1951 const u8 *private_key_blob,
1952 size_t private_key_blob_len)
1954 SSL_CTX *ssl_ctx = _ssl_ctx;
1958 if (private_key == NULL && private_key_blob == NULL)
1961 if (private_key_passwd) {
1962 passwd = os_strdup(private_key_passwd);
1968 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1969 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1972 while (private_key_blob) {
1973 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1974 (u8 *) private_key_blob,
1975 private_key_blob_len) == 1) {
1976 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1977 "ASN1(EVP_PKEY_RSA) --> OK");
1982 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1983 (u8 *) private_key_blob,
1984 private_key_blob_len) == 1) {
1985 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1986 "ASN1(EVP_PKEY_DSA) --> OK");
1991 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1992 (u8 *) private_key_blob,
1993 private_key_blob_len) == 1) {
1994 wpa_printf(MSG_DEBUG, "OpenSSL: "
1995 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2000 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2001 private_key_blob_len, passwd) == 0) {
2002 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2012 if (!ok && private_key &&
2013 os_strncmp("keystore://", private_key, 11) == 0) {
2014 BIO *bio = BIO_from_keystore(&private_key[11]);
2015 EVP_PKEY *pkey = NULL;
2017 pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
2021 if (SSL_use_PrivateKey(conn->ssl, pkey) == 1) {
2022 wpa_printf(MSG_DEBUG, "OpenSSL: Private key "
2026 EVP_PKEY_free(pkey);
2029 #endif /* ANDROID */
2031 while (!ok && private_key) {
2032 #ifndef OPENSSL_NO_STDIO
2033 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2034 SSL_FILETYPE_ASN1) == 1) {
2035 wpa_printf(MSG_DEBUG, "OpenSSL: "
2036 "SSL_use_PrivateKey_File (DER) --> OK");
2041 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2042 SSL_FILETYPE_PEM) == 1) {
2043 wpa_printf(MSG_DEBUG, "OpenSSL: "
2044 "SSL_use_PrivateKey_File (PEM) --> OK");
2048 #else /* OPENSSL_NO_STDIO */
2049 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2051 #endif /* OPENSSL_NO_STDIO */
2053 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2055 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2061 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2062 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2063 "access certificate store --> OK");
2072 tls_show_errors(MSG_INFO, __func__,
2073 "Failed to load private key");
2078 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2081 if (!SSL_check_private_key(conn->ssl)) {
2082 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2087 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2092 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2093 const char *private_key_passwd)
2097 if (private_key == NULL)
2100 if (private_key_passwd) {
2101 passwd = os_strdup(private_key_passwd);
2107 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2108 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2110 #ifndef OPENSSL_NO_STDIO
2111 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2112 SSL_FILETYPE_ASN1) != 1 &&
2113 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2114 SSL_FILETYPE_PEM) != 1 &&
2115 #endif /* OPENSSL_NO_STDIO */
2116 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2117 tls_show_errors(MSG_INFO, __func__,
2118 "Failed to load private key");
2125 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2127 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2128 tls_show_errors(MSG_INFO, __func__,
2129 "Private key failed verification");
2137 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2139 #ifdef OPENSSL_NO_DH
2140 if (dh_file == NULL)
2142 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2143 "dh_file specified");
2145 #else /* OPENSSL_NO_DH */
2149 /* TODO: add support for dh_blob */
2150 if (dh_file == NULL)
2155 bio = BIO_new_file(dh_file, "r");
2157 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2158 dh_file, ERR_error_string(ERR_get_error(), NULL));
2161 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2163 #ifndef OPENSSL_NO_DSA
2164 while (dh == NULL) {
2166 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2167 " trying to parse as DSA params", dh_file,
2168 ERR_error_string(ERR_get_error(), NULL));
2169 bio = BIO_new_file(dh_file, "r");
2172 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2175 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2176 "'%s': %s", dh_file,
2177 ERR_error_string(ERR_get_error(), NULL));
2181 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2182 dh = DSA_dup_DH(dsa);
2185 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2186 "params into DH params");
2191 #endif /* !OPENSSL_NO_DSA */
2193 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2198 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2199 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2201 ERR_error_string(ERR_get_error(), NULL));
2207 #endif /* OPENSSL_NO_DH */
2211 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2213 #ifdef OPENSSL_NO_DH
2214 if (dh_file == NULL)
2216 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2217 "dh_file specified");
2219 #else /* OPENSSL_NO_DH */
2223 /* TODO: add support for dh_blob */
2224 if (dh_file == NULL)
2226 if (ssl_ctx == NULL)
2229 bio = BIO_new_file(dh_file, "r");
2231 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2232 dh_file, ERR_error_string(ERR_get_error(), NULL));
2235 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2237 #ifndef OPENSSL_NO_DSA
2238 while (dh == NULL) {
2240 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2241 " trying to parse as DSA params", dh_file,
2242 ERR_error_string(ERR_get_error(), NULL));
2243 bio = BIO_new_file(dh_file, "r");
2246 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2249 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2250 "'%s': %s", dh_file,
2251 ERR_error_string(ERR_get_error(), NULL));
2255 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2256 dh = DSA_dup_DH(dsa);
2259 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2260 "params into DH params");
2265 #endif /* !OPENSSL_NO_DSA */
2267 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2272 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2273 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2275 ERR_error_string(ERR_get_error(), NULL));
2281 #endif /* OPENSSL_NO_DH */
2285 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2286 struct tls_keys *keys)
2290 if (conn == NULL || keys == NULL)
2293 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2296 os_memset(keys, 0, sizeof(*keys));
2297 keys->master_key = ssl->session->master_key;
2298 keys->master_key_len = ssl->session->master_key_length;
2299 keys->client_random = ssl->s3->client_random;
2300 keys->client_random_len = SSL3_RANDOM_SIZE;
2301 keys->server_random = ssl->s3->server_random;
2302 keys->server_random_len = SSL3_RANDOM_SIZE;
2308 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2309 const char *label, int server_random_first,
2310 u8 *out, size_t out_len)
2316 static struct wpabuf *
2317 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2321 struct wpabuf *out_data;
2324 * Give TLS handshake data from the server (if available) to OpenSSL
2328 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2330 tls_show_errors(MSG_INFO, __func__,
2331 "Handshake failed - BIO_write");
2335 /* Initiate TLS handshake or continue the existing handshake */
2337 res = SSL_accept(conn->ssl);
2339 res = SSL_connect(conn->ssl);
2341 int err = SSL_get_error(conn->ssl, res);
2342 if (err == SSL_ERROR_WANT_READ)
2343 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2345 else if (err == SSL_ERROR_WANT_WRITE)
2346 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2349 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2354 /* Get the TLS handshake data to be sent to the server */
2355 res = BIO_ctrl_pending(conn->ssl_out);
2356 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2357 out_data = wpabuf_alloc(res);
2358 if (out_data == NULL) {
2359 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2360 "handshake output (%d bytes)", res);
2361 if (BIO_reset(conn->ssl_out) < 0) {
2362 tls_show_errors(MSG_INFO, __func__,
2363 "BIO_reset failed");
2367 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2370 tls_show_errors(MSG_INFO, __func__,
2371 "Handshake failed - BIO_read");
2372 if (BIO_reset(conn->ssl_out) < 0) {
2373 tls_show_errors(MSG_INFO, __func__,
2374 "BIO_reset failed");
2376 wpabuf_free(out_data);
2379 wpabuf_put(out_data, res);
2385 static struct wpabuf *
2386 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2388 struct wpabuf *appl_data;
2391 appl_data = wpabuf_alloc(max_len + 100);
2392 if (appl_data == NULL)
2395 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2396 wpabuf_size(appl_data));
2398 int err = SSL_get_error(conn->ssl, res);
2399 if (err == SSL_ERROR_WANT_READ ||
2400 err == SSL_ERROR_WANT_WRITE) {
2401 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2404 tls_show_errors(MSG_INFO, __func__,
2405 "Failed to read possible "
2406 "Application Data");
2408 wpabuf_free(appl_data);
2412 wpabuf_put(appl_data, res);
2413 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2414 "message", appl_data);
2420 static struct wpabuf *
2421 openssl_connection_handshake(struct tls_connection *conn,
2422 const struct wpabuf *in_data,
2423 struct wpabuf **appl_data, int server)
2425 struct wpabuf *out_data;
2430 out_data = openssl_handshake(conn, in_data, server);
2431 if (out_data == NULL)
2434 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2435 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2442 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2443 const struct wpabuf *in_data,
2444 struct wpabuf **appl_data)
2446 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2450 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2451 struct tls_connection *conn,
2452 const struct wpabuf *in_data,
2453 struct wpabuf **appl_data)
2455 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2459 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2460 struct tls_connection *conn,
2461 const struct wpabuf *in_data)
2469 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2470 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2471 (res = BIO_reset(conn->ssl_out)) < 0) {
2472 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2475 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2477 tls_show_errors(MSG_INFO, __func__,
2478 "Encryption failed - SSL_write");
2482 /* Read encrypted data to be sent to the server */
2483 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2486 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2488 tls_show_errors(MSG_INFO, __func__,
2489 "Encryption failed - BIO_read");
2493 wpabuf_put(buf, res);
2499 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2500 struct tls_connection *conn,
2501 const struct wpabuf *in_data)
2506 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2507 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2508 wpabuf_len(in_data));
2510 tls_show_errors(MSG_INFO, __func__,
2511 "Decryption failed - BIO_write");
2514 if (BIO_reset(conn->ssl_out) < 0) {
2515 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2519 /* Read decrypted data for further processing */
2521 * Even though we try to disable TLS compression, it is possible that
2522 * this cannot be done with all TLS libraries. Add extra buffer space
2523 * to handle the possibility of the decrypted data being longer than
2526 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2529 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2531 tls_show_errors(MSG_INFO, __func__,
2532 "Decryption failed - SSL_read");
2536 wpabuf_put(buf, res);
2542 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2544 return conn ? conn->ssl->hit : 0;
2548 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2551 char buf[100], *pos, *end;
2555 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2560 end = pos + sizeof(buf);
2563 while (*c != TLS_CIPHER_NONE) {
2567 case TLS_CIPHER_RC4_SHA:
2570 case TLS_CIPHER_AES128_SHA:
2571 suite = "AES128-SHA";
2573 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2574 suite = "DHE-RSA-AES128-SHA";
2576 case TLS_CIPHER_ANON_DH_AES128_SHA:
2577 suite = "ADH-AES128-SHA";
2580 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2581 "cipher selection: %d", *c);
2584 ret = os_snprintf(pos, end - pos, ":%s", suite);
2585 if (ret < 0 || ret >= end - pos)
2592 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2594 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2595 tls_show_errors(MSG_INFO, __func__,
2596 "Cipher suite configuration failed");
2604 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2605 char *buf, size_t buflen)
2608 if (conn == NULL || conn->ssl == NULL)
2611 name = SSL_get_cipher(conn->ssl);
2615 os_strlcpy(buf, name, buflen);
2620 int tls_connection_enable_workaround(void *ssl_ctx,
2621 struct tls_connection *conn)
2623 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2629 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2630 /* ClientHello TLS extensions require a patch to openssl, so this function is
2631 * commented out unless explicitly needed for EAP-FAST in order to be able to
2632 * build this file with unmodified openssl. */
2633 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2634 int ext_type, const u8 *data,
2637 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2640 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2641 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2644 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2645 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2648 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2652 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2655 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2659 return conn->failed;
2663 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2667 return conn->read_alerts;
2671 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2675 return conn->write_alerts;
2679 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2680 const struct tls_connection_params *params)
2688 while ((err = ERR_get_error())) {
2689 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2690 __func__, ERR_error_string(err, NULL));
2693 if (params->engine) {
2694 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2695 ret = tls_engine_init(conn, params->engine_id, params->pin,
2696 params->key_id, params->cert_id,
2697 params->ca_cert_id);
2701 if (tls_connection_set_subject_match(conn,
2702 params->subject_match,
2703 params->altsubject_match))
2706 if (params->engine && params->ca_cert_id) {
2707 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2708 params->ca_cert_id))
2709 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2710 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2711 params->ca_cert_blob,
2712 params->ca_cert_blob_len,
2716 if (params->engine && params->cert_id) {
2717 if (tls_connection_engine_client_cert(conn, params->cert_id))
2718 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2719 } else if (tls_connection_client_cert(conn, params->client_cert,
2720 params->client_cert_blob,
2721 params->client_cert_blob_len))
2724 if (params->engine && params->key_id) {
2725 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2726 if (tls_connection_engine_private_key(conn))
2727 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2728 } else if (tls_connection_private_key(tls_ctx, conn,
2729 params->private_key,
2730 params->private_key_passwd,
2731 params->private_key_blob,
2732 params->private_key_blob_len)) {
2733 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2734 params->private_key);
2738 if (tls_connection_dh(conn, params->dh_file)) {
2739 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2744 conn->flags = params->flags;
2746 tls_get_errors(tls_ctx);
2752 int tls_global_set_params(void *tls_ctx,
2753 const struct tls_connection_params *params)
2755 SSL_CTX *ssl_ctx = tls_ctx;
2758 while ((err = ERR_get_error())) {
2759 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2760 __func__, ERR_error_string(err, NULL));
2763 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2766 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2769 if (tls_global_private_key(ssl_ctx, params->private_key,
2770 params->private_key_passwd))
2773 if (tls_global_dh(ssl_ctx, params->dh_file)) {
2774 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2783 int tls_connection_get_keyblock_size(void *tls_ctx,
2784 struct tls_connection *conn)
2786 const EVP_CIPHER *c;
2789 if (conn == NULL || conn->ssl == NULL ||
2790 conn->ssl->enc_read_ctx == NULL ||
2791 conn->ssl->enc_read_ctx->cipher == NULL ||
2792 conn->ssl->read_hash == NULL)
2795 c = conn->ssl->enc_read_ctx->cipher;
2796 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2797 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2799 h = conn->ssl->read_hash;
2802 return 2 * (EVP_CIPHER_key_length(c) +
2804 EVP_CIPHER_iv_length(c));
2808 unsigned int tls_capabilities(void *tls_ctx)
2814 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2815 /* Pre-shared secred requires a patch to openssl, so this function is
2816 * commented out unless explicitly needed for EAP-FAST in order to be able to
2817 * build this file with unmodified openssl. */
2819 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2820 STACK_OF(SSL_CIPHER) *peer_ciphers,
2821 SSL_CIPHER **cipher, void *arg)
2823 struct tls_connection *conn = arg;
2826 if (conn == NULL || conn->session_ticket_cb == NULL)
2829 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2830 conn->session_ticket,
2831 conn->session_ticket_len,
2832 s->s3->client_random,
2833 s->s3->server_random, secret);
2834 os_free(conn->session_ticket);
2835 conn->session_ticket = NULL;
2840 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2845 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2846 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
2849 struct tls_connection *conn = arg;
2851 if (conn == NULL || conn->session_ticket_cb == NULL)
2854 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
2856 os_free(conn->session_ticket);
2857 conn->session_ticket = NULL;
2859 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2860 "extension", data, len);
2862 conn->session_ticket = os_malloc(len);
2863 if (conn->session_ticket == NULL)
2866 os_memcpy(conn->session_ticket, data, len);
2867 conn->session_ticket_len = len;
2871 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2872 #ifdef SSL_OP_NO_TICKET
2873 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2874 unsigned char *data, int len, void *arg)
2876 struct tls_connection *conn = arg;
2878 if (conn == NULL || conn->session_ticket_cb == NULL)
2881 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2884 if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2885 os_free(conn->session_ticket);
2886 conn->session_ticket = NULL;
2888 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2889 "extension", data, len);
2890 conn->session_ticket = os_malloc(len);
2891 if (conn->session_ticket == NULL)
2894 os_memcpy(conn->session_ticket, data, len);
2895 conn->session_ticket_len = len;
2898 #else /* SSL_OP_NO_TICKET */
2899 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2901 struct tls_connection *conn = arg;
2903 if (conn == NULL || conn->session_ticket_cb == NULL)
2906 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2907 ext->type, ext->length);
2909 os_free(conn->session_ticket);
2910 conn->session_ticket = NULL;
2912 if (ext->type == 35) {
2913 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2914 "extension", ext->data, ext->length);
2915 conn->session_ticket = os_malloc(ext->length);
2916 if (conn->session_ticket == NULL)
2917 return SSL_AD_INTERNAL_ERROR;
2919 os_memcpy(conn->session_ticket, ext->data, ext->length);
2920 conn->session_ticket_len = ext->length;
2925 #endif /* SSL_OP_NO_TICKET */
2926 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2927 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2930 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2931 struct tls_connection *conn,
2932 tls_session_ticket_cb cb,
2935 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2936 conn->session_ticket_cb = cb;
2937 conn->session_ticket_cb_ctx = ctx;
2940 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2943 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2944 SSL_set_session_ticket_ext_cb(conn->ssl,
2945 tls_session_ticket_ext_cb, conn);
2946 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2947 #ifdef SSL_OP_NO_TICKET
2948 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2949 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2950 #else /* SSL_OP_NO_TICKET */
2951 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2954 #endif /* SSL_OP_NO_TICKET */
2955 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2957 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2959 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2960 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
2961 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2962 #ifdef SSL_OP_NO_TICKET
2963 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2964 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2965 #else /* SSL_OP_NO_TICKET */
2966 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2968 #endif /* SSL_OP_NO_TICKET */
2969 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2973 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2975 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */