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);
64 static struct tls_global *tls_global = NULL;
67 struct tls_connection {
69 BIO *ssl_in, *ssl_out;
70 #ifndef OPENSSL_NO_ENGINE
71 ENGINE *engine; /* functional reference to the engine */
72 EVP_PKEY *private_key; /* the private key if using engine */
73 #endif /* OPENSSL_NO_ENGINE */
74 char *subject_match, *altsubject_match;
75 int read_alerts, write_alerts, failed;
77 tls_session_ticket_cb session_ticket_cb;
78 void *session_ticket_cb_ctx;
80 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
82 size_t session_ticket_len;
84 unsigned int ca_cert_verify:1;
85 unsigned int cert_probe:1;
86 unsigned int server_cert_only:1;
94 #ifdef CONFIG_NO_STDOUT_DEBUG
96 static void _tls_show_errors(void)
100 while ((err = ERR_get_error())) {
101 /* Just ignore the errors, since stdout is disabled */
104 #define tls_show_errors(l, f, t) _tls_show_errors()
106 #else /* CONFIG_NO_STDOUT_DEBUG */
108 static void tls_show_errors(int level, const char *func, const char *txt)
112 wpa_printf(level, "OpenSSL: %s - %s %s",
113 func, txt, ERR_error_string(ERR_get_error(), NULL));
115 while ((err = ERR_get_error())) {
116 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
117 ERR_error_string(err, NULL));
121 #endif /* CONFIG_NO_STDOUT_DEBUG */
124 #ifdef CONFIG_NATIVE_WINDOWS
126 /* Windows CryptoAPI and access to certificate stores */
127 #include <wincrypt.h>
129 #ifdef __MINGW32_VERSION
131 * MinGW does not yet include all the needed definitions for CryptoAPI, so
132 * define here whatever extra is needed.
134 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
135 #define CERT_STORE_READONLY_FLAG 0x00008000
136 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
138 #endif /* __MINGW32_VERSION */
141 struct cryptoapi_rsa_data {
142 const CERT_CONTEXT *cert;
143 HCRYPTPROV crypt_prov;
145 BOOL free_crypt_prov;
149 static void cryptoapi_error(const char *msg)
151 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
152 msg, (unsigned int) GetLastError());
156 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
157 unsigned char *to, RSA *rsa, int padding)
159 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
164 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
165 unsigned char *to, RSA *rsa, int padding)
167 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
172 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
173 unsigned char *to, RSA *rsa, int padding)
175 struct cryptoapi_rsa_data *priv =
176 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
178 DWORD hash_size, len, i;
179 unsigned char *buf = NULL;
183 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
184 ERR_R_PASSED_NULL_PARAMETER);
188 if (padding != RSA_PKCS1_PADDING) {
189 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
190 RSA_R_UNKNOWN_PADDING_TYPE);
194 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
195 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
197 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
198 RSA_R_INVALID_MESSAGE_LENGTH);
202 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
204 cryptoapi_error("CryptCreateHash failed");
208 len = sizeof(hash_size);
209 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
211 cryptoapi_error("CryptGetHashParam failed");
215 if ((int) hash_size != flen) {
216 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
217 (unsigned) hash_size, flen);
218 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
219 RSA_R_INVALID_MESSAGE_LENGTH);
222 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
223 cryptoapi_error("CryptSetHashParam failed");
228 buf = os_malloc(len);
230 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
234 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
235 cryptoapi_error("CryptSignHash failed");
239 for (i = 0; i < len; i++)
240 to[i] = buf[len - i - 1];
245 CryptDestroyHash(hash);
251 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
252 unsigned char *to, RSA *rsa, int padding)
254 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
259 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
263 if (priv->crypt_prov && priv->free_crypt_prov)
264 CryptReleaseContext(priv->crypt_prov, 0);
266 CertFreeCertificateContext(priv->cert);
271 static int cryptoapi_finish(RSA *rsa)
273 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
274 os_free((void *) rsa->meth);
280 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
283 const CERT_CONTEXT *ret = NULL;
285 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
286 store | CERT_STORE_OPEN_EXISTING_FLAG |
287 CERT_STORE_READONLY_FLAG, L"MY");
289 cryptoapi_error("Failed to open 'My system store'");
293 if (strncmp(name, "cert://", 7) == 0) {
294 unsigned short wbuf[255];
295 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
296 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
298 0, CERT_FIND_SUBJECT_STR,
300 } else if (strncmp(name, "hash://", 7) == 0) {
301 CRYPT_HASH_BLOB blob;
303 const char *hash = name + 7;
306 len = os_strlen(hash) / 2;
307 buf = os_malloc(len);
308 if (buf && hexstr2bin(hash, buf, len) == 0) {
311 ret = CertFindCertificateInStore(cs,
320 CertCloseStore(cs, 0);
326 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
329 RSA *rsa = NULL, *pub_rsa;
330 struct cryptoapi_rsa_data *priv;
331 RSA_METHOD *rsa_meth;
334 (strncmp(name, "cert://", 7) != 0 &&
335 strncmp(name, "hash://", 7) != 0))
338 priv = os_zalloc(sizeof(*priv));
339 rsa_meth = os_zalloc(sizeof(*rsa_meth));
340 if (priv == NULL || rsa_meth == NULL) {
341 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
342 "for CryptoAPI RSA method");
348 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
349 if (priv->cert == NULL) {
350 priv->cert = cryptoapi_find_cert(
351 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
353 if (priv->cert == NULL) {
354 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
359 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
360 priv->cert->cbCertEncoded);
362 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
367 if (!CryptAcquireCertificatePrivateKey(priv->cert,
368 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
369 NULL, &priv->crypt_prov,
371 &priv->free_crypt_prov)) {
372 cryptoapi_error("Failed to acquire a private key for the "
377 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
378 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
379 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
380 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
381 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
382 rsa_meth->finish = cryptoapi_finish;
383 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
384 rsa_meth->app_data = (char *) priv;
388 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
389 ERR_R_MALLOC_FAILURE);
393 if (!SSL_use_certificate(ssl, cert)) {
398 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
402 rsa->n = BN_dup(pub_rsa->n);
403 rsa->e = BN_dup(pub_rsa->e);
404 if (!RSA_set_method(rsa, rsa_meth))
407 if (!SSL_use_RSAPrivateKey(ssl, rsa))
420 cryptoapi_free_data(priv);
426 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
429 PCCERT_CONTEXT ctx = NULL;
437 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
442 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
445 wsprintf(wstore, L"%S", store);
446 cs = CertOpenSystemStore(0, wstore);
449 cs = CertOpenSystemStore(0, store);
452 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
453 "'%s': error=%d", __func__, store,
454 (int) GetLastError());
458 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
459 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
462 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
463 "X509 DER encoding for CA cert");
467 X509_NAME_oneline(X509_get_subject_name(cert), buf,
469 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
470 "system certificate store: subject='%s'", buf);
472 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
473 tls_show_errors(MSG_WARNING, __func__,
474 "Failed to add ca_cert to OpenSSL "
475 "certificate store");
481 if (!CertCloseStore(cs, 0)) {
482 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
483 "'%s': error=%d", __func__, name + 13,
484 (int) GetLastError());
491 #else /* CONFIG_NATIVE_WINDOWS */
493 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
498 #endif /* CONFIG_NATIVE_WINDOWS */
501 static void ssl_info_cb(const SSL *ssl, int where, int ret)
506 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
507 w = where & ~SSL_ST_MASK;
508 if (w & SSL_ST_CONNECT)
510 else if (w & SSL_ST_ACCEPT)
515 if (where & SSL_CB_LOOP) {
516 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
517 str, SSL_state_string_long(ssl));
518 } else if (where & SSL_CB_ALERT) {
519 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
520 where & SSL_CB_READ ?
521 "read (remote end reported an error)" :
522 "write (local SSL3 detected an error)",
523 SSL_alert_type_string_long(ret),
524 SSL_alert_desc_string_long(ret));
525 if ((ret >> 8) == SSL3_AL_FATAL) {
526 struct tls_connection *conn =
527 SSL_get_app_data((SSL *) ssl);
528 if (where & SSL_CB_READ)
531 conn->write_alerts++;
533 } else if (where & SSL_CB_EXIT && ret <= 0) {
534 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
535 str, ret == 0 ? "failed" : "error",
536 SSL_state_string_long(ssl));
541 #ifndef OPENSSL_NO_ENGINE
543 * tls_engine_load_dynamic_generic - load any openssl engine
544 * @pre: an array of commands and values that load an engine initialized
545 * in the engine specific function
546 * @post: an array of commands and values that initialize an already loaded
547 * engine (or %NULL if not required)
548 * @id: the engine id of the engine to load (only required if post is not %NULL
550 * This function is a generic function that loads any openssl engine.
552 * Returns: 0 on success, -1 on failure
554 static int tls_engine_load_dynamic_generic(const char *pre[],
555 const char *post[], const char *id)
558 const char *dynamic_id = "dynamic";
560 engine = ENGINE_by_id(id);
563 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
569 engine = ENGINE_by_id(dynamic_id);
570 if (engine == NULL) {
571 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
573 ERR_error_string(ERR_get_error(), NULL));
577 /* Perform the pre commands. This will load the engine. */
578 while (pre && pre[0]) {
579 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
580 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
581 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
582 "%s %s [%s]", pre[0], pre[1],
583 ERR_error_string(ERR_get_error(), NULL));
591 * Free the reference to the "dynamic" engine. The loaded engine can
592 * now be looked up using ENGINE_by_id().
596 engine = ENGINE_by_id(id);
597 if (engine == NULL) {
598 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
599 id, ERR_error_string(ERR_get_error(), NULL));
603 while (post && post[0]) {
604 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
605 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
606 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
607 " %s %s [%s]", post[0], post[1],
608 ERR_error_string(ERR_get_error(), NULL));
609 ENGINE_remove(engine);
622 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
623 * @pkcs11_so_path: pksc11_so_path from the configuration
624 * @pcks11_module_path: pkcs11_module_path from the configuration
626 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
627 const char *pkcs11_module_path)
629 char *engine_id = "pkcs11";
630 const char *pre_cmd[] = {
631 "SO_PATH", NULL /* pkcs11_so_path */,
632 "ID", NULL /* engine_id */,
634 /* "NO_VCHECK", "1", */
638 const char *post_cmd[] = {
639 "MODULE_PATH", NULL /* pkcs11_module_path */,
643 if (!pkcs11_so_path || !pkcs11_module_path)
646 pre_cmd[1] = pkcs11_so_path;
647 pre_cmd[3] = engine_id;
648 post_cmd[1] = pkcs11_module_path;
650 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
653 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
658 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
659 * @opensc_so_path: opensc_so_path from the configuration
661 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
663 char *engine_id = "opensc";
664 const char *pre_cmd[] = {
665 "SO_PATH", NULL /* opensc_so_path */,
666 "ID", NULL /* engine_id */,
675 pre_cmd[1] = opensc_so_path;
676 pre_cmd[3] = engine_id;
678 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
681 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
683 #endif /* OPENSSL_NO_ENGINE */
686 void * tls_init(const struct tls_config *conf)
690 if (tls_openssl_ref_count == 0) {
691 tls_global = os_zalloc(sizeof(*tls_global));
692 if (tls_global == NULL)
695 tls_global->event_cb = conf->event_cb;
696 tls_global->cb_ctx = conf->cb_ctx;
701 if (conf && conf->fips_mode) {
702 if (!FIPS_mode_set(1)) {
703 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
705 ERR_load_crypto_strings();
706 ERR_print_errors_fp(stderr);
709 wpa_printf(MSG_INFO, "Running in FIPS mode");
711 #else /* OPENSSL_FIPS */
712 if (conf && conf->fips_mode) {
713 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
717 #endif /* OPENSSL_FIPS */
718 #endif /* CONFIG_FIPS */
719 SSL_load_error_strings();
721 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
722 EVP_add_digest(EVP_sha256());
723 #endif /* OPENSSL_NO_SHA256 */
724 /* TODO: if /dev/urandom is available, PRNG is seeded
725 * automatically. If this is not the case, random data should
729 #ifndef OPENSSL_NO_RC2
731 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
732 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
733 * versions, but it looks like OpenSSL 1.0.0 does not do that
736 EVP_add_cipher(EVP_rc2_40_cbc());
737 #endif /* OPENSSL_NO_RC2 */
739 #endif /* PKCS12_FUNCS */
741 tls_openssl_ref_count++;
743 ssl = SSL_CTX_new(TLSv1_method());
747 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
749 #ifndef OPENSSL_NO_ENGINE
751 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
752 conf->pkcs11_module_path)) {
753 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
754 ERR_load_ENGINE_strings();
755 ENGINE_load_dynamic();
757 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
758 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
759 conf->pkcs11_module_path)) {
764 #endif /* OPENSSL_NO_ENGINE */
770 void tls_deinit(void *ssl_ctx)
772 SSL_CTX *ssl = ssl_ctx;
775 tls_openssl_ref_count--;
776 if (tls_openssl_ref_count == 0) {
777 #ifndef OPENSSL_NO_ENGINE
779 #endif /* OPENSSL_NO_ENGINE */
780 CRYPTO_cleanup_all_ex_data();
790 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
791 const char *pin, const char *key_id,
792 const char *cert_id, const char *ca_cert_id)
794 #ifndef OPENSSL_NO_ENGINE
796 if (engine_id == NULL) {
797 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
801 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
804 if (key_id == NULL) {
805 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
810 conn->engine = ENGINE_by_id(engine_id);
812 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
813 engine_id, ERR_error_string(ERR_get_error(), NULL));
816 if (ENGINE_init(conn->engine) != 1) {
817 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
818 "(engine: %s) [%s]", engine_id,
819 ERR_error_string(ERR_get_error(), NULL));
822 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
824 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
825 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
826 ERR_error_string(ERR_get_error(), NULL));
829 /* load private key first in-case PIN is required for cert */
830 conn->private_key = ENGINE_load_private_key(conn->engine,
832 if (!conn->private_key) {
833 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
834 " '%s' [%s]", key_id,
835 ERR_error_string(ERR_get_error(), NULL));
836 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
840 /* handle a certificate and/or CA certificate */
841 if (cert_id || ca_cert_id) {
842 const char *cmd_name = "LOAD_CERT_CTRL";
844 /* test if the engine supports a LOAD_CERT_CTRL */
845 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
846 0, (void *)cmd_name, NULL)) {
847 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
848 " loading certificates");
849 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
858 ENGINE_free(conn->engine);
862 if (conn->private_key) {
863 EVP_PKEY_free(conn->private_key);
864 conn->private_key = NULL;
868 #else /* OPENSSL_NO_ENGINE */
870 #endif /* OPENSSL_NO_ENGINE */
874 static void tls_engine_deinit(struct tls_connection *conn)
876 #ifndef OPENSSL_NO_ENGINE
877 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
878 if (conn->private_key) {
879 EVP_PKEY_free(conn->private_key);
880 conn->private_key = NULL;
883 ENGINE_finish(conn->engine);
886 #endif /* OPENSSL_NO_ENGINE */
890 int tls_get_errors(void *ssl_ctx)
895 while ((err = ERR_get_error())) {
896 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
897 ERR_error_string(err, NULL));
904 struct tls_connection * tls_connection_init(void *ssl_ctx)
906 SSL_CTX *ssl = ssl_ctx;
907 struct tls_connection *conn;
910 conn = os_zalloc(sizeof(*conn));
913 conn->ssl = SSL_new(ssl);
914 if (conn->ssl == NULL) {
915 tls_show_errors(MSG_INFO, __func__,
916 "Failed to initialize new SSL connection");
921 SSL_set_app_data(conn->ssl, conn);
922 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
923 SSL_OP_SINGLE_DH_USE;
924 #ifdef SSL_OP_NO_COMPRESSION
925 options |= SSL_OP_NO_COMPRESSION;
926 #endif /* SSL_OP_NO_COMPRESSION */
927 SSL_set_options(conn->ssl, options);
929 conn->ssl_in = BIO_new(BIO_s_mem());
931 tls_show_errors(MSG_INFO, __func__,
932 "Failed to create a new BIO for ssl_in");
938 conn->ssl_out = BIO_new(BIO_s_mem());
939 if (!conn->ssl_out) {
940 tls_show_errors(MSG_INFO, __func__,
941 "Failed to create a new BIO for ssl_out");
943 BIO_free(conn->ssl_in);
948 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
954 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
959 tls_engine_deinit(conn);
960 os_free(conn->subject_match);
961 os_free(conn->altsubject_match);
962 os_free(conn->session_ticket);
967 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
969 return conn ? SSL_is_init_finished(conn->ssl) : 0;
973 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
978 /* Shutdown previous TLS connection without notifying the peer
979 * because the connection was already terminated in practice
980 * and "close notify" shutdown alert would confuse AS. */
981 SSL_set_quiet_shutdown(conn->ssl, 1);
982 SSL_shutdown(conn->ssl);
987 static int tls_match_altsubject_component(X509 *cert, int type,
988 const char *value, size_t len)
994 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
996 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
997 gen = sk_GENERAL_NAME_value(ext, i);
998 if (gen->type != type)
1000 if (os_strlen((char *) gen->d.ia5->data) == len &&
1001 os_memcmp(value, gen->d.ia5->data, len) == 0)
1009 static int tls_match_altsubject(X509 *cert, const char *match)
1012 const char *pos, *end;
1017 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1020 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1023 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1027 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1031 end = os_strchr(pos, ';');
1033 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1034 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1035 os_strncmp(end + 1, "URI:", 4) == 0)
1037 end = os_strchr(end + 1, ';');
1042 len = os_strlen(pos);
1043 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1052 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1055 case X509_V_ERR_CERT_REVOKED:
1056 return TLS_FAIL_REVOKED;
1057 case X509_V_ERR_CERT_NOT_YET_VALID:
1058 case X509_V_ERR_CRL_NOT_YET_VALID:
1059 return TLS_FAIL_NOT_YET_VALID;
1060 case X509_V_ERR_CERT_HAS_EXPIRED:
1061 case X509_V_ERR_CRL_HAS_EXPIRED:
1062 return TLS_FAIL_EXPIRED;
1063 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1064 case X509_V_ERR_UNABLE_TO_GET_CRL:
1065 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1066 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1067 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1068 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1069 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1070 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1071 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1072 case X509_V_ERR_INVALID_CA:
1073 return TLS_FAIL_UNTRUSTED;
1074 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1075 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1076 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1077 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1078 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1079 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1080 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1081 case X509_V_ERR_CERT_UNTRUSTED:
1082 case X509_V_ERR_CERT_REJECTED:
1083 return TLS_FAIL_BAD_CERTIFICATE;
1085 return TLS_FAIL_UNSPECIFIED;
1090 static struct wpabuf * get_x509_cert(X509 *cert)
1095 int cert_len = i2d_X509(cert, NULL);
1099 buf = wpabuf_alloc(cert_len);
1103 tmp = wpabuf_put(buf, cert_len);
1104 i2d_X509(cert, &tmp);
1109 static void openssl_tls_fail_event(struct tls_connection *conn,
1110 X509 *err_cert, int err, int depth,
1111 const char *subject, const char *err_str,
1112 enum tls_fail_reason reason)
1114 union tls_event_data ev;
1115 struct wpabuf *cert = NULL;
1117 if (tls_global->event_cb == NULL)
1120 cert = get_x509_cert(err_cert);
1121 os_memset(&ev, 0, sizeof(ev));
1122 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1123 reason : openssl_tls_fail_reason(err);
1124 ev.cert_fail.depth = depth;
1125 ev.cert_fail.subject = subject;
1126 ev.cert_fail.reason_txt = err_str;
1127 ev.cert_fail.cert = cert;
1128 tls_global->event_cb(tls_global->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1133 static void openssl_tls_cert_event(struct tls_connection *conn,
1134 X509 *err_cert, int depth,
1135 const char *subject)
1137 struct wpabuf *cert = NULL;
1138 union tls_event_data ev;
1139 #ifdef CONFIG_SHA256
1141 #endif /* CONFIG_SHA256 */
1143 if (tls_global->event_cb == NULL)
1146 os_memset(&ev, 0, sizeof(ev));
1147 if (conn->cert_probe) {
1148 cert = get_x509_cert(err_cert);
1149 ev.peer_cert.cert = cert;
1151 #ifdef CONFIG_SHA256
1155 addr[0] = wpabuf_head(cert);
1156 len[0] = wpabuf_len(cert);
1157 if (sha256_vector(1, addr, len, hash) == 0) {
1158 ev.peer_cert.hash = hash;
1159 ev.peer_cert.hash_len = sizeof(hash);
1162 #endif /* CONFIG_SHA256 */
1163 ev.peer_cert.depth = depth;
1164 ev.peer_cert.subject = subject;
1165 tls_global->event_cb(tls_global->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1170 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1176 struct tls_connection *conn;
1177 char *match, *altmatch;
1178 const char *err_str;
1180 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1181 err = X509_STORE_CTX_get_error(x509_ctx);
1182 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1183 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1184 SSL_get_ex_data_X509_STORE_CTX_idx());
1185 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1187 conn = SSL_get_app_data(ssl);
1190 match = conn->subject_match;
1191 altmatch = conn->altsubject_match;
1193 if (!preverify_ok && !conn->ca_cert_verify)
1195 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1197 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1198 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1199 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1200 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1205 err_str = X509_verify_cert_error_string(err);
1207 #ifdef CONFIG_SHA256
1208 if (preverify_ok && depth == 0 && conn->server_cert_only) {
1209 struct wpabuf *cert;
1210 cert = get_x509_cert(err_cert);
1212 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1213 "server certificate data");
1219 addr[0] = wpabuf_head(cert);
1220 len[0] = wpabuf_len(cert);
1221 if (sha256_vector(1, addr, len, hash) < 0 ||
1222 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1223 err_str = "Server certificate mismatch";
1224 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1230 #endif /* CONFIG_SHA256 */
1232 if (!preverify_ok) {
1233 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1234 " error %d (%s) depth %d for '%s'", err, err_str,
1236 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1237 err_str, TLS_FAIL_UNSPECIFIED);
1238 return preverify_ok;
1241 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1242 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1243 preverify_ok, err, err_str,
1244 conn->ca_cert_verify, depth, buf);
1245 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1246 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1247 "match with '%s'", buf, match);
1249 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1251 TLS_FAIL_SUBJECT_MISMATCH);
1252 } else if (depth == 0 && altmatch &&
1253 !tls_match_altsubject(err_cert, altmatch)) {
1254 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1255 "'%s' not found", altmatch);
1257 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1258 "AltSubject mismatch",
1259 TLS_FAIL_ALTSUBJECT_MISMATCH);
1261 openssl_tls_cert_event(conn, err_cert, depth, buf);
1263 if (conn->cert_probe && preverify_ok && depth == 0) {
1264 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1265 "on probe-only run");
1267 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1268 "Server certificate chain probe",
1269 TLS_FAIL_SERVER_CHAIN_PROBE);
1272 return preverify_ok;
1276 #ifndef OPENSSL_NO_STDIO
1277 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1279 SSL_CTX *ssl_ctx = _ssl_ctx;
1280 X509_LOOKUP *lookup;
1283 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1284 X509_LOOKUP_file());
1285 if (lookup == NULL) {
1286 tls_show_errors(MSG_WARNING, __func__,
1287 "Failed add lookup for X509 store");
1291 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1292 unsigned long err = ERR_peek_error();
1293 tls_show_errors(MSG_WARNING, __func__,
1294 "Failed load CA in DER format");
1295 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1296 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1297 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1298 "cert already in hash table error",
1306 #endif /* OPENSSL_NO_STDIO */
1310 static BIO * BIO_from_keystore(const char *key)
1313 char value[KEYSTORE_MESSAGE_SIZE];
1314 int length = keystore_get(key, strlen(key), value);
1315 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
1316 BIO_write(bio, value, length);
1319 #endif /* ANDROID */
1322 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1323 const char *ca_cert, const u8 *ca_cert_blob,
1324 size_t ca_cert_blob_len, const char *ca_path)
1326 SSL_CTX *ssl_ctx = _ssl_ctx;
1329 * Remove previously configured trusted CA certificates before adding
1332 X509_STORE_free(ssl_ctx->cert_store);
1333 ssl_ctx->cert_store = X509_STORE_new();
1334 if (ssl_ctx->cert_store == NULL) {
1335 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1336 "certificate store", __func__);
1340 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1341 conn->ca_cert_verify = 1;
1343 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1344 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1346 conn->cert_probe = 1;
1347 conn->ca_cert_verify = 0;
1351 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1352 #ifdef CONFIG_SHA256
1353 const char *pos = ca_cert + 7;
1354 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1355 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1356 "hash value '%s'", ca_cert);
1360 if (os_strlen(pos) != 32 * 2) {
1361 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1362 "hash length in ca_cert '%s'", ca_cert);
1365 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1366 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1367 "value in ca_cert '%s'", ca_cert);
1370 conn->server_cert_only = 1;
1371 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1372 "certificate match");
1374 #else /* CONFIG_SHA256 */
1375 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1376 "cannot validate server certificate hash");
1378 #endif /* CONFIG_SHA256 */
1382 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1385 tls_show_errors(MSG_WARNING, __func__,
1386 "Failed to parse ca_cert_blob");
1390 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1391 unsigned long err = ERR_peek_error();
1392 tls_show_errors(MSG_WARNING, __func__,
1393 "Failed to add ca_cert_blob to "
1394 "certificate store");
1395 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1396 ERR_GET_REASON(err) ==
1397 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1398 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1399 "cert already in hash table error",
1407 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1408 "to certificate store", __func__);
1413 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1414 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1415 STACK_OF(X509_INFO) *stack = NULL;
1419 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1425 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1426 X509_INFO *info = sk_X509_INFO_value(stack, i);
1428 X509_STORE_add_cert(ssl_ctx->cert_store,
1432 X509_STORE_add_crl(ssl_ctx->cert_store,
1436 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1437 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1440 #endif /* ANDROID */
1442 #ifdef CONFIG_NATIVE_WINDOWS
1443 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1445 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1446 "system certificate store");
1449 #endif /* CONFIG_NATIVE_WINDOWS */
1451 if (ca_cert || ca_path) {
1452 #ifndef OPENSSL_NO_STDIO
1453 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1455 tls_show_errors(MSG_WARNING, __func__,
1456 "Failed to load root certificates");
1458 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1459 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1460 "DER format CA certificate",
1465 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1466 "certificate(s) loaded");
1467 tls_get_errors(ssl_ctx);
1469 #else /* OPENSSL_NO_STDIO */
1470 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1473 #endif /* OPENSSL_NO_STDIO */
1475 /* No ca_cert configured - do not try to verify server
1477 conn->ca_cert_verify = 0;
1484 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1487 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1489 tls_show_errors(MSG_WARNING, __func__,
1490 "Failed to load root certificates");
1494 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1495 "certificate(s) loaded");
1497 #ifndef OPENSSL_NO_STDIO
1498 /* Add the same CAs to the client certificate requests */
1499 SSL_CTX_set_client_CA_list(ssl_ctx,
1500 SSL_load_client_CA_file(ca_cert));
1501 #endif /* OPENSSL_NO_STDIO */
1508 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1513 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1515 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1516 "certificate store when enabling "
1520 flags = X509_V_FLAG_CRL_CHECK;
1522 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1523 X509_STORE_set_flags(cs, flags);
1529 static int tls_connection_set_subject_match(struct tls_connection *conn,
1530 const char *subject_match,
1531 const char *altsubject_match)
1533 os_free(conn->subject_match);
1534 conn->subject_match = NULL;
1535 if (subject_match) {
1536 conn->subject_match = os_strdup(subject_match);
1537 if (conn->subject_match == NULL)
1541 os_free(conn->altsubject_match);
1542 conn->altsubject_match = NULL;
1543 if (altsubject_match) {
1544 conn->altsubject_match = os_strdup(altsubject_match);
1545 if (conn->altsubject_match == NULL)
1553 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1556 static int counter = 0;
1562 conn->ca_cert_verify = 1;
1563 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1564 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1565 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1567 conn->ca_cert_verify = 0;
1568 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1571 SSL_set_accept_state(conn->ssl);
1574 * Set session id context in order to avoid fatal errors when client
1575 * tries to resume a session. However, set the context to a unique
1576 * value in order to effectively disable session resumption for now
1577 * since not all areas of the server code are ready for it (e.g.,
1578 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1582 SSL_set_session_id_context(conn->ssl,
1583 (const unsigned char *) &counter,
1590 static int tls_connection_client_cert(struct tls_connection *conn,
1591 const char *client_cert,
1592 const u8 *client_cert_blob,
1593 size_t client_cert_blob_len)
1595 if (client_cert == NULL && client_cert_blob == NULL)
1598 if (client_cert_blob &&
1599 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1600 client_cert_blob_len) == 1) {
1601 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1604 } else if (client_cert_blob) {
1605 tls_show_errors(MSG_DEBUG, __func__,
1606 "SSL_use_certificate_ASN1 failed");
1609 if (client_cert == NULL)
1613 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1614 BIO *bio = BIO_from_keystore(&client_cert[11]);
1618 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1622 if (SSL_use_certificate(conn->ssl, x509) == 1)
1628 #endif /* ANDROID */
1630 #ifndef OPENSSL_NO_STDIO
1631 if (SSL_use_certificate_file(conn->ssl, client_cert,
1632 SSL_FILETYPE_ASN1) == 1) {
1633 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1638 if (SSL_use_certificate_file(conn->ssl, client_cert,
1639 SSL_FILETYPE_PEM) == 1) {
1641 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1646 tls_show_errors(MSG_DEBUG, __func__,
1647 "SSL_use_certificate_file failed");
1648 #else /* OPENSSL_NO_STDIO */
1649 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1650 #endif /* OPENSSL_NO_STDIO */
1656 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1658 #ifndef OPENSSL_NO_STDIO
1659 if (client_cert == NULL)
1662 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1663 SSL_FILETYPE_ASN1) != 1 &&
1664 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1665 SSL_FILETYPE_PEM) != 1) {
1666 tls_show_errors(MSG_INFO, __func__,
1667 "Failed to load client certificate");
1671 #else /* OPENSSL_NO_STDIO */
1672 if (client_cert == NULL)
1674 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1676 #endif /* OPENSSL_NO_STDIO */
1680 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1682 if (password == NULL) {
1685 os_strlcpy(buf, (char *) password, size);
1686 return os_strlen(buf);
1691 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1696 STACK_OF(X509) *certs;
1703 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1704 tls_show_errors(MSG_DEBUG, __func__,
1705 "Failed to parse PKCS12 file");
1709 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1712 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1714 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1715 "subject='%s'", buf);
1717 if (SSL_use_certificate(ssl, cert) != 1)
1720 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1727 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1729 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1732 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1735 EVP_PKEY_free(pkey);
1739 while ((cert = sk_X509_pop(certs)) != NULL) {
1740 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1742 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1743 " from PKCS12: subject='%s'", buf);
1745 * There is no SSL equivalent for the chain cert - so
1746 * always add it to the context...
1748 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1753 sk_X509_free(certs);
1759 tls_get_errors(ssl_ctx);
1763 #endif /* PKCS12_FUNCS */
1766 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1773 f = fopen(private_key, "rb");
1777 p12 = d2i_PKCS12_fp(f, NULL);
1781 tls_show_errors(MSG_INFO, __func__,
1782 "Failed to use PKCS#12 file");
1786 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1788 #else /* PKCS12_FUNCS */
1789 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1792 #endif /* PKCS12_FUNCS */
1796 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1797 const u8 *blob, size_t len, const char *passwd)
1802 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1804 tls_show_errors(MSG_INFO, __func__,
1805 "Failed to use PKCS#12 blob");
1809 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1811 #else /* PKCS12_FUNCS */
1812 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1815 #endif /* PKCS12_FUNCS */
1819 #ifndef OPENSSL_NO_ENGINE
1820 static int tls_engine_get_cert(struct tls_connection *conn,
1821 const char *cert_id,
1824 /* this runs after the private key is loaded so no PIN is required */
1826 const char *cert_id;
1829 params.cert_id = cert_id;
1832 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1833 0, ¶ms, NULL, 1)) {
1834 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1835 " '%s' [%s]", cert_id,
1836 ERR_error_string(ERR_get_error(), NULL));
1837 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1840 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1842 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1844 *cert = params.cert;
1847 #endif /* OPENSSL_NO_ENGINE */
1850 static int tls_connection_engine_client_cert(struct tls_connection *conn,
1851 const char *cert_id)
1853 #ifndef OPENSSL_NO_ENGINE
1856 if (tls_engine_get_cert(conn, cert_id, &cert))
1859 if (!SSL_use_certificate(conn->ssl, cert)) {
1860 tls_show_errors(MSG_ERROR, __func__,
1861 "SSL_use_certificate failed");
1866 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1870 #else /* OPENSSL_NO_ENGINE */
1872 #endif /* OPENSSL_NO_ENGINE */
1876 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1877 struct tls_connection *conn,
1878 const char *ca_cert_id)
1880 #ifndef OPENSSL_NO_ENGINE
1882 SSL_CTX *ssl_ctx = _ssl_ctx;
1884 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1887 /* start off the same as tls_connection_ca_cert */
1888 X509_STORE_free(ssl_ctx->cert_store);
1889 ssl_ctx->cert_store = X509_STORE_new();
1890 if (ssl_ctx->cert_store == NULL) {
1891 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1892 "certificate store", __func__);
1896 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1897 unsigned long err = ERR_peek_error();
1898 tls_show_errors(MSG_WARNING, __func__,
1899 "Failed to add CA certificate from engine "
1900 "to certificate store");
1901 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1902 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1903 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1904 " already in hash table error",
1912 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1913 "to certificate store", __func__);
1914 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1917 #else /* OPENSSL_NO_ENGINE */
1919 #endif /* OPENSSL_NO_ENGINE */
1923 static int tls_connection_engine_private_key(struct tls_connection *conn)
1925 #ifndef OPENSSL_NO_ENGINE
1926 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1927 tls_show_errors(MSG_ERROR, __func__,
1928 "ENGINE: cannot use private key for TLS");
1931 if (!SSL_check_private_key(conn->ssl)) {
1932 tls_show_errors(MSG_INFO, __func__,
1933 "Private key failed verification");
1937 #else /* OPENSSL_NO_ENGINE */
1938 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1939 "engine support was not compiled in");
1941 #endif /* OPENSSL_NO_ENGINE */
1945 static int tls_connection_private_key(void *_ssl_ctx,
1946 struct tls_connection *conn,
1947 const char *private_key,
1948 const char *private_key_passwd,
1949 const u8 *private_key_blob,
1950 size_t private_key_blob_len)
1952 SSL_CTX *ssl_ctx = _ssl_ctx;
1956 if (private_key == NULL && private_key_blob == NULL)
1959 if (private_key_passwd) {
1960 passwd = os_strdup(private_key_passwd);
1966 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1967 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1970 while (private_key_blob) {
1971 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1972 (u8 *) private_key_blob,
1973 private_key_blob_len) == 1) {
1974 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1975 "ASN1(EVP_PKEY_RSA) --> OK");
1980 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1981 (u8 *) private_key_blob,
1982 private_key_blob_len) == 1) {
1983 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1984 "ASN1(EVP_PKEY_DSA) --> OK");
1989 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1990 (u8 *) private_key_blob,
1991 private_key_blob_len) == 1) {
1992 wpa_printf(MSG_DEBUG, "OpenSSL: "
1993 "SSL_use_RSAPrivateKey_ASN1 --> OK");
1998 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1999 private_key_blob_len, passwd) == 0) {
2000 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2010 if (!ok && private_key &&
2011 os_strncmp("keystore://", private_key, 11) == 0) {
2012 BIO *bio = BIO_from_keystore(&private_key[11]);
2013 EVP_PKEY *pkey = NULL;
2015 pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
2019 if (SSL_use_PrivateKey(conn->ssl, pkey) == 1) {
2020 wpa_printf(MSG_DEBUG, "OpenSSL: Private key "
2024 EVP_PKEY_free(pkey);
2027 #endif /* ANDROID */
2029 while (!ok && private_key) {
2030 #ifndef OPENSSL_NO_STDIO
2031 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2032 SSL_FILETYPE_ASN1) == 1) {
2033 wpa_printf(MSG_DEBUG, "OpenSSL: "
2034 "SSL_use_PrivateKey_File (DER) --> OK");
2039 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2040 SSL_FILETYPE_PEM) == 1) {
2041 wpa_printf(MSG_DEBUG, "OpenSSL: "
2042 "SSL_use_PrivateKey_File (PEM) --> OK");
2046 #else /* OPENSSL_NO_STDIO */
2047 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2049 #endif /* OPENSSL_NO_STDIO */
2051 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2053 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2059 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2060 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2061 "access certificate store --> OK");
2070 tls_show_errors(MSG_INFO, __func__,
2071 "Failed to load private key");
2076 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2079 if (!SSL_check_private_key(conn->ssl)) {
2080 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2085 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2090 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2091 const char *private_key_passwd)
2095 if (private_key == NULL)
2098 if (private_key_passwd) {
2099 passwd = os_strdup(private_key_passwd);
2105 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2106 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2108 #ifndef OPENSSL_NO_STDIO
2109 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2110 SSL_FILETYPE_ASN1) != 1 &&
2111 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2112 SSL_FILETYPE_PEM) != 1 &&
2113 #endif /* OPENSSL_NO_STDIO */
2114 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2115 tls_show_errors(MSG_INFO, __func__,
2116 "Failed to load private key");
2123 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2125 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2126 tls_show_errors(MSG_INFO, __func__,
2127 "Private key failed verification");
2135 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2137 #ifdef OPENSSL_NO_DH
2138 if (dh_file == NULL)
2140 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2141 "dh_file specified");
2143 #else /* OPENSSL_NO_DH */
2147 /* TODO: add support for dh_blob */
2148 if (dh_file == NULL)
2153 bio = BIO_new_file(dh_file, "r");
2155 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2156 dh_file, ERR_error_string(ERR_get_error(), NULL));
2159 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2161 #ifndef OPENSSL_NO_DSA
2162 while (dh == NULL) {
2164 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2165 " trying to parse as DSA params", dh_file,
2166 ERR_error_string(ERR_get_error(), NULL));
2167 bio = BIO_new_file(dh_file, "r");
2170 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2173 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2174 "'%s': %s", dh_file,
2175 ERR_error_string(ERR_get_error(), NULL));
2179 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2180 dh = DSA_dup_DH(dsa);
2183 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2184 "params into DH params");
2189 #endif /* !OPENSSL_NO_DSA */
2191 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2196 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2197 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2199 ERR_error_string(ERR_get_error(), NULL));
2205 #endif /* OPENSSL_NO_DH */
2209 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2211 #ifdef OPENSSL_NO_DH
2212 if (dh_file == NULL)
2214 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2215 "dh_file specified");
2217 #else /* OPENSSL_NO_DH */
2221 /* TODO: add support for dh_blob */
2222 if (dh_file == NULL)
2224 if (ssl_ctx == NULL)
2227 bio = BIO_new_file(dh_file, "r");
2229 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2230 dh_file, ERR_error_string(ERR_get_error(), NULL));
2233 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2235 #ifndef OPENSSL_NO_DSA
2236 while (dh == NULL) {
2238 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2239 " trying to parse as DSA params", dh_file,
2240 ERR_error_string(ERR_get_error(), NULL));
2241 bio = BIO_new_file(dh_file, "r");
2244 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2247 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2248 "'%s': %s", dh_file,
2249 ERR_error_string(ERR_get_error(), NULL));
2253 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2254 dh = DSA_dup_DH(dsa);
2257 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2258 "params into DH params");
2263 #endif /* !OPENSSL_NO_DSA */
2265 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2270 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2271 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2273 ERR_error_string(ERR_get_error(), NULL));
2279 #endif /* OPENSSL_NO_DH */
2283 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2284 struct tls_keys *keys)
2288 if (conn == NULL || keys == NULL)
2291 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2294 os_memset(keys, 0, sizeof(*keys));
2295 keys->master_key = ssl->session->master_key;
2296 keys->master_key_len = ssl->session->master_key_length;
2297 keys->client_random = ssl->s3->client_random;
2298 keys->client_random_len = SSL3_RANDOM_SIZE;
2299 keys->server_random = ssl->s3->server_random;
2300 keys->server_random_len = SSL3_RANDOM_SIZE;
2306 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2307 const char *label, int server_random_first,
2308 u8 *out, size_t out_len)
2314 static struct wpabuf *
2315 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2319 struct wpabuf *out_data;
2322 * Give TLS handshake data from the server (if available) to OpenSSL
2326 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2328 tls_show_errors(MSG_INFO, __func__,
2329 "Handshake failed - BIO_write");
2333 /* Initiate TLS handshake or continue the existing handshake */
2335 res = SSL_accept(conn->ssl);
2337 res = SSL_connect(conn->ssl);
2339 int err = SSL_get_error(conn->ssl, res);
2340 if (err == SSL_ERROR_WANT_READ)
2341 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2343 else if (err == SSL_ERROR_WANT_WRITE)
2344 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2347 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2352 /* Get the TLS handshake data to be sent to the server */
2353 res = BIO_ctrl_pending(conn->ssl_out);
2354 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2355 out_data = wpabuf_alloc(res);
2356 if (out_data == NULL) {
2357 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2358 "handshake output (%d bytes)", res);
2359 if (BIO_reset(conn->ssl_out) < 0) {
2360 tls_show_errors(MSG_INFO, __func__,
2361 "BIO_reset failed");
2365 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2368 tls_show_errors(MSG_INFO, __func__,
2369 "Handshake failed - BIO_read");
2370 if (BIO_reset(conn->ssl_out) < 0) {
2371 tls_show_errors(MSG_INFO, __func__,
2372 "BIO_reset failed");
2374 wpabuf_free(out_data);
2377 wpabuf_put(out_data, res);
2383 static struct wpabuf *
2384 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2386 struct wpabuf *appl_data;
2389 appl_data = wpabuf_alloc(max_len + 100);
2390 if (appl_data == NULL)
2393 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2394 wpabuf_size(appl_data));
2396 int err = SSL_get_error(conn->ssl, res);
2397 if (err == SSL_ERROR_WANT_READ ||
2398 err == SSL_ERROR_WANT_WRITE) {
2399 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2402 tls_show_errors(MSG_INFO, __func__,
2403 "Failed to read possible "
2404 "Application Data");
2406 wpabuf_free(appl_data);
2410 wpabuf_put(appl_data, res);
2411 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2412 "message", appl_data);
2418 static struct wpabuf *
2419 openssl_connection_handshake(struct tls_connection *conn,
2420 const struct wpabuf *in_data,
2421 struct wpabuf **appl_data, int server)
2423 struct wpabuf *out_data;
2428 out_data = openssl_handshake(conn, in_data, server);
2429 if (out_data == NULL)
2432 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2433 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2440 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2441 const struct wpabuf *in_data,
2442 struct wpabuf **appl_data)
2444 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2448 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2449 struct tls_connection *conn,
2450 const struct wpabuf *in_data,
2451 struct wpabuf **appl_data)
2453 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2457 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2458 struct tls_connection *conn,
2459 const struct wpabuf *in_data)
2467 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2468 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2469 (res = BIO_reset(conn->ssl_out)) < 0) {
2470 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2473 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2475 tls_show_errors(MSG_INFO, __func__,
2476 "Encryption failed - SSL_write");
2480 /* Read encrypted data to be sent to the server */
2481 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2484 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2486 tls_show_errors(MSG_INFO, __func__,
2487 "Encryption failed - BIO_read");
2491 wpabuf_put(buf, res);
2497 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2498 struct tls_connection *conn,
2499 const struct wpabuf *in_data)
2504 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2505 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2506 wpabuf_len(in_data));
2508 tls_show_errors(MSG_INFO, __func__,
2509 "Decryption failed - BIO_write");
2512 if (BIO_reset(conn->ssl_out) < 0) {
2513 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2517 /* Read decrypted data for further processing */
2519 * Even though we try to disable TLS compression, it is possible that
2520 * this cannot be done with all TLS libraries. Add extra buffer space
2521 * to handle the possibility of the decrypted data being longer than
2524 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2527 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2529 tls_show_errors(MSG_INFO, __func__,
2530 "Decryption failed - SSL_read");
2534 wpabuf_put(buf, res);
2540 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2542 return conn ? conn->ssl->hit : 0;
2546 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2549 char buf[100], *pos, *end;
2553 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2558 end = pos + sizeof(buf);
2561 while (*c != TLS_CIPHER_NONE) {
2565 case TLS_CIPHER_RC4_SHA:
2568 case TLS_CIPHER_AES128_SHA:
2569 suite = "AES128-SHA";
2571 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2572 suite = "DHE-RSA-AES128-SHA";
2574 case TLS_CIPHER_ANON_DH_AES128_SHA:
2575 suite = "ADH-AES128-SHA";
2578 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2579 "cipher selection: %d", *c);
2582 ret = os_snprintf(pos, end - pos, ":%s", suite);
2583 if (ret < 0 || ret >= end - pos)
2590 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2592 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2593 tls_show_errors(MSG_INFO, __func__,
2594 "Cipher suite configuration failed");
2602 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2603 char *buf, size_t buflen)
2606 if (conn == NULL || conn->ssl == NULL)
2609 name = SSL_get_cipher(conn->ssl);
2613 os_strlcpy(buf, name, buflen);
2618 int tls_connection_enable_workaround(void *ssl_ctx,
2619 struct tls_connection *conn)
2621 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2627 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2628 /* ClientHello TLS extensions require a patch to openssl, so this function is
2629 * commented out unless explicitly needed for EAP-FAST in order to be able to
2630 * build this file with unmodified openssl. */
2631 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2632 int ext_type, const u8 *data,
2635 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2638 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2639 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2642 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2643 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2646 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2650 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2653 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2657 return conn->failed;
2661 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2665 return conn->read_alerts;
2669 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2673 return conn->write_alerts;
2677 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2678 const struct tls_connection_params *params)
2686 while ((err = ERR_get_error())) {
2687 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2688 __func__, ERR_error_string(err, NULL));
2691 if (params->engine) {
2692 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2693 ret = tls_engine_init(conn, params->engine_id, params->pin,
2694 params->key_id, params->cert_id,
2695 params->ca_cert_id);
2699 if (tls_connection_set_subject_match(conn,
2700 params->subject_match,
2701 params->altsubject_match))
2704 if (params->engine && params->ca_cert_id) {
2705 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2706 params->ca_cert_id))
2707 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2708 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2709 params->ca_cert_blob,
2710 params->ca_cert_blob_len,
2714 if (params->engine && params->cert_id) {
2715 if (tls_connection_engine_client_cert(conn, params->cert_id))
2716 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2717 } else if (tls_connection_client_cert(conn, params->client_cert,
2718 params->client_cert_blob,
2719 params->client_cert_blob_len))
2722 if (params->engine && params->key_id) {
2723 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2724 if (tls_connection_engine_private_key(conn))
2725 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2726 } else if (tls_connection_private_key(tls_ctx, conn,
2727 params->private_key,
2728 params->private_key_passwd,
2729 params->private_key_blob,
2730 params->private_key_blob_len)) {
2731 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2732 params->private_key);
2736 if (tls_connection_dh(conn, params->dh_file)) {
2737 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2742 conn->flags = params->flags;
2744 tls_get_errors(tls_ctx);
2750 int tls_global_set_params(void *tls_ctx,
2751 const struct tls_connection_params *params)
2753 SSL_CTX *ssl_ctx = tls_ctx;
2756 while ((err = ERR_get_error())) {
2757 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2758 __func__, ERR_error_string(err, NULL));
2761 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2764 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2767 if (tls_global_private_key(ssl_ctx, params->private_key,
2768 params->private_key_passwd))
2771 if (tls_global_dh(ssl_ctx, params->dh_file)) {
2772 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2781 int tls_connection_get_keyblock_size(void *tls_ctx,
2782 struct tls_connection *conn)
2784 const EVP_CIPHER *c;
2787 if (conn == NULL || conn->ssl == NULL ||
2788 conn->ssl->enc_read_ctx == NULL ||
2789 conn->ssl->enc_read_ctx->cipher == NULL ||
2790 conn->ssl->read_hash == NULL)
2793 c = conn->ssl->enc_read_ctx->cipher;
2794 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2795 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2797 h = conn->ssl->read_hash;
2800 return 2 * (EVP_CIPHER_key_length(c) +
2802 EVP_CIPHER_iv_length(c));
2806 unsigned int tls_capabilities(void *tls_ctx)
2812 int tls_connection_set_ia(void *tls_ctx, struct tls_connection *conn,
2819 struct wpabuf * tls_connection_ia_send_phase_finished(
2820 void *tls_ctx, struct tls_connection *conn, int final)
2826 int tls_connection_ia_final_phase_finished(void *tls_ctx,
2827 struct tls_connection *conn)
2833 int tls_connection_ia_permute_inner_secret(void *tls_ctx,
2834 struct tls_connection *conn,
2835 const u8 *key, size_t key_len)
2841 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2842 /* Pre-shared secred requires a patch to openssl, so this function is
2843 * commented out unless explicitly needed for EAP-FAST in order to be able to
2844 * build this file with unmodified openssl. */
2846 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2847 STACK_OF(SSL_CIPHER) *peer_ciphers,
2848 SSL_CIPHER **cipher, void *arg)
2850 struct tls_connection *conn = arg;
2853 if (conn == NULL || conn->session_ticket_cb == NULL)
2856 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2857 conn->session_ticket,
2858 conn->session_ticket_len,
2859 s->s3->client_random,
2860 s->s3->server_random, secret);
2861 os_free(conn->session_ticket);
2862 conn->session_ticket = NULL;
2867 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2872 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2873 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
2876 struct tls_connection *conn = arg;
2878 if (conn == NULL || conn->session_ticket_cb == NULL)
2881 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
2883 os_free(conn->session_ticket);
2884 conn->session_ticket = NULL;
2886 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2887 "extension", data, len);
2889 conn->session_ticket = os_malloc(len);
2890 if (conn->session_ticket == NULL)
2893 os_memcpy(conn->session_ticket, data, len);
2894 conn->session_ticket_len = len;
2898 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2899 #ifdef SSL_OP_NO_TICKET
2900 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2901 unsigned char *data, int len, void *arg)
2903 struct tls_connection *conn = arg;
2905 if (conn == NULL || conn->session_ticket_cb == NULL)
2908 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2911 if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2912 os_free(conn->session_ticket);
2913 conn->session_ticket = NULL;
2915 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2916 "extension", data, len);
2917 conn->session_ticket = os_malloc(len);
2918 if (conn->session_ticket == NULL)
2921 os_memcpy(conn->session_ticket, data, len);
2922 conn->session_ticket_len = len;
2925 #else /* SSL_OP_NO_TICKET */
2926 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2928 struct tls_connection *conn = arg;
2930 if (conn == NULL || conn->session_ticket_cb == NULL)
2933 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2934 ext->type, ext->length);
2936 os_free(conn->session_ticket);
2937 conn->session_ticket = NULL;
2939 if (ext->type == 35) {
2940 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2941 "extension", ext->data, ext->length);
2942 conn->session_ticket = os_malloc(ext->length);
2943 if (conn->session_ticket == NULL)
2944 return SSL_AD_INTERNAL_ERROR;
2946 os_memcpy(conn->session_ticket, ext->data, ext->length);
2947 conn->session_ticket_len = ext->length;
2952 #endif /* SSL_OP_NO_TICKET */
2953 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2954 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2957 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2958 struct tls_connection *conn,
2959 tls_session_ticket_cb cb,
2962 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2963 conn->session_ticket_cb = cb;
2964 conn->session_ticket_cb_ctx = ctx;
2967 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2970 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2971 SSL_set_session_ticket_ext_cb(conn->ssl,
2972 tls_session_ticket_ext_cb, conn);
2973 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2974 #ifdef SSL_OP_NO_TICKET
2975 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2976 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2977 #else /* SSL_OP_NO_TICKET */
2978 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2981 #endif /* SSL_OP_NO_TICKET */
2982 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2984 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2986 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2987 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
2988 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2989 #ifdef SSL_OP_NO_TICKET
2990 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2991 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2992 #else /* SSL_OP_NO_TICKET */
2993 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2995 #endif /* SSL_OP_NO_TICKET */
2996 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3000 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3002 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */