2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2011, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
11 #ifndef CONFIG_SMARTCARD
12 #ifndef OPENSSL_NO_ENGINE
13 #define OPENSSL_NO_ENGINE
17 #include <openssl/ssl.h>
18 #include <openssl/err.h>
19 #include <openssl/pkcs12.h>
20 #include <openssl/x509v3.h>
21 #ifndef OPENSSL_NO_ENGINE
22 #include <openssl/engine.h>
23 #endif /* OPENSSL_NO_ENGINE */
26 #include <openssl/pem.h>
27 #include "keystore_get.h"
34 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
35 #define OPENSSL_d2i_TYPE const unsigned char **
37 #define OPENSSL_d2i_TYPE unsigned char **
40 #ifdef SSL_F_SSL_SET_SESSION_TICKET_EXT
41 #ifdef SSL_OP_NO_TICKET
43 * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
44 * 2008-11-15. This version uses a bit different API compared to the old patch.
46 #define CONFIG_OPENSSL_TICKET_OVERRIDE
50 static int tls_openssl_ref_count = 0;
53 void (*event_cb)(void *ctx, enum tls_event ev,
54 union tls_event_data *data);
59 static struct tls_global *tls_global = NULL;
62 struct tls_connection {
64 BIO *ssl_in, *ssl_out;
65 #ifndef OPENSSL_NO_ENGINE
66 ENGINE *engine; /* functional reference to the engine */
67 EVP_PKEY *private_key; /* the private key if using engine */
68 #endif /* OPENSSL_NO_ENGINE */
69 char *subject_match, *altsubject_match;
70 int read_alerts, write_alerts, failed;
72 tls_session_ticket_cb session_ticket_cb;
73 void *session_ticket_cb_ctx;
75 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
77 size_t session_ticket_len;
79 unsigned int ca_cert_verify:1;
80 unsigned int cert_probe:1;
81 unsigned int server_cert_only:1;
89 #ifdef CONFIG_NO_STDOUT_DEBUG
91 static void _tls_show_errors(void)
95 while ((err = ERR_get_error())) {
96 /* Just ignore the errors, since stdout is disabled */
99 #define tls_show_errors(l, f, t) _tls_show_errors()
101 #else /* CONFIG_NO_STDOUT_DEBUG */
103 static void tls_show_errors(int level, const char *func, const char *txt)
107 wpa_printf(level, "OpenSSL: %s - %s %s",
108 func, txt, ERR_error_string(ERR_get_error(), NULL));
110 while ((err = ERR_get_error())) {
111 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
112 ERR_error_string(err, NULL));
116 #endif /* CONFIG_NO_STDOUT_DEBUG */
119 #ifdef CONFIG_NATIVE_WINDOWS
121 /* Windows CryptoAPI and access to certificate stores */
122 #include <wincrypt.h>
124 #ifdef __MINGW32_VERSION
126 * MinGW does not yet include all the needed definitions for CryptoAPI, so
127 * define here whatever extra is needed.
129 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
130 #define CERT_STORE_READONLY_FLAG 0x00008000
131 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
133 #endif /* __MINGW32_VERSION */
136 struct cryptoapi_rsa_data {
137 const CERT_CONTEXT *cert;
138 HCRYPTPROV crypt_prov;
140 BOOL free_crypt_prov;
144 static void cryptoapi_error(const char *msg)
146 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
147 msg, (unsigned int) GetLastError());
151 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
152 unsigned char *to, RSA *rsa, int padding)
154 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
159 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
160 unsigned char *to, RSA *rsa, int padding)
162 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
167 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
168 unsigned char *to, RSA *rsa, int padding)
170 struct cryptoapi_rsa_data *priv =
171 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
173 DWORD hash_size, len, i;
174 unsigned char *buf = NULL;
178 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
179 ERR_R_PASSED_NULL_PARAMETER);
183 if (padding != RSA_PKCS1_PADDING) {
184 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
185 RSA_R_UNKNOWN_PADDING_TYPE);
189 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
190 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
192 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
193 RSA_R_INVALID_MESSAGE_LENGTH);
197 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
199 cryptoapi_error("CryptCreateHash failed");
203 len = sizeof(hash_size);
204 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
206 cryptoapi_error("CryptGetHashParam failed");
210 if ((int) hash_size != flen) {
211 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
212 (unsigned) hash_size, flen);
213 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
214 RSA_R_INVALID_MESSAGE_LENGTH);
217 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
218 cryptoapi_error("CryptSetHashParam failed");
223 buf = os_malloc(len);
225 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
229 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
230 cryptoapi_error("CryptSignHash failed");
234 for (i = 0; i < len; i++)
235 to[i] = buf[len - i - 1];
240 CryptDestroyHash(hash);
246 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
247 unsigned char *to, RSA *rsa, int padding)
249 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
254 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
258 if (priv->crypt_prov && priv->free_crypt_prov)
259 CryptReleaseContext(priv->crypt_prov, 0);
261 CertFreeCertificateContext(priv->cert);
266 static int cryptoapi_finish(RSA *rsa)
268 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
269 os_free((void *) rsa->meth);
275 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
278 const CERT_CONTEXT *ret = NULL;
280 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
281 store | CERT_STORE_OPEN_EXISTING_FLAG |
282 CERT_STORE_READONLY_FLAG, L"MY");
284 cryptoapi_error("Failed to open 'My system store'");
288 if (strncmp(name, "cert://", 7) == 0) {
289 unsigned short wbuf[255];
290 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
291 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
293 0, CERT_FIND_SUBJECT_STR,
295 } else if (strncmp(name, "hash://", 7) == 0) {
296 CRYPT_HASH_BLOB blob;
298 const char *hash = name + 7;
301 len = os_strlen(hash) / 2;
302 buf = os_malloc(len);
303 if (buf && hexstr2bin(hash, buf, len) == 0) {
306 ret = CertFindCertificateInStore(cs,
315 CertCloseStore(cs, 0);
321 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
324 RSA *rsa = NULL, *pub_rsa;
325 struct cryptoapi_rsa_data *priv;
326 RSA_METHOD *rsa_meth;
329 (strncmp(name, "cert://", 7) != 0 &&
330 strncmp(name, "hash://", 7) != 0))
333 priv = os_zalloc(sizeof(*priv));
334 rsa_meth = os_zalloc(sizeof(*rsa_meth));
335 if (priv == NULL || rsa_meth == NULL) {
336 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
337 "for CryptoAPI RSA method");
343 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
344 if (priv->cert == NULL) {
345 priv->cert = cryptoapi_find_cert(
346 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
348 if (priv->cert == NULL) {
349 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
354 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
355 priv->cert->cbCertEncoded);
357 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
362 if (!CryptAcquireCertificatePrivateKey(priv->cert,
363 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
364 NULL, &priv->crypt_prov,
366 &priv->free_crypt_prov)) {
367 cryptoapi_error("Failed to acquire a private key for the "
372 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
373 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
374 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
375 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
376 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
377 rsa_meth->finish = cryptoapi_finish;
378 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
379 rsa_meth->app_data = (char *) priv;
383 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
384 ERR_R_MALLOC_FAILURE);
388 if (!SSL_use_certificate(ssl, cert)) {
393 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
397 rsa->n = BN_dup(pub_rsa->n);
398 rsa->e = BN_dup(pub_rsa->e);
399 if (!RSA_set_method(rsa, rsa_meth))
402 if (!SSL_use_RSAPrivateKey(ssl, rsa))
415 cryptoapi_free_data(priv);
421 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
424 PCCERT_CONTEXT ctx = NULL;
432 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
437 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
440 wsprintf(wstore, L"%S", store);
441 cs = CertOpenSystemStore(0, wstore);
444 cs = CertOpenSystemStore(0, store);
447 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
448 "'%s': error=%d", __func__, store,
449 (int) GetLastError());
453 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
454 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
457 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
458 "X509 DER encoding for CA cert");
462 X509_NAME_oneline(X509_get_subject_name(cert), buf,
464 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
465 "system certificate store: subject='%s'", buf);
467 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
468 tls_show_errors(MSG_WARNING, __func__,
469 "Failed to add ca_cert to OpenSSL "
470 "certificate store");
476 if (!CertCloseStore(cs, 0)) {
477 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
478 "'%s': error=%d", __func__, name + 13,
479 (int) GetLastError());
486 #else /* CONFIG_NATIVE_WINDOWS */
488 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
493 #endif /* CONFIG_NATIVE_WINDOWS */
496 static void ssl_info_cb(const SSL *ssl, int where, int ret)
501 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
502 w = where & ~SSL_ST_MASK;
503 if (w & SSL_ST_CONNECT)
505 else if (w & SSL_ST_ACCEPT)
510 if (where & SSL_CB_LOOP) {
511 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
512 str, SSL_state_string_long(ssl));
513 } else if (where & SSL_CB_ALERT) {
514 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
515 where & SSL_CB_READ ?
516 "read (remote end reported an error)" :
517 "write (local SSL3 detected an error)",
518 SSL_alert_type_string_long(ret),
519 SSL_alert_desc_string_long(ret));
520 if ((ret >> 8) == SSL3_AL_FATAL) {
521 struct tls_connection *conn =
522 SSL_get_app_data((SSL *) ssl);
523 if (where & SSL_CB_READ)
526 conn->write_alerts++;
528 if (tls_global->event_cb != NULL) {
529 union tls_event_data ev;
530 os_memset(&ev, 0, sizeof(ev));
531 ev.alert.is_local = !(where & SSL_CB_READ);
532 ev.alert.type = SSL_alert_type_string_long(ret);
533 ev.alert.description = SSL_alert_desc_string_long(ret);
534 tls_global->event_cb(tls_global->cb_ctx, TLS_ALERT,
537 } else if (where & SSL_CB_EXIT && ret <= 0) {
538 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
539 str, ret == 0 ? "failed" : "error",
540 SSL_state_string_long(ssl));
545 #ifndef OPENSSL_NO_ENGINE
547 * tls_engine_load_dynamic_generic - load any openssl engine
548 * @pre: an array of commands and values that load an engine initialized
549 * in the engine specific function
550 * @post: an array of commands and values that initialize an already loaded
551 * engine (or %NULL if not required)
552 * @id: the engine id of the engine to load (only required if post is not %NULL
554 * This function is a generic function that loads any openssl engine.
556 * Returns: 0 on success, -1 on failure
558 static int tls_engine_load_dynamic_generic(const char *pre[],
559 const char *post[], const char *id)
562 const char *dynamic_id = "dynamic";
564 engine = ENGINE_by_id(id);
567 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
573 engine = ENGINE_by_id(dynamic_id);
574 if (engine == NULL) {
575 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
577 ERR_error_string(ERR_get_error(), NULL));
581 /* Perform the pre commands. This will load the engine. */
582 while (pre && pre[0]) {
583 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
584 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
585 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
586 "%s %s [%s]", pre[0], pre[1],
587 ERR_error_string(ERR_get_error(), NULL));
595 * Free the reference to the "dynamic" engine. The loaded engine can
596 * now be looked up using ENGINE_by_id().
600 engine = ENGINE_by_id(id);
601 if (engine == NULL) {
602 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
603 id, ERR_error_string(ERR_get_error(), NULL));
607 while (post && post[0]) {
608 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
609 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
610 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
611 " %s %s [%s]", post[0], post[1],
612 ERR_error_string(ERR_get_error(), NULL));
613 ENGINE_remove(engine);
626 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
627 * @pkcs11_so_path: pksc11_so_path from the configuration
628 * @pcks11_module_path: pkcs11_module_path from the configuration
630 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
631 const char *pkcs11_module_path)
633 char *engine_id = "pkcs11";
634 const char *pre_cmd[] = {
635 "SO_PATH", NULL /* pkcs11_so_path */,
636 "ID", NULL /* engine_id */,
638 /* "NO_VCHECK", "1", */
642 const char *post_cmd[] = {
643 "MODULE_PATH", NULL /* pkcs11_module_path */,
647 if (!pkcs11_so_path || !pkcs11_module_path)
650 pre_cmd[1] = pkcs11_so_path;
651 pre_cmd[3] = engine_id;
652 post_cmd[1] = pkcs11_module_path;
654 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
657 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
662 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
663 * @opensc_so_path: opensc_so_path from the configuration
665 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
667 char *engine_id = "opensc";
668 const char *pre_cmd[] = {
669 "SO_PATH", NULL /* opensc_so_path */,
670 "ID", NULL /* engine_id */,
679 pre_cmd[1] = opensc_so_path;
680 pre_cmd[3] = engine_id;
682 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
685 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
687 #endif /* OPENSSL_NO_ENGINE */
690 void * tls_init(const struct tls_config *conf)
694 if (tls_openssl_ref_count == 0) {
695 tls_global = os_zalloc(sizeof(*tls_global));
696 if (tls_global == NULL)
699 tls_global->event_cb = conf->event_cb;
700 tls_global->cb_ctx = conf->cb_ctx;
701 tls_global->cert_in_cb = conf->cert_in_cb;
706 if (conf && conf->fips_mode) {
707 if (!FIPS_mode_set(1)) {
708 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
710 ERR_load_crypto_strings();
711 ERR_print_errors_fp(stderr);
716 wpa_printf(MSG_INFO, "Running in FIPS mode");
718 #else /* OPENSSL_FIPS */
719 if (conf && conf->fips_mode) {
720 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
726 #endif /* OPENSSL_FIPS */
727 #endif /* CONFIG_FIPS */
728 SSL_load_error_strings();
730 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
731 EVP_add_digest(EVP_sha256());
732 #endif /* OPENSSL_NO_SHA256 */
733 /* TODO: if /dev/urandom is available, PRNG is seeded
734 * automatically. If this is not the case, random data should
738 #ifndef OPENSSL_NO_RC2
740 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
741 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
742 * versions, but it looks like OpenSSL 1.0.0 does not do that
745 EVP_add_cipher(EVP_rc2_40_cbc());
746 #endif /* OPENSSL_NO_RC2 */
748 #endif /* PKCS12_FUNCS */
750 tls_openssl_ref_count++;
752 ssl = SSL_CTX_new(TLSv1_method());
756 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
758 #ifndef OPENSSL_NO_ENGINE
760 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
761 conf->pkcs11_module_path)) {
762 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
763 ERR_load_ENGINE_strings();
764 ENGINE_load_dynamic();
766 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
767 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
768 conf->pkcs11_module_path)) {
773 #endif /* OPENSSL_NO_ENGINE */
779 void tls_deinit(void *ssl_ctx)
781 SSL_CTX *ssl = ssl_ctx;
784 tls_openssl_ref_count--;
785 if (tls_openssl_ref_count == 0) {
786 #ifndef OPENSSL_NO_ENGINE
788 #endif /* OPENSSL_NO_ENGINE */
789 CRYPTO_cleanup_all_ex_data();
799 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
800 const char *pin, const char *key_id,
801 const char *cert_id, const char *ca_cert_id)
803 #ifndef OPENSSL_NO_ENGINE
805 if (engine_id == NULL) {
806 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
810 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
813 if (key_id == NULL) {
814 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
819 conn->engine = ENGINE_by_id(engine_id);
821 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
822 engine_id, ERR_error_string(ERR_get_error(), NULL));
825 if (ENGINE_init(conn->engine) != 1) {
826 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
827 "(engine: %s) [%s]", engine_id,
828 ERR_error_string(ERR_get_error(), NULL));
831 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
833 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
834 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
835 ERR_error_string(ERR_get_error(), NULL));
838 /* load private key first in-case PIN is required for cert */
839 conn->private_key = ENGINE_load_private_key(conn->engine,
841 if (!conn->private_key) {
842 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
843 " '%s' [%s]", key_id,
844 ERR_error_string(ERR_get_error(), NULL));
845 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
849 /* handle a certificate and/or CA certificate */
850 if (cert_id || ca_cert_id) {
851 const char *cmd_name = "LOAD_CERT_CTRL";
853 /* test if the engine supports a LOAD_CERT_CTRL */
854 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
855 0, (void *)cmd_name, NULL)) {
856 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
857 " loading certificates");
858 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
867 ENGINE_free(conn->engine);
871 if (conn->private_key) {
872 EVP_PKEY_free(conn->private_key);
873 conn->private_key = NULL;
877 #else /* OPENSSL_NO_ENGINE */
879 #endif /* OPENSSL_NO_ENGINE */
883 static void tls_engine_deinit(struct tls_connection *conn)
885 #ifndef OPENSSL_NO_ENGINE
886 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
887 if (conn->private_key) {
888 EVP_PKEY_free(conn->private_key);
889 conn->private_key = NULL;
892 ENGINE_finish(conn->engine);
895 #endif /* OPENSSL_NO_ENGINE */
899 int tls_get_errors(void *ssl_ctx)
904 while ((err = ERR_get_error())) {
905 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
906 ERR_error_string(err, NULL));
913 struct tls_connection * tls_connection_init(void *ssl_ctx)
915 SSL_CTX *ssl = ssl_ctx;
916 struct tls_connection *conn;
919 conn = os_zalloc(sizeof(*conn));
922 conn->ssl = SSL_new(ssl);
923 if (conn->ssl == NULL) {
924 tls_show_errors(MSG_INFO, __func__,
925 "Failed to initialize new SSL connection");
930 SSL_set_app_data(conn->ssl, conn);
931 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
932 SSL_OP_SINGLE_DH_USE;
933 #ifdef SSL_OP_NO_COMPRESSION
934 options |= SSL_OP_NO_COMPRESSION;
935 #endif /* SSL_OP_NO_COMPRESSION */
936 SSL_set_options(conn->ssl, options);
938 conn->ssl_in = BIO_new(BIO_s_mem());
940 tls_show_errors(MSG_INFO, __func__,
941 "Failed to create a new BIO for ssl_in");
947 conn->ssl_out = BIO_new(BIO_s_mem());
948 if (!conn->ssl_out) {
949 tls_show_errors(MSG_INFO, __func__,
950 "Failed to create a new BIO for ssl_out");
952 BIO_free(conn->ssl_in);
957 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
963 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
968 tls_engine_deinit(conn);
969 os_free(conn->subject_match);
970 os_free(conn->altsubject_match);
971 os_free(conn->session_ticket);
976 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
978 return conn ? SSL_is_init_finished(conn->ssl) : 0;
982 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
987 /* Shutdown previous TLS connection without notifying the peer
988 * because the connection was already terminated in practice
989 * and "close notify" shutdown alert would confuse AS. */
990 SSL_set_quiet_shutdown(conn->ssl, 1);
991 SSL_shutdown(conn->ssl);
996 static int tls_match_altsubject_component(X509 *cert, int type,
997 const char *value, size_t len)
1003 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1005 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1006 gen = sk_GENERAL_NAME_value(ext, i);
1007 if (gen->type != type)
1009 if (os_strlen((char *) gen->d.ia5->data) == len &&
1010 os_memcmp(value, gen->d.ia5->data, len) == 0)
1018 static int tls_match_altsubject(X509 *cert, const char *match)
1021 const char *pos, *end;
1026 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1029 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1032 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1036 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1040 end = os_strchr(pos, ';');
1042 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1043 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1044 os_strncmp(end + 1, "URI:", 4) == 0)
1046 end = os_strchr(end + 1, ';');
1051 len = os_strlen(pos);
1052 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1061 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1064 case X509_V_ERR_CERT_REVOKED:
1065 return TLS_FAIL_REVOKED;
1066 case X509_V_ERR_CERT_NOT_YET_VALID:
1067 case X509_V_ERR_CRL_NOT_YET_VALID:
1068 return TLS_FAIL_NOT_YET_VALID;
1069 case X509_V_ERR_CERT_HAS_EXPIRED:
1070 case X509_V_ERR_CRL_HAS_EXPIRED:
1071 return TLS_FAIL_EXPIRED;
1072 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1073 case X509_V_ERR_UNABLE_TO_GET_CRL:
1074 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1075 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1076 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1077 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1078 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1079 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1080 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1081 case X509_V_ERR_INVALID_CA:
1082 return TLS_FAIL_UNTRUSTED;
1083 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1084 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1085 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1086 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1087 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1088 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1089 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1090 case X509_V_ERR_CERT_UNTRUSTED:
1091 case X509_V_ERR_CERT_REJECTED:
1092 return TLS_FAIL_BAD_CERTIFICATE;
1094 return TLS_FAIL_UNSPECIFIED;
1099 static struct wpabuf * get_x509_cert(X509 *cert)
1104 int cert_len = i2d_X509(cert, NULL);
1108 buf = wpabuf_alloc(cert_len);
1112 tmp = wpabuf_put(buf, cert_len);
1113 i2d_X509(cert, &tmp);
1118 static void openssl_tls_fail_event(struct tls_connection *conn,
1119 X509 *err_cert, int err, int depth,
1120 const char *subject, const char *err_str,
1121 enum tls_fail_reason reason)
1123 union tls_event_data ev;
1124 struct wpabuf *cert = NULL;
1126 if (tls_global->event_cb == NULL)
1129 cert = get_x509_cert(err_cert);
1130 os_memset(&ev, 0, sizeof(ev));
1131 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1132 reason : openssl_tls_fail_reason(err);
1133 ev.cert_fail.depth = depth;
1134 ev.cert_fail.subject = subject;
1135 ev.cert_fail.reason_txt = err_str;
1136 ev.cert_fail.cert = cert;
1137 tls_global->event_cb(tls_global->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1142 static void openssl_tls_cert_event(struct tls_connection *conn,
1143 X509 *err_cert, int depth,
1144 const char *subject)
1146 struct wpabuf *cert = NULL;
1147 union tls_event_data ev;
1148 #ifdef CONFIG_SHA256
1150 #endif /* CONFIG_SHA256 */
1152 if (tls_global->event_cb == NULL)
1155 os_memset(&ev, 0, sizeof(ev));
1156 if (conn->cert_probe || tls_global->cert_in_cb) {
1157 cert = get_x509_cert(err_cert);
1158 ev.peer_cert.cert = cert;
1160 #ifdef CONFIG_SHA256
1164 addr[0] = wpabuf_head(cert);
1165 len[0] = wpabuf_len(cert);
1166 if (sha256_vector(1, addr, len, hash) == 0) {
1167 ev.peer_cert.hash = hash;
1168 ev.peer_cert.hash_len = sizeof(hash);
1171 #endif /* CONFIG_SHA256 */
1172 ev.peer_cert.depth = depth;
1173 ev.peer_cert.subject = subject;
1174 tls_global->event_cb(tls_global->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1179 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1185 struct tls_connection *conn;
1186 char *match, *altmatch;
1187 const char *err_str;
1189 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1190 err = X509_STORE_CTX_get_error(x509_ctx);
1191 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1192 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1193 SSL_get_ex_data_X509_STORE_CTX_idx());
1194 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1196 conn = SSL_get_app_data(ssl);
1199 match = conn->subject_match;
1200 altmatch = conn->altsubject_match;
1202 if (!preverify_ok && !conn->ca_cert_verify)
1204 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1206 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1207 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1208 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1209 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1214 err_str = X509_verify_cert_error_string(err);
1216 #ifdef CONFIG_SHA256
1217 if (preverify_ok && depth == 0 && conn->server_cert_only) {
1218 struct wpabuf *cert;
1219 cert = get_x509_cert(err_cert);
1221 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1222 "server certificate data");
1228 addr[0] = wpabuf_head(cert);
1229 len[0] = wpabuf_len(cert);
1230 if (sha256_vector(1, addr, len, hash) < 0 ||
1231 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1232 err_str = "Server certificate mismatch";
1233 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1239 #endif /* CONFIG_SHA256 */
1241 if (!preverify_ok) {
1242 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1243 " error %d (%s) depth %d for '%s'", err, err_str,
1245 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1246 err_str, TLS_FAIL_UNSPECIFIED);
1247 return preverify_ok;
1250 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1251 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1252 preverify_ok, err, err_str,
1253 conn->ca_cert_verify, depth, buf);
1254 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1255 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1256 "match with '%s'", buf, match);
1258 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1260 TLS_FAIL_SUBJECT_MISMATCH);
1261 } else if (depth == 0 && altmatch &&
1262 !tls_match_altsubject(err_cert, altmatch)) {
1263 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1264 "'%s' not found", altmatch);
1266 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1267 "AltSubject mismatch",
1268 TLS_FAIL_ALTSUBJECT_MISMATCH);
1270 openssl_tls_cert_event(conn, err_cert, depth, buf);
1272 if (conn->cert_probe && preverify_ok && depth == 0) {
1273 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1274 "on probe-only run");
1276 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1277 "Server certificate chain probe",
1278 TLS_FAIL_SERVER_CHAIN_PROBE);
1281 if (preverify_ok && tls_global->event_cb != NULL)
1282 tls_global->event_cb(tls_global->cb_ctx,
1283 TLS_CERT_CHAIN_SUCCESS, NULL);
1285 return preverify_ok;
1289 #ifndef OPENSSL_NO_STDIO
1290 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1292 SSL_CTX *ssl_ctx = _ssl_ctx;
1293 X509_LOOKUP *lookup;
1296 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1297 X509_LOOKUP_file());
1298 if (lookup == NULL) {
1299 tls_show_errors(MSG_WARNING, __func__,
1300 "Failed add lookup for X509 store");
1304 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1305 unsigned long err = ERR_peek_error();
1306 tls_show_errors(MSG_WARNING, __func__,
1307 "Failed load CA in DER format");
1308 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1309 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1310 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1311 "cert already in hash table error",
1319 #endif /* OPENSSL_NO_STDIO */
1323 static BIO * BIO_from_keystore(const char *key)
1326 char value[KEYSTORE_MESSAGE_SIZE];
1327 int length = keystore_get(key, strlen(key), value);
1328 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
1329 BIO_write(bio, value, length);
1332 #endif /* ANDROID */
1335 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1336 const char *ca_cert, const u8 *ca_cert_blob,
1337 size_t ca_cert_blob_len, const char *ca_path)
1339 SSL_CTX *ssl_ctx = _ssl_ctx;
1342 * Remove previously configured trusted CA certificates before adding
1345 X509_STORE_free(ssl_ctx->cert_store);
1346 ssl_ctx->cert_store = X509_STORE_new();
1347 if (ssl_ctx->cert_store == NULL) {
1348 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1349 "certificate store", __func__);
1353 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1354 conn->ca_cert_verify = 1;
1356 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1357 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1359 conn->cert_probe = 1;
1360 conn->ca_cert_verify = 0;
1364 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1365 #ifdef CONFIG_SHA256
1366 const char *pos = ca_cert + 7;
1367 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1368 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1369 "hash value '%s'", ca_cert);
1373 if (os_strlen(pos) != 32 * 2) {
1374 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1375 "hash length in ca_cert '%s'", ca_cert);
1378 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1379 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1380 "value in ca_cert '%s'", ca_cert);
1383 conn->server_cert_only = 1;
1384 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1385 "certificate match");
1387 #else /* CONFIG_SHA256 */
1388 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1389 "cannot validate server certificate hash");
1391 #endif /* CONFIG_SHA256 */
1395 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1398 tls_show_errors(MSG_WARNING, __func__,
1399 "Failed to parse ca_cert_blob");
1403 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1404 unsigned long err = ERR_peek_error();
1405 tls_show_errors(MSG_WARNING, __func__,
1406 "Failed to add ca_cert_blob to "
1407 "certificate store");
1408 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1409 ERR_GET_REASON(err) ==
1410 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1411 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1412 "cert already in hash table error",
1420 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1421 "to certificate store", __func__);
1426 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1427 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1428 STACK_OF(X509_INFO) *stack = NULL;
1432 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1438 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1439 X509_INFO *info = sk_X509_INFO_value(stack, i);
1441 X509_STORE_add_cert(ssl_ctx->cert_store,
1445 X509_STORE_add_crl(ssl_ctx->cert_store,
1449 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1450 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1453 #endif /* ANDROID */
1455 #ifdef CONFIG_NATIVE_WINDOWS
1456 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1458 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1459 "system certificate store");
1462 #endif /* CONFIG_NATIVE_WINDOWS */
1464 if (ca_cert || ca_path) {
1465 #ifndef OPENSSL_NO_STDIO
1466 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1468 tls_show_errors(MSG_WARNING, __func__,
1469 "Failed to load root certificates");
1471 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1472 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1473 "DER format CA certificate",
1478 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1479 "certificate(s) loaded");
1480 tls_get_errors(ssl_ctx);
1482 #else /* OPENSSL_NO_STDIO */
1483 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1486 #endif /* OPENSSL_NO_STDIO */
1488 /* No ca_cert configured - do not try to verify server
1490 conn->ca_cert_verify = 0;
1497 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1500 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1502 tls_show_errors(MSG_WARNING, __func__,
1503 "Failed to load root certificates");
1507 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1508 "certificate(s) loaded");
1510 #ifndef OPENSSL_NO_STDIO
1511 /* Add the same CAs to the client certificate requests */
1512 SSL_CTX_set_client_CA_list(ssl_ctx,
1513 SSL_load_client_CA_file(ca_cert));
1514 #endif /* OPENSSL_NO_STDIO */
1521 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1526 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1528 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1529 "certificate store when enabling "
1533 flags = X509_V_FLAG_CRL_CHECK;
1535 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1536 X509_STORE_set_flags(cs, flags);
1542 static int tls_connection_set_subject_match(struct tls_connection *conn,
1543 const char *subject_match,
1544 const char *altsubject_match)
1546 os_free(conn->subject_match);
1547 conn->subject_match = NULL;
1548 if (subject_match) {
1549 conn->subject_match = os_strdup(subject_match);
1550 if (conn->subject_match == NULL)
1554 os_free(conn->altsubject_match);
1555 conn->altsubject_match = NULL;
1556 if (altsubject_match) {
1557 conn->altsubject_match = os_strdup(altsubject_match);
1558 if (conn->altsubject_match == NULL)
1566 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1569 static int counter = 0;
1575 conn->ca_cert_verify = 1;
1576 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1577 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1578 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1580 conn->ca_cert_verify = 0;
1581 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1584 SSL_set_accept_state(conn->ssl);
1587 * Set session id context in order to avoid fatal errors when client
1588 * tries to resume a session. However, set the context to a unique
1589 * value in order to effectively disable session resumption for now
1590 * since not all areas of the server code are ready for it (e.g.,
1591 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1595 SSL_set_session_id_context(conn->ssl,
1596 (const unsigned char *) &counter,
1603 static int tls_connection_client_cert(struct tls_connection *conn,
1604 const char *client_cert,
1605 const u8 *client_cert_blob,
1606 size_t client_cert_blob_len)
1608 if (client_cert == NULL && client_cert_blob == NULL)
1611 if (client_cert_blob &&
1612 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1613 client_cert_blob_len) == 1) {
1614 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1617 } else if (client_cert_blob) {
1618 tls_show_errors(MSG_DEBUG, __func__,
1619 "SSL_use_certificate_ASN1 failed");
1622 if (client_cert == NULL)
1626 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1627 BIO *bio = BIO_from_keystore(&client_cert[11]);
1631 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1635 if (SSL_use_certificate(conn->ssl, x509) == 1)
1641 #endif /* ANDROID */
1643 #ifndef OPENSSL_NO_STDIO
1644 if (SSL_use_certificate_file(conn->ssl, client_cert,
1645 SSL_FILETYPE_ASN1) == 1) {
1646 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1651 if (SSL_use_certificate_file(conn->ssl, client_cert,
1652 SSL_FILETYPE_PEM) == 1) {
1654 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1659 tls_show_errors(MSG_DEBUG, __func__,
1660 "SSL_use_certificate_file failed");
1661 #else /* OPENSSL_NO_STDIO */
1662 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1663 #endif /* OPENSSL_NO_STDIO */
1669 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1671 #ifndef OPENSSL_NO_STDIO
1672 if (client_cert == NULL)
1675 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1676 SSL_FILETYPE_ASN1) != 1 &&
1677 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
1678 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1679 SSL_FILETYPE_PEM) != 1) {
1680 tls_show_errors(MSG_INFO, __func__,
1681 "Failed to load client certificate");
1685 #else /* OPENSSL_NO_STDIO */
1686 if (client_cert == NULL)
1688 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1690 #endif /* OPENSSL_NO_STDIO */
1694 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1696 if (password == NULL) {
1699 os_strlcpy(buf, (char *) password, size);
1700 return os_strlen(buf);
1705 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1710 STACK_OF(X509) *certs;
1717 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1718 tls_show_errors(MSG_DEBUG, __func__,
1719 "Failed to parse PKCS12 file");
1723 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1726 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1728 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1729 "subject='%s'", buf);
1731 if (SSL_use_certificate(ssl, cert) != 1)
1734 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1741 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1743 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1746 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1749 EVP_PKEY_free(pkey);
1753 while ((cert = sk_X509_pop(certs)) != NULL) {
1754 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1756 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1757 " from PKCS12: subject='%s'", buf);
1759 * There is no SSL equivalent for the chain cert - so
1760 * always add it to the context...
1762 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1767 sk_X509_free(certs);
1773 tls_get_errors(ssl_ctx);
1777 #endif /* PKCS12_FUNCS */
1780 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1787 f = fopen(private_key, "rb");
1791 p12 = d2i_PKCS12_fp(f, NULL);
1795 tls_show_errors(MSG_INFO, __func__,
1796 "Failed to use PKCS#12 file");
1800 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1802 #else /* PKCS12_FUNCS */
1803 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1806 #endif /* PKCS12_FUNCS */
1810 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1811 const u8 *blob, size_t len, const char *passwd)
1816 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1818 tls_show_errors(MSG_INFO, __func__,
1819 "Failed to use PKCS#12 blob");
1823 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1825 #else /* PKCS12_FUNCS */
1826 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1829 #endif /* PKCS12_FUNCS */
1833 #ifndef OPENSSL_NO_ENGINE
1834 static int tls_engine_get_cert(struct tls_connection *conn,
1835 const char *cert_id,
1838 /* this runs after the private key is loaded so no PIN is required */
1840 const char *cert_id;
1843 params.cert_id = cert_id;
1846 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1847 0, ¶ms, NULL, 1)) {
1848 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1849 " '%s' [%s]", cert_id,
1850 ERR_error_string(ERR_get_error(), NULL));
1851 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1854 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1856 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1858 *cert = params.cert;
1861 #endif /* OPENSSL_NO_ENGINE */
1864 static int tls_connection_engine_client_cert(struct tls_connection *conn,
1865 const char *cert_id)
1867 #ifndef OPENSSL_NO_ENGINE
1870 if (tls_engine_get_cert(conn, cert_id, &cert))
1873 if (!SSL_use_certificate(conn->ssl, cert)) {
1874 tls_show_errors(MSG_ERROR, __func__,
1875 "SSL_use_certificate failed");
1880 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1884 #else /* OPENSSL_NO_ENGINE */
1886 #endif /* OPENSSL_NO_ENGINE */
1890 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1891 struct tls_connection *conn,
1892 const char *ca_cert_id)
1894 #ifndef OPENSSL_NO_ENGINE
1896 SSL_CTX *ssl_ctx = _ssl_ctx;
1898 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1901 /* start off the same as tls_connection_ca_cert */
1902 X509_STORE_free(ssl_ctx->cert_store);
1903 ssl_ctx->cert_store = X509_STORE_new();
1904 if (ssl_ctx->cert_store == NULL) {
1905 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1906 "certificate store", __func__);
1910 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1911 unsigned long err = ERR_peek_error();
1912 tls_show_errors(MSG_WARNING, __func__,
1913 "Failed to add CA certificate from engine "
1914 "to certificate store");
1915 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1916 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1917 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1918 " already in hash table error",
1926 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1927 "to certificate store", __func__);
1928 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1929 conn->ca_cert_verify = 1;
1933 #else /* OPENSSL_NO_ENGINE */
1935 #endif /* OPENSSL_NO_ENGINE */
1939 static int tls_connection_engine_private_key(struct tls_connection *conn)
1941 #ifndef OPENSSL_NO_ENGINE
1942 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1943 tls_show_errors(MSG_ERROR, __func__,
1944 "ENGINE: cannot use private key for TLS");
1947 if (!SSL_check_private_key(conn->ssl)) {
1948 tls_show_errors(MSG_INFO, __func__,
1949 "Private key failed verification");
1953 #else /* OPENSSL_NO_ENGINE */
1954 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1955 "engine support was not compiled in");
1957 #endif /* OPENSSL_NO_ENGINE */
1961 static int tls_connection_private_key(void *_ssl_ctx,
1962 struct tls_connection *conn,
1963 const char *private_key,
1964 const char *private_key_passwd,
1965 const u8 *private_key_blob,
1966 size_t private_key_blob_len)
1968 SSL_CTX *ssl_ctx = _ssl_ctx;
1972 if (private_key == NULL && private_key_blob == NULL)
1975 if (private_key_passwd) {
1976 passwd = os_strdup(private_key_passwd);
1982 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1983 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1986 while (private_key_blob) {
1987 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1988 (u8 *) private_key_blob,
1989 private_key_blob_len) == 1) {
1990 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1991 "ASN1(EVP_PKEY_RSA) --> OK");
1996 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1997 (u8 *) private_key_blob,
1998 private_key_blob_len) == 1) {
1999 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2000 "ASN1(EVP_PKEY_DSA) --> OK");
2005 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2006 (u8 *) private_key_blob,
2007 private_key_blob_len) == 1) {
2008 wpa_printf(MSG_DEBUG, "OpenSSL: "
2009 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2014 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2015 private_key_blob_len, passwd) == 0) {
2016 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2026 if (!ok && private_key &&
2027 os_strncmp("keystore://", private_key, 11) == 0) {
2028 BIO *bio = BIO_from_keystore(&private_key[11]);
2029 EVP_PKEY *pkey = NULL;
2031 pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
2035 if (SSL_use_PrivateKey(conn->ssl, pkey) == 1) {
2036 wpa_printf(MSG_DEBUG, "OpenSSL: Private key "
2040 EVP_PKEY_free(pkey);
2043 #endif /* ANDROID */
2045 while (!ok && private_key) {
2046 #ifndef OPENSSL_NO_STDIO
2047 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2048 SSL_FILETYPE_ASN1) == 1) {
2049 wpa_printf(MSG_DEBUG, "OpenSSL: "
2050 "SSL_use_PrivateKey_File (DER) --> OK");
2055 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2056 SSL_FILETYPE_PEM) == 1) {
2057 wpa_printf(MSG_DEBUG, "OpenSSL: "
2058 "SSL_use_PrivateKey_File (PEM) --> OK");
2062 #else /* OPENSSL_NO_STDIO */
2063 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2065 #endif /* OPENSSL_NO_STDIO */
2067 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2069 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2075 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2076 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2077 "access certificate store --> OK");
2086 tls_show_errors(MSG_INFO, __func__,
2087 "Failed to load private key");
2092 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2095 if (!SSL_check_private_key(conn->ssl)) {
2096 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2101 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2106 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2107 const char *private_key_passwd)
2111 if (private_key == NULL)
2114 if (private_key_passwd) {
2115 passwd = os_strdup(private_key_passwd);
2121 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2122 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2124 #ifndef OPENSSL_NO_STDIO
2125 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2126 SSL_FILETYPE_ASN1) != 1 &&
2127 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2128 SSL_FILETYPE_PEM) != 1 &&
2129 #endif /* OPENSSL_NO_STDIO */
2130 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2131 tls_show_errors(MSG_INFO, __func__,
2132 "Failed to load private key");
2139 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2141 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2142 tls_show_errors(MSG_INFO, __func__,
2143 "Private key failed verification");
2151 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2153 #ifdef OPENSSL_NO_DH
2154 if (dh_file == NULL)
2156 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2157 "dh_file specified");
2159 #else /* OPENSSL_NO_DH */
2163 /* TODO: add support for dh_blob */
2164 if (dh_file == NULL)
2169 bio = BIO_new_file(dh_file, "r");
2171 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2172 dh_file, ERR_error_string(ERR_get_error(), NULL));
2175 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2177 #ifndef OPENSSL_NO_DSA
2178 while (dh == NULL) {
2180 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2181 " trying to parse as DSA params", dh_file,
2182 ERR_error_string(ERR_get_error(), NULL));
2183 bio = BIO_new_file(dh_file, "r");
2186 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2189 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2190 "'%s': %s", dh_file,
2191 ERR_error_string(ERR_get_error(), NULL));
2195 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2196 dh = DSA_dup_DH(dsa);
2199 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2200 "params into DH params");
2205 #endif /* !OPENSSL_NO_DSA */
2207 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2212 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2213 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2215 ERR_error_string(ERR_get_error(), NULL));
2221 #endif /* OPENSSL_NO_DH */
2225 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2227 #ifdef OPENSSL_NO_DH
2228 if (dh_file == NULL)
2230 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2231 "dh_file specified");
2233 #else /* OPENSSL_NO_DH */
2237 /* TODO: add support for dh_blob */
2238 if (dh_file == NULL)
2240 if (ssl_ctx == NULL)
2243 bio = BIO_new_file(dh_file, "r");
2245 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2246 dh_file, ERR_error_string(ERR_get_error(), NULL));
2249 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2251 #ifndef OPENSSL_NO_DSA
2252 while (dh == NULL) {
2254 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2255 " trying to parse as DSA params", dh_file,
2256 ERR_error_string(ERR_get_error(), NULL));
2257 bio = BIO_new_file(dh_file, "r");
2260 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2263 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2264 "'%s': %s", dh_file,
2265 ERR_error_string(ERR_get_error(), NULL));
2269 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2270 dh = DSA_dup_DH(dsa);
2273 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2274 "params into DH params");
2279 #endif /* !OPENSSL_NO_DSA */
2281 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2286 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2287 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2289 ERR_error_string(ERR_get_error(), NULL));
2295 #endif /* OPENSSL_NO_DH */
2299 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2300 struct tls_keys *keys)
2303 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2306 #else /* CONFIG_FIPS */
2309 if (conn == NULL || keys == NULL)
2312 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2315 os_memset(keys, 0, sizeof(*keys));
2316 keys->master_key = ssl->session->master_key;
2317 keys->master_key_len = ssl->session->master_key_length;
2318 keys->client_random = ssl->s3->client_random;
2319 keys->client_random_len = SSL3_RANDOM_SIZE;
2320 keys->server_random = ssl->s3->server_random;
2321 keys->server_random_len = SSL3_RANDOM_SIZE;
2324 #endif /* CONFIG_FIPS */
2328 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2329 const char *label, int server_random_first,
2330 u8 *out, size_t out_len)
2332 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2336 if (server_random_first)
2339 if (SSL_export_keying_material(ssl, out, out_len, label,
2340 os_strlen(label), NULL, 0, 0) == 1) {
2341 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2349 static struct wpabuf *
2350 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2354 struct wpabuf *out_data;
2357 * Give TLS handshake data from the server (if available) to OpenSSL
2361 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2363 tls_show_errors(MSG_INFO, __func__,
2364 "Handshake failed - BIO_write");
2368 /* Initiate TLS handshake or continue the existing handshake */
2370 res = SSL_accept(conn->ssl);
2372 res = SSL_connect(conn->ssl);
2374 int err = SSL_get_error(conn->ssl, res);
2375 if (err == SSL_ERROR_WANT_READ)
2376 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2378 else if (err == SSL_ERROR_WANT_WRITE)
2379 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2382 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2387 /* Get the TLS handshake data to be sent to the server */
2388 res = BIO_ctrl_pending(conn->ssl_out);
2389 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2390 out_data = wpabuf_alloc(res);
2391 if (out_data == NULL) {
2392 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2393 "handshake output (%d bytes)", res);
2394 if (BIO_reset(conn->ssl_out) < 0) {
2395 tls_show_errors(MSG_INFO, __func__,
2396 "BIO_reset failed");
2400 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2403 tls_show_errors(MSG_INFO, __func__,
2404 "Handshake failed - BIO_read");
2405 if (BIO_reset(conn->ssl_out) < 0) {
2406 tls_show_errors(MSG_INFO, __func__,
2407 "BIO_reset failed");
2409 wpabuf_free(out_data);
2412 wpabuf_put(out_data, res);
2418 static struct wpabuf *
2419 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2421 struct wpabuf *appl_data;
2424 appl_data = wpabuf_alloc(max_len + 100);
2425 if (appl_data == NULL)
2428 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2429 wpabuf_size(appl_data));
2431 int err = SSL_get_error(conn->ssl, res);
2432 if (err == SSL_ERROR_WANT_READ ||
2433 err == SSL_ERROR_WANT_WRITE) {
2434 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2437 tls_show_errors(MSG_INFO, __func__,
2438 "Failed to read possible "
2439 "Application Data");
2441 wpabuf_free(appl_data);
2445 wpabuf_put(appl_data, res);
2446 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2447 "message", appl_data);
2453 static struct wpabuf *
2454 openssl_connection_handshake(struct tls_connection *conn,
2455 const struct wpabuf *in_data,
2456 struct wpabuf **appl_data, int server)
2458 struct wpabuf *out_data;
2463 out_data = openssl_handshake(conn, in_data, server);
2464 if (out_data == NULL)
2467 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2468 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2475 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2476 const struct wpabuf *in_data,
2477 struct wpabuf **appl_data)
2479 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2483 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2484 struct tls_connection *conn,
2485 const struct wpabuf *in_data,
2486 struct wpabuf **appl_data)
2488 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2492 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2493 struct tls_connection *conn,
2494 const struct wpabuf *in_data)
2502 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2503 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2504 (res = BIO_reset(conn->ssl_out)) < 0) {
2505 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2508 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2510 tls_show_errors(MSG_INFO, __func__,
2511 "Encryption failed - SSL_write");
2515 /* Read encrypted data to be sent to the server */
2516 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2519 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2521 tls_show_errors(MSG_INFO, __func__,
2522 "Encryption failed - BIO_read");
2526 wpabuf_put(buf, res);
2532 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2533 struct tls_connection *conn,
2534 const struct wpabuf *in_data)
2539 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2540 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2541 wpabuf_len(in_data));
2543 tls_show_errors(MSG_INFO, __func__,
2544 "Decryption failed - BIO_write");
2547 if (BIO_reset(conn->ssl_out) < 0) {
2548 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2552 /* Read decrypted data for further processing */
2554 * Even though we try to disable TLS compression, it is possible that
2555 * this cannot be done with all TLS libraries. Add extra buffer space
2556 * to handle the possibility of the decrypted data being longer than
2559 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2562 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2564 tls_show_errors(MSG_INFO, __func__,
2565 "Decryption failed - SSL_read");
2569 wpabuf_put(buf, res);
2575 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2577 return conn ? conn->ssl->hit : 0;
2581 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2584 char buf[100], *pos, *end;
2588 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2593 end = pos + sizeof(buf);
2596 while (*c != TLS_CIPHER_NONE) {
2600 case TLS_CIPHER_RC4_SHA:
2603 case TLS_CIPHER_AES128_SHA:
2604 suite = "AES128-SHA";
2606 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2607 suite = "DHE-RSA-AES128-SHA";
2609 case TLS_CIPHER_ANON_DH_AES128_SHA:
2610 suite = "ADH-AES128-SHA";
2613 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2614 "cipher selection: %d", *c);
2617 ret = os_snprintf(pos, end - pos, ":%s", suite);
2618 if (ret < 0 || ret >= end - pos)
2625 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2627 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2628 tls_show_errors(MSG_INFO, __func__,
2629 "Cipher suite configuration failed");
2637 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2638 char *buf, size_t buflen)
2641 if (conn == NULL || conn->ssl == NULL)
2644 name = SSL_get_cipher(conn->ssl);
2648 os_strlcpy(buf, name, buflen);
2653 int tls_connection_enable_workaround(void *ssl_ctx,
2654 struct tls_connection *conn)
2656 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2662 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2663 /* ClientHello TLS extensions require a patch to openssl, so this function is
2664 * commented out unless explicitly needed for EAP-FAST in order to be able to
2665 * build this file with unmodified openssl. */
2666 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2667 int ext_type, const u8 *data,
2670 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2673 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2674 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2677 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2678 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2681 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2685 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2688 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2692 return conn->failed;
2696 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2700 return conn->read_alerts;
2704 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2708 return conn->write_alerts;
2712 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2713 const struct tls_connection_params *params)
2721 while ((err = ERR_get_error())) {
2722 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2723 __func__, ERR_error_string(err, NULL));
2726 if (params->engine) {
2727 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2728 ret = tls_engine_init(conn, params->engine_id, params->pin,
2729 params->key_id, params->cert_id,
2730 params->ca_cert_id);
2734 if (tls_connection_set_subject_match(conn,
2735 params->subject_match,
2736 params->altsubject_match))
2739 if (params->engine && params->ca_cert_id) {
2740 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2741 params->ca_cert_id))
2742 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2743 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2744 params->ca_cert_blob,
2745 params->ca_cert_blob_len,
2749 if (params->engine && params->cert_id) {
2750 if (tls_connection_engine_client_cert(conn, params->cert_id))
2751 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2752 } else if (tls_connection_client_cert(conn, params->client_cert,
2753 params->client_cert_blob,
2754 params->client_cert_blob_len))
2757 if (params->engine && params->key_id) {
2758 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2759 if (tls_connection_engine_private_key(conn))
2760 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2761 } else if (tls_connection_private_key(tls_ctx, conn,
2762 params->private_key,
2763 params->private_key_passwd,
2764 params->private_key_blob,
2765 params->private_key_blob_len)) {
2766 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2767 params->private_key);
2771 if (tls_connection_dh(conn, params->dh_file)) {
2772 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2777 #ifdef SSL_OP_NO_TICKET
2778 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
2779 SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
2781 SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
2782 #endif /* SSL_OP_NO_TICKET */
2784 conn->flags = params->flags;
2786 tls_get_errors(tls_ctx);
2792 int tls_global_set_params(void *tls_ctx,
2793 const struct tls_connection_params *params)
2795 SSL_CTX *ssl_ctx = tls_ctx;
2798 while ((err = ERR_get_error())) {
2799 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2800 __func__, ERR_error_string(err, NULL));
2803 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2806 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2809 if (tls_global_private_key(ssl_ctx, params->private_key,
2810 params->private_key_passwd))
2813 if (tls_global_dh(ssl_ctx, params->dh_file)) {
2814 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2819 #ifdef SSL_OP_NO_TICKET
2820 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
2821 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
2823 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
2824 #endif /* SSL_OP_NO_TICKET */
2830 int tls_connection_get_keyblock_size(void *tls_ctx,
2831 struct tls_connection *conn)
2833 const EVP_CIPHER *c;
2837 if (conn == NULL || conn->ssl == NULL ||
2838 conn->ssl->enc_read_ctx == NULL ||
2839 conn->ssl->enc_read_ctx->cipher == NULL ||
2840 conn->ssl->read_hash == NULL)
2843 c = conn->ssl->enc_read_ctx->cipher;
2844 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2845 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2847 h = conn->ssl->read_hash;
2850 md_size = EVP_MD_size(h);
2851 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2852 else if (conn->ssl->s3)
2853 md_size = conn->ssl->s3->tmp.new_mac_secret_size;
2858 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2859 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2860 EVP_CIPHER_iv_length(c));
2861 return 2 * (EVP_CIPHER_key_length(c) +
2863 EVP_CIPHER_iv_length(c));
2867 unsigned int tls_capabilities(void *tls_ctx)
2873 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2874 /* Pre-shared secred requires a patch to openssl, so this function is
2875 * commented out unless explicitly needed for EAP-FAST in order to be able to
2876 * build this file with unmodified openssl. */
2878 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2879 STACK_OF(SSL_CIPHER) *peer_ciphers,
2880 SSL_CIPHER **cipher, void *arg)
2882 struct tls_connection *conn = arg;
2885 if (conn == NULL || conn->session_ticket_cb == NULL)
2888 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2889 conn->session_ticket,
2890 conn->session_ticket_len,
2891 s->s3->client_random,
2892 s->s3->server_random, secret);
2893 os_free(conn->session_ticket);
2894 conn->session_ticket = NULL;
2899 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2904 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2905 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
2908 struct tls_connection *conn = arg;
2910 if (conn == NULL || conn->session_ticket_cb == NULL)
2913 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
2915 os_free(conn->session_ticket);
2916 conn->session_ticket = NULL;
2918 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2919 "extension", data, len);
2921 conn->session_ticket = os_malloc(len);
2922 if (conn->session_ticket == NULL)
2925 os_memcpy(conn->session_ticket, data, len);
2926 conn->session_ticket_len = len;
2930 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2931 #ifdef SSL_OP_NO_TICKET
2932 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2933 unsigned char *data, int len, void *arg)
2935 struct tls_connection *conn = arg;
2937 if (conn == NULL || conn->session_ticket_cb == NULL)
2940 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2943 if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2944 os_free(conn->session_ticket);
2945 conn->session_ticket = NULL;
2947 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2948 "extension", data, len);
2949 conn->session_ticket = os_malloc(len);
2950 if (conn->session_ticket == NULL)
2953 os_memcpy(conn->session_ticket, data, len);
2954 conn->session_ticket_len = len;
2957 #else /* SSL_OP_NO_TICKET */
2958 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2960 struct tls_connection *conn = arg;
2962 if (conn == NULL || conn->session_ticket_cb == NULL)
2965 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2966 ext->type, ext->length);
2968 os_free(conn->session_ticket);
2969 conn->session_ticket = NULL;
2971 if (ext->type == 35) {
2972 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2973 "extension", ext->data, ext->length);
2974 conn->session_ticket = os_malloc(ext->length);
2975 if (conn->session_ticket == NULL)
2976 return SSL_AD_INTERNAL_ERROR;
2978 os_memcpy(conn->session_ticket, ext->data, ext->length);
2979 conn->session_ticket_len = ext->length;
2984 #endif /* SSL_OP_NO_TICKET */
2985 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2986 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2989 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2990 struct tls_connection *conn,
2991 tls_session_ticket_cb cb,
2994 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2995 conn->session_ticket_cb = cb;
2996 conn->session_ticket_cb_ctx = ctx;
2999 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3002 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
3003 SSL_set_session_ticket_ext_cb(conn->ssl,
3004 tls_session_ticket_ext_cb, conn);
3005 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3006 #ifdef SSL_OP_NO_TICKET
3007 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
3008 SSL_set_tlsext_debug_arg(conn->ssl, conn);
3009 #else /* SSL_OP_NO_TICKET */
3010 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
3013 #endif /* SSL_OP_NO_TICKET */
3014 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3016 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3018 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
3019 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
3020 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3021 #ifdef SSL_OP_NO_TICKET
3022 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
3023 SSL_set_tlsext_debug_arg(conn->ssl, conn);
3024 #else /* SSL_OP_NO_TICKET */
3025 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
3027 #endif /* SSL_OP_NO_TICKET */
3028 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
3032 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3034 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */