2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2010, 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 */
35 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
36 #define OPENSSL_d2i_TYPE const unsigned char **
38 #define OPENSSL_d2i_TYPE unsigned char **
41 #ifdef SSL_F_SSL_SET_SESSION_TICKET_EXT
42 #ifdef SSL_OP_NO_TICKET
44 * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
45 * 2008-11-15. This version uses a bit different API compared to the old patch.
47 #define CONFIG_OPENSSL_TICKET_OVERRIDE
51 static int tls_openssl_ref_count = 0;
54 void (*event_cb)(void *ctx, enum tls_event ev,
55 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;
87 #ifdef CONFIG_NO_STDOUT_DEBUG
89 static void _tls_show_errors(void)
93 while ((err = ERR_get_error())) {
94 /* Just ignore the errors, since stdout is disabled */
97 #define tls_show_errors(l, f, t) _tls_show_errors()
99 #else /* CONFIG_NO_STDOUT_DEBUG */
101 static void tls_show_errors(int level, const char *func, const char *txt)
105 wpa_printf(level, "OpenSSL: %s - %s %s",
106 func, txt, ERR_error_string(ERR_get_error(), NULL));
108 while ((err = ERR_get_error())) {
109 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
110 ERR_error_string(err, NULL));
114 #endif /* CONFIG_NO_STDOUT_DEBUG */
117 #ifdef CONFIG_NATIVE_WINDOWS
119 /* Windows CryptoAPI and access to certificate stores */
120 #include <wincrypt.h>
122 #ifdef __MINGW32_VERSION
124 * MinGW does not yet include all the needed definitions for CryptoAPI, so
125 * define here whatever extra is needed.
127 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
128 #define CERT_STORE_READONLY_FLAG 0x00008000
129 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
131 #endif /* __MINGW32_VERSION */
134 struct cryptoapi_rsa_data {
135 const CERT_CONTEXT *cert;
136 HCRYPTPROV crypt_prov;
138 BOOL free_crypt_prov;
142 static void cryptoapi_error(const char *msg)
144 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
145 msg, (unsigned int) GetLastError());
149 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
150 unsigned char *to, RSA *rsa, int padding)
152 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
157 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
158 unsigned char *to, RSA *rsa, int padding)
160 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
165 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
166 unsigned char *to, RSA *rsa, int padding)
168 struct cryptoapi_rsa_data *priv =
169 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
171 DWORD hash_size, len, i;
172 unsigned char *buf = NULL;
176 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
177 ERR_R_PASSED_NULL_PARAMETER);
181 if (padding != RSA_PKCS1_PADDING) {
182 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
183 RSA_R_UNKNOWN_PADDING_TYPE);
187 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
188 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
190 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
191 RSA_R_INVALID_MESSAGE_LENGTH);
195 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
197 cryptoapi_error("CryptCreateHash failed");
201 len = sizeof(hash_size);
202 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
204 cryptoapi_error("CryptGetHashParam failed");
208 if ((int) hash_size != flen) {
209 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
210 (unsigned) hash_size, flen);
211 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
212 RSA_R_INVALID_MESSAGE_LENGTH);
215 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
216 cryptoapi_error("CryptSetHashParam failed");
221 buf = os_malloc(len);
223 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
227 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
228 cryptoapi_error("CryptSignHash failed");
232 for (i = 0; i < len; i++)
233 to[i] = buf[len - i - 1];
238 CryptDestroyHash(hash);
244 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
245 unsigned char *to, RSA *rsa, int padding)
247 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
252 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
256 if (priv->crypt_prov && priv->free_crypt_prov)
257 CryptReleaseContext(priv->crypt_prov, 0);
259 CertFreeCertificateContext(priv->cert);
264 static int cryptoapi_finish(RSA *rsa)
266 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
267 os_free((void *) rsa->meth);
273 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
276 const CERT_CONTEXT *ret = NULL;
278 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
279 store | CERT_STORE_OPEN_EXISTING_FLAG |
280 CERT_STORE_READONLY_FLAG, L"MY");
282 cryptoapi_error("Failed to open 'My system store'");
286 if (strncmp(name, "cert://", 7) == 0) {
287 unsigned short wbuf[255];
288 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
289 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
291 0, CERT_FIND_SUBJECT_STR,
293 } else if (strncmp(name, "hash://", 7) == 0) {
294 CRYPT_HASH_BLOB blob;
296 const char *hash = name + 7;
299 len = os_strlen(hash) / 2;
300 buf = os_malloc(len);
301 if (buf && hexstr2bin(hash, buf, len) == 0) {
304 ret = CertFindCertificateInStore(cs,
313 CertCloseStore(cs, 0);
319 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
322 RSA *rsa = NULL, *pub_rsa;
323 struct cryptoapi_rsa_data *priv;
324 RSA_METHOD *rsa_meth;
327 (strncmp(name, "cert://", 7) != 0 &&
328 strncmp(name, "hash://", 7) != 0))
331 priv = os_zalloc(sizeof(*priv));
332 rsa_meth = os_zalloc(sizeof(*rsa_meth));
333 if (priv == NULL || rsa_meth == NULL) {
334 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
335 "for CryptoAPI RSA method");
341 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
342 if (priv->cert == NULL) {
343 priv->cert = cryptoapi_find_cert(
344 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
346 if (priv->cert == NULL) {
347 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
352 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
353 priv->cert->cbCertEncoded);
355 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
360 if (!CryptAcquireCertificatePrivateKey(priv->cert,
361 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
362 NULL, &priv->crypt_prov,
364 &priv->free_crypt_prov)) {
365 cryptoapi_error("Failed to acquire a private key for the "
370 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
371 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
372 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
373 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
374 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
375 rsa_meth->finish = cryptoapi_finish;
376 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
377 rsa_meth->app_data = (char *) priv;
381 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
382 ERR_R_MALLOC_FAILURE);
386 if (!SSL_use_certificate(ssl, cert)) {
391 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
395 rsa->n = BN_dup(pub_rsa->n);
396 rsa->e = BN_dup(pub_rsa->e);
397 if (!RSA_set_method(rsa, rsa_meth))
400 if (!SSL_use_RSAPrivateKey(ssl, rsa))
413 cryptoapi_free_data(priv);
419 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
422 PCCERT_CONTEXT ctx = NULL;
430 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
435 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
438 wsprintf(wstore, L"%S", store);
439 cs = CertOpenSystemStore(0, wstore);
442 cs = CertOpenSystemStore(0, store);
445 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
446 "'%s': error=%d", __func__, store,
447 (int) GetLastError());
451 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
452 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
455 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
456 "X509 DER encoding for CA cert");
460 X509_NAME_oneline(X509_get_subject_name(cert), buf,
462 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
463 "system certificate store: subject='%s'", buf);
465 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
466 tls_show_errors(MSG_WARNING, __func__,
467 "Failed to add ca_cert to OpenSSL "
468 "certificate store");
474 if (!CertCloseStore(cs, 0)) {
475 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
476 "'%s': error=%d", __func__, name + 13,
477 (int) GetLastError());
484 #else /* CONFIG_NATIVE_WINDOWS */
486 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
491 #endif /* CONFIG_NATIVE_WINDOWS */
494 static void ssl_info_cb(const SSL *ssl, int where, int ret)
499 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
500 w = where & ~SSL_ST_MASK;
501 if (w & SSL_ST_CONNECT)
503 else if (w & SSL_ST_ACCEPT)
508 if (where & SSL_CB_LOOP) {
509 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
510 str, SSL_state_string_long(ssl));
511 } else if (where & SSL_CB_ALERT) {
512 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
513 where & SSL_CB_READ ?
514 "read (remote end reported an error)" :
515 "write (local SSL3 detected an error)",
516 SSL_alert_type_string_long(ret),
517 SSL_alert_desc_string_long(ret));
518 if ((ret >> 8) == SSL3_AL_FATAL) {
519 struct tls_connection *conn =
520 SSL_get_app_data((SSL *) ssl);
521 if (where & SSL_CB_READ)
524 conn->write_alerts++;
526 } else if (where & SSL_CB_EXIT && ret <= 0) {
527 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
528 str, ret == 0 ? "failed" : "error",
529 SSL_state_string_long(ssl));
534 #ifndef OPENSSL_NO_ENGINE
536 * tls_engine_load_dynamic_generic - load any openssl engine
537 * @pre: an array of commands and values that load an engine initialized
538 * in the engine specific function
539 * @post: an array of commands and values that initialize an already loaded
540 * engine (or %NULL if not required)
541 * @id: the engine id of the engine to load (only required if post is not %NULL
543 * This function is a generic function that loads any openssl engine.
545 * Returns: 0 on success, -1 on failure
547 static int tls_engine_load_dynamic_generic(const char *pre[],
548 const char *post[], const char *id)
551 const char *dynamic_id = "dynamic";
553 engine = ENGINE_by_id(id);
556 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
562 engine = ENGINE_by_id(dynamic_id);
563 if (engine == NULL) {
564 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
566 ERR_error_string(ERR_get_error(), NULL));
570 /* Perform the pre commands. This will load the engine. */
571 while (pre && pre[0]) {
572 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
573 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
574 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
575 "%s %s [%s]", pre[0], pre[1],
576 ERR_error_string(ERR_get_error(), NULL));
584 * Free the reference to the "dynamic" engine. The loaded engine can
585 * now be looked up using ENGINE_by_id().
589 engine = ENGINE_by_id(id);
590 if (engine == NULL) {
591 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
592 id, ERR_error_string(ERR_get_error(), NULL));
596 while (post && post[0]) {
597 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
598 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
599 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
600 " %s %s [%s]", post[0], post[1],
601 ERR_error_string(ERR_get_error(), NULL));
602 ENGINE_remove(engine);
615 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
616 * @pkcs11_so_path: pksc11_so_path from the configuration
617 * @pcks11_module_path: pkcs11_module_path from the configuration
619 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
620 const char *pkcs11_module_path)
622 char *engine_id = "pkcs11";
623 const char *pre_cmd[] = {
624 "SO_PATH", NULL /* pkcs11_so_path */,
625 "ID", NULL /* engine_id */,
627 /* "NO_VCHECK", "1", */
631 const char *post_cmd[] = {
632 "MODULE_PATH", NULL /* pkcs11_module_path */,
636 if (!pkcs11_so_path || !pkcs11_module_path)
639 pre_cmd[1] = pkcs11_so_path;
640 pre_cmd[3] = engine_id;
641 post_cmd[1] = pkcs11_module_path;
643 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
646 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
651 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
652 * @opensc_so_path: opensc_so_path from the configuration
654 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
656 char *engine_id = "opensc";
657 const char *pre_cmd[] = {
658 "SO_PATH", NULL /* opensc_so_path */,
659 "ID", NULL /* engine_id */,
668 pre_cmd[1] = opensc_so_path;
669 pre_cmd[3] = engine_id;
671 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
674 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
676 #endif /* OPENSSL_NO_ENGINE */
679 void * tls_init(const struct tls_config *conf)
683 if (tls_openssl_ref_count == 0) {
684 tls_global = os_zalloc(sizeof(*tls_global));
685 if (tls_global == NULL)
688 tls_global->event_cb = conf->event_cb;
689 tls_global->cb_ctx = conf->cb_ctx;
694 if (conf && conf->fips_mode) {
695 if (!FIPS_mode_set(1)) {
696 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
698 ERR_load_crypto_strings();
699 ERR_print_errors_fp(stderr);
702 wpa_printf(MSG_INFO, "Running in FIPS mode");
704 #else /* OPENSSL_FIPS */
705 if (conf && conf->fips_mode) {
706 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
710 #endif /* OPENSSL_FIPS */
711 #endif /* CONFIG_FIPS */
712 SSL_load_error_strings();
714 #ifndef OPENSSL_NO_SHA256
715 EVP_add_digest(EVP_sha256());
716 #endif /* OPENSSL_NO_SHA256 */
717 /* TODO: if /dev/urandom is available, PRNG is seeded
718 * automatically. If this is not the case, random data should
722 #ifndef OPENSSL_NO_RC2
724 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
725 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
726 * versions, but it looks like OpenSSL 1.0.0 does not do that
729 EVP_add_cipher(EVP_rc2_40_cbc());
730 #endif /* OPENSSL_NO_RC2 */
732 #endif /* PKCS12_FUNCS */
734 tls_openssl_ref_count++;
736 ssl = SSL_CTX_new(TLSv1_method());
740 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
742 #ifndef OPENSSL_NO_ENGINE
744 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
745 conf->pkcs11_module_path)) {
746 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
747 ERR_load_ENGINE_strings();
748 ENGINE_load_dynamic();
750 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
751 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
752 conf->pkcs11_module_path)) {
757 #endif /* OPENSSL_NO_ENGINE */
763 void tls_deinit(void *ssl_ctx)
765 SSL_CTX *ssl = ssl_ctx;
768 tls_openssl_ref_count--;
769 if (tls_openssl_ref_count == 0) {
770 #ifndef OPENSSL_NO_ENGINE
772 #endif /* OPENSSL_NO_ENGINE */
773 CRYPTO_cleanup_all_ex_data();
783 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
784 const char *pin, const char *key_id,
785 const char *cert_id, const char *ca_cert_id)
787 #ifndef OPENSSL_NO_ENGINE
789 if (engine_id == NULL) {
790 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
794 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
797 if (key_id == NULL) {
798 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
803 conn->engine = ENGINE_by_id(engine_id);
805 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
806 engine_id, ERR_error_string(ERR_get_error(), NULL));
809 if (ENGINE_init(conn->engine) != 1) {
810 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
811 "(engine: %s) [%s]", engine_id,
812 ERR_error_string(ERR_get_error(), NULL));
815 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
817 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
818 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
819 ERR_error_string(ERR_get_error(), NULL));
822 /* load private key first in-case PIN is required for cert */
823 conn->private_key = ENGINE_load_private_key(conn->engine,
825 if (!conn->private_key) {
826 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
827 " '%s' [%s]", key_id,
828 ERR_error_string(ERR_get_error(), NULL));
829 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
833 /* handle a certificate and/or CA certificate */
834 if (cert_id || ca_cert_id) {
835 const char *cmd_name = "LOAD_CERT_CTRL";
837 /* test if the engine supports a LOAD_CERT_CTRL */
838 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
839 0, (void *)cmd_name, NULL)) {
840 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
841 " loading certificates");
842 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
851 ENGINE_free(conn->engine);
855 if (conn->private_key) {
856 EVP_PKEY_free(conn->private_key);
857 conn->private_key = NULL;
861 #else /* OPENSSL_NO_ENGINE */
863 #endif /* OPENSSL_NO_ENGINE */
867 static void tls_engine_deinit(struct tls_connection *conn)
869 #ifndef OPENSSL_NO_ENGINE
870 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
871 if (conn->private_key) {
872 EVP_PKEY_free(conn->private_key);
873 conn->private_key = NULL;
876 ENGINE_finish(conn->engine);
879 #endif /* OPENSSL_NO_ENGINE */
883 int tls_get_errors(void *ssl_ctx)
888 while ((err = ERR_get_error())) {
889 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
890 ERR_error_string(err, NULL));
897 struct tls_connection * tls_connection_init(void *ssl_ctx)
899 SSL_CTX *ssl = ssl_ctx;
900 struct tls_connection *conn;
903 conn = os_zalloc(sizeof(*conn));
906 conn->ssl = SSL_new(ssl);
907 if (conn->ssl == NULL) {
908 tls_show_errors(MSG_INFO, __func__,
909 "Failed to initialize new SSL connection");
914 SSL_set_app_data(conn->ssl, conn);
915 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
916 SSL_OP_SINGLE_DH_USE;
917 #ifdef SSL_OP_NO_COMPRESSION
918 options |= SSL_OP_NO_COMPRESSION;
919 #endif /* SSL_OP_NO_COMPRESSION */
920 SSL_set_options(conn->ssl, options);
922 conn->ssl_in = BIO_new(BIO_s_mem());
924 tls_show_errors(MSG_INFO, __func__,
925 "Failed to create a new BIO for ssl_in");
931 conn->ssl_out = BIO_new(BIO_s_mem());
932 if (!conn->ssl_out) {
933 tls_show_errors(MSG_INFO, __func__,
934 "Failed to create a new BIO for ssl_out");
936 BIO_free(conn->ssl_in);
941 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
947 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
952 tls_engine_deinit(conn);
953 os_free(conn->subject_match);
954 os_free(conn->altsubject_match);
955 os_free(conn->session_ticket);
960 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
962 return conn ? SSL_is_init_finished(conn->ssl) : 0;
966 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
971 /* Shutdown previous TLS connection without notifying the peer
972 * because the connection was already terminated in practice
973 * and "close notify" shutdown alert would confuse AS. */
974 SSL_set_quiet_shutdown(conn->ssl, 1);
975 SSL_shutdown(conn->ssl);
980 static int tls_match_altsubject_component(X509 *cert, int type,
981 const char *value, size_t len)
987 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
989 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
990 gen = sk_GENERAL_NAME_value(ext, i);
991 if (gen->type != type)
993 if (os_strlen((char *) gen->d.ia5->data) == len &&
994 os_memcmp(value, gen->d.ia5->data, len) == 0)
1002 static int tls_match_altsubject(X509 *cert, const char *match)
1005 const char *pos, *end;
1010 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1013 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1016 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1020 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1024 end = os_strchr(pos, ';');
1026 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1027 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1028 os_strncmp(end + 1, "URI:", 4) == 0)
1030 end = os_strchr(end + 1, ';');
1035 len = os_strlen(pos);
1036 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1045 static enum tls_fail_reason openssl_tls_fail_reason(int err)
1048 case X509_V_ERR_CERT_REVOKED:
1049 return TLS_FAIL_REVOKED;
1050 case X509_V_ERR_CERT_NOT_YET_VALID:
1051 case X509_V_ERR_CRL_NOT_YET_VALID:
1052 return TLS_FAIL_NOT_YET_VALID;
1053 case X509_V_ERR_CERT_HAS_EXPIRED:
1054 case X509_V_ERR_CRL_HAS_EXPIRED:
1055 return TLS_FAIL_EXPIRED;
1056 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1057 case X509_V_ERR_UNABLE_TO_GET_CRL:
1058 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1059 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1060 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1061 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1062 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1063 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1064 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1065 case X509_V_ERR_INVALID_CA:
1066 return TLS_FAIL_UNTRUSTED;
1067 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1068 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1069 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1070 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1071 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1072 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1073 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1074 case X509_V_ERR_CERT_UNTRUSTED:
1075 case X509_V_ERR_CERT_REJECTED:
1076 return TLS_FAIL_BAD_CERTIFICATE;
1078 return TLS_FAIL_UNSPECIFIED;
1083 static struct wpabuf * get_x509_cert(X509 *cert)
1088 int cert_len = i2d_X509(cert, NULL);
1092 buf = wpabuf_alloc(cert_len);
1096 tmp = wpabuf_put(buf, cert_len);
1097 i2d_X509(cert, &tmp);
1102 static void openssl_tls_fail_event(struct tls_connection *conn,
1103 X509 *err_cert, int err, int depth,
1104 const char *subject, const char *err_str,
1105 enum tls_fail_reason reason)
1107 union tls_event_data ev;
1108 struct wpabuf *cert = NULL;
1110 if (tls_global->event_cb == NULL)
1113 cert = get_x509_cert(err_cert);
1114 os_memset(&ev, 0, sizeof(ev));
1115 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1116 reason : openssl_tls_fail_reason(err);
1117 ev.cert_fail.depth = depth;
1118 ev.cert_fail.subject = subject;
1119 ev.cert_fail.reason_txt = err_str;
1120 ev.cert_fail.cert = cert;
1121 tls_global->event_cb(tls_global->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
1126 static void openssl_tls_cert_event(struct tls_connection *conn,
1127 X509 *err_cert, int depth,
1128 const char *subject)
1130 struct wpabuf *cert = NULL;
1131 union tls_event_data ev;
1132 #ifdef CONFIG_SHA256
1134 #endif /* CONFIG_SHA256 */
1136 if (tls_global->event_cb == NULL)
1139 os_memset(&ev, 0, sizeof(ev));
1140 if (conn->cert_probe) {
1141 cert = get_x509_cert(err_cert);
1142 ev.peer_cert.cert = cert;
1144 #ifdef CONFIG_SHA256
1148 addr[0] = wpabuf_head(cert);
1149 len[0] = wpabuf_len(cert);
1150 if (sha256_vector(1, addr, len, hash) == 0) {
1151 ev.peer_cert.hash = hash;
1152 ev.peer_cert.hash_len = sizeof(hash);
1155 #endif /* CONFIG_SHA256 */
1156 ev.peer_cert.depth = depth;
1157 ev.peer_cert.subject = subject;
1158 tls_global->event_cb(tls_global->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
1163 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1169 struct tls_connection *conn;
1170 char *match, *altmatch;
1171 const char *err_str;
1173 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1174 err = X509_STORE_CTX_get_error(x509_ctx);
1175 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1176 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1177 SSL_get_ex_data_X509_STORE_CTX_idx());
1178 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1180 conn = SSL_get_app_data(ssl);
1181 match = conn ? conn->subject_match : NULL;
1182 altmatch = conn ? conn->altsubject_match : NULL;
1184 if (!preverify_ok && !conn->ca_cert_verify)
1186 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1189 err_str = X509_verify_cert_error_string(err);
1191 #ifdef CONFIG_SHA256
1192 if (preverify_ok && depth == 0 && conn->server_cert_only) {
1193 struct wpabuf *cert;
1194 cert = get_x509_cert(err_cert);
1196 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1197 "server certificate data");
1203 addr[0] = wpabuf_head(cert);
1204 len[0] = wpabuf_len(cert);
1205 if (sha256_vector(1, addr, len, hash) < 0 ||
1206 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1207 err_str = "Server certificate mismatch";
1208 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1214 #endif /* CONFIG_SHA256 */
1216 if (!preverify_ok) {
1217 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1218 " error %d (%s) depth %d for '%s'", err, err_str,
1220 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1221 err_str, TLS_FAIL_UNSPECIFIED);
1222 return preverify_ok;
1225 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1226 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1227 preverify_ok, err, err_str,
1228 conn->ca_cert_verify, depth, buf);
1229 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1230 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1231 "match with '%s'", buf, match);
1233 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1235 TLS_FAIL_SUBJECT_MISMATCH);
1236 } else if (depth == 0 && altmatch &&
1237 !tls_match_altsubject(err_cert, altmatch)) {
1238 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1239 "'%s' not found", altmatch);
1241 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1242 "AltSubject mismatch",
1243 TLS_FAIL_ALTSUBJECT_MISMATCH);
1245 openssl_tls_cert_event(conn, err_cert, depth, buf);
1247 if (conn->cert_probe && preverify_ok && depth == 0) {
1248 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1249 "on probe-only run");
1251 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1252 "Server certificate chain probe",
1253 TLS_FAIL_SERVER_CHAIN_PROBE);
1256 return preverify_ok;
1260 #ifndef OPENSSL_NO_STDIO
1261 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1263 SSL_CTX *ssl_ctx = _ssl_ctx;
1264 X509_LOOKUP *lookup;
1267 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1268 X509_LOOKUP_file());
1269 if (lookup == NULL) {
1270 tls_show_errors(MSG_WARNING, __func__,
1271 "Failed add lookup for X509 store");
1275 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1276 unsigned long err = ERR_peek_error();
1277 tls_show_errors(MSG_WARNING, __func__,
1278 "Failed load CA in DER format");
1279 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1280 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1281 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1282 "cert already in hash table error",
1290 #endif /* OPENSSL_NO_STDIO */
1293 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1294 const char *ca_cert, const u8 *ca_cert_blob,
1295 size_t ca_cert_blob_len, const char *ca_path)
1297 SSL_CTX *ssl_ctx = _ssl_ctx;
1300 * Remove previously configured trusted CA certificates before adding
1303 X509_STORE_free(ssl_ctx->cert_store);
1304 ssl_ctx->cert_store = X509_STORE_new();
1305 if (ssl_ctx->cert_store == NULL) {
1306 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1307 "certificate store", __func__);
1311 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1312 conn->ca_cert_verify = 1;
1314 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1315 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1317 conn->cert_probe = 1;
1318 conn->ca_cert_verify = 0;
1322 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1323 #ifdef CONFIG_SHA256
1324 const char *pos = ca_cert + 7;
1325 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1326 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1327 "hash value '%s'", ca_cert);
1331 if (os_strlen(pos) != 32 * 2) {
1332 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1333 "hash length in ca_cert '%s'", ca_cert);
1336 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1337 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1338 "value in ca_cert '%s'", ca_cert);
1341 conn->server_cert_only = 1;
1342 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1343 "certificate match");
1345 #else /* CONFIG_SHA256 */
1346 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1347 "cannot validate server certificate hash");
1349 #endif /* CONFIG_SHA256 */
1353 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1356 tls_show_errors(MSG_WARNING, __func__,
1357 "Failed to parse ca_cert_blob");
1361 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1362 unsigned long err = ERR_peek_error();
1363 tls_show_errors(MSG_WARNING, __func__,
1364 "Failed to add ca_cert_blob to "
1365 "certificate store");
1366 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1367 ERR_GET_REASON(err) ==
1368 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1369 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1370 "cert already in hash table error",
1378 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1379 "to certificate store", __func__);
1383 #ifdef CONFIG_NATIVE_WINDOWS
1384 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1386 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1387 "system certificate store");
1390 #endif /* CONFIG_NATIVE_WINDOWS */
1392 if (ca_cert || ca_path) {
1393 #ifndef OPENSSL_NO_STDIO
1394 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1396 tls_show_errors(MSG_WARNING, __func__,
1397 "Failed to load root certificates");
1399 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1400 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1401 "DER format CA certificate",
1406 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1407 "certificate(s) loaded");
1408 tls_get_errors(ssl_ctx);
1410 #else /* OPENSSL_NO_STDIO */
1411 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1414 #endif /* OPENSSL_NO_STDIO */
1416 /* No ca_cert configured - do not try to verify server
1418 conn->ca_cert_verify = 0;
1425 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1428 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1430 tls_show_errors(MSG_WARNING, __func__,
1431 "Failed to load root certificates");
1435 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1436 "certificate(s) loaded");
1438 #ifndef OPENSSL_NO_STDIO
1439 /* Add the same CAs to the client certificate requests */
1440 SSL_CTX_set_client_CA_list(ssl_ctx,
1441 SSL_load_client_CA_file(ca_cert));
1442 #endif /* OPENSSL_NO_STDIO */
1449 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1454 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1456 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1457 "certificate store when enabling "
1461 flags = X509_V_FLAG_CRL_CHECK;
1463 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1464 X509_STORE_set_flags(cs, flags);
1470 static int tls_connection_set_subject_match(struct tls_connection *conn,
1471 const char *subject_match,
1472 const char *altsubject_match)
1474 os_free(conn->subject_match);
1475 conn->subject_match = NULL;
1476 if (subject_match) {
1477 conn->subject_match = os_strdup(subject_match);
1478 if (conn->subject_match == NULL)
1482 os_free(conn->altsubject_match);
1483 conn->altsubject_match = NULL;
1484 if (altsubject_match) {
1485 conn->altsubject_match = os_strdup(altsubject_match);
1486 if (conn->altsubject_match == NULL)
1494 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1497 static int counter = 0;
1503 conn->ca_cert_verify = 1;
1504 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1505 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1506 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1508 conn->ca_cert_verify = 0;
1509 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1512 SSL_set_accept_state(conn->ssl);
1515 * Set session id context in order to avoid fatal errors when client
1516 * tries to resume a session. However, set the context to a unique
1517 * value in order to effectively disable session resumption for now
1518 * since not all areas of the server code are ready for it (e.g.,
1519 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1523 SSL_set_session_id_context(conn->ssl,
1524 (const unsigned char *) &counter,
1531 static int tls_connection_client_cert(struct tls_connection *conn,
1532 const char *client_cert,
1533 const u8 *client_cert_blob,
1534 size_t client_cert_blob_len)
1536 if (client_cert == NULL && client_cert_blob == NULL)
1539 if (client_cert_blob &&
1540 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1541 client_cert_blob_len) == 1) {
1542 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1545 } else if (client_cert_blob) {
1546 tls_show_errors(MSG_DEBUG, __func__,
1547 "SSL_use_certificate_ASN1 failed");
1550 if (client_cert == NULL)
1553 #ifndef OPENSSL_NO_STDIO
1554 if (SSL_use_certificate_file(conn->ssl, client_cert,
1555 SSL_FILETYPE_ASN1) == 1) {
1556 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1560 tls_show_errors(MSG_DEBUG, __func__,
1561 "SSL_use_certificate_file (DER) failed");
1564 if (SSL_use_certificate_file(conn->ssl, client_cert,
1565 SSL_FILETYPE_PEM) == 1) {
1566 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1570 tls_show_errors(MSG_DEBUG, __func__,
1571 "SSL_use_certificate_file (PEM) failed");
1573 #else /* OPENSSL_NO_STDIO */
1574 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1575 #endif /* OPENSSL_NO_STDIO */
1581 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1583 #ifndef OPENSSL_NO_STDIO
1584 if (client_cert == NULL)
1587 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1588 SSL_FILETYPE_ASN1) != 1 &&
1589 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1590 SSL_FILETYPE_PEM) != 1) {
1591 tls_show_errors(MSG_INFO, __func__,
1592 "Failed to load client certificate");
1596 #else /* OPENSSL_NO_STDIO */
1597 if (client_cert == NULL)
1599 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1601 #endif /* OPENSSL_NO_STDIO */
1605 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1607 if (password == NULL) {
1610 os_strlcpy(buf, (char *) password, size);
1611 return os_strlen(buf);
1616 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1621 STACK_OF(X509) *certs;
1628 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1629 tls_show_errors(MSG_DEBUG, __func__,
1630 "Failed to parse PKCS12 file");
1634 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1637 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1639 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1640 "subject='%s'", buf);
1642 if (SSL_use_certificate(ssl, cert) != 1)
1645 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1652 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1654 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1657 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1660 EVP_PKEY_free(pkey);
1664 while ((cert = sk_X509_pop(certs)) != NULL) {
1665 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1667 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1668 " from PKCS12: subject='%s'", buf);
1670 * There is no SSL equivalent for the chain cert - so
1671 * always add it to the context...
1673 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1678 sk_X509_free(certs);
1684 tls_get_errors(ssl_ctx);
1688 #endif /* PKCS12_FUNCS */
1691 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1698 f = fopen(private_key, "rb");
1702 p12 = d2i_PKCS12_fp(f, NULL);
1706 tls_show_errors(MSG_INFO, __func__,
1707 "Failed to use PKCS#12 file");
1711 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1713 #else /* PKCS12_FUNCS */
1714 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1717 #endif /* PKCS12_FUNCS */
1721 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1722 const u8 *blob, size_t len, const char *passwd)
1727 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1729 tls_show_errors(MSG_INFO, __func__,
1730 "Failed to use PKCS#12 blob");
1734 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1736 #else /* PKCS12_FUNCS */
1737 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1740 #endif /* PKCS12_FUNCS */
1744 #ifndef OPENSSL_NO_ENGINE
1745 static int tls_engine_get_cert(struct tls_connection *conn,
1746 const char *cert_id,
1749 /* this runs after the private key is loaded so no PIN is required */
1751 const char *cert_id;
1754 params.cert_id = cert_id;
1757 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1758 0, ¶ms, NULL, 1)) {
1759 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1760 " '%s' [%s]", cert_id,
1761 ERR_error_string(ERR_get_error(), NULL));
1762 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1765 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1767 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1769 *cert = params.cert;
1772 #endif /* OPENSSL_NO_ENGINE */
1775 static int tls_connection_engine_client_cert(struct tls_connection *conn,
1776 const char *cert_id)
1778 #ifndef OPENSSL_NO_ENGINE
1781 if (tls_engine_get_cert(conn, cert_id, &cert))
1784 if (!SSL_use_certificate(conn->ssl, cert)) {
1785 tls_show_errors(MSG_ERROR, __func__,
1786 "SSL_use_certificate failed");
1791 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1795 #else /* OPENSSL_NO_ENGINE */
1797 #endif /* OPENSSL_NO_ENGINE */
1801 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1802 struct tls_connection *conn,
1803 const char *ca_cert_id)
1805 #ifndef OPENSSL_NO_ENGINE
1807 SSL_CTX *ssl_ctx = _ssl_ctx;
1809 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1812 /* start off the same as tls_connection_ca_cert */
1813 X509_STORE_free(ssl_ctx->cert_store);
1814 ssl_ctx->cert_store = X509_STORE_new();
1815 if (ssl_ctx->cert_store == NULL) {
1816 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1817 "certificate store", __func__);
1821 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1822 unsigned long err = ERR_peek_error();
1823 tls_show_errors(MSG_WARNING, __func__,
1824 "Failed to add CA certificate from engine "
1825 "to certificate store");
1826 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1827 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1828 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1829 " already in hash table error",
1837 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1838 "to certificate store", __func__);
1839 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1842 #else /* OPENSSL_NO_ENGINE */
1844 #endif /* OPENSSL_NO_ENGINE */
1848 static int tls_connection_engine_private_key(struct tls_connection *conn)
1850 #ifndef OPENSSL_NO_ENGINE
1851 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1852 tls_show_errors(MSG_ERROR, __func__,
1853 "ENGINE: cannot use private key for TLS");
1856 if (!SSL_check_private_key(conn->ssl)) {
1857 tls_show_errors(MSG_INFO, __func__,
1858 "Private key failed verification");
1862 #else /* OPENSSL_NO_ENGINE */
1863 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1864 "engine support was not compiled in");
1866 #endif /* OPENSSL_NO_ENGINE */
1870 static int tls_connection_private_key(void *_ssl_ctx,
1871 struct tls_connection *conn,
1872 const char *private_key,
1873 const char *private_key_passwd,
1874 const u8 *private_key_blob,
1875 size_t private_key_blob_len)
1877 SSL_CTX *ssl_ctx = _ssl_ctx;
1881 if (private_key == NULL && private_key_blob == NULL)
1884 if (private_key_passwd) {
1885 passwd = os_strdup(private_key_passwd);
1891 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1892 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1895 while (private_key_blob) {
1896 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1897 (u8 *) private_key_blob,
1898 private_key_blob_len) == 1) {
1899 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1900 "ASN1(EVP_PKEY_RSA) --> OK");
1904 tls_show_errors(MSG_DEBUG, __func__,
1905 "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
1909 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1910 (u8 *) private_key_blob,
1911 private_key_blob_len) == 1) {
1912 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1913 "ASN1(EVP_PKEY_DSA) --> OK");
1917 tls_show_errors(MSG_DEBUG, __func__,
1918 "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
1922 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1923 (u8 *) private_key_blob,
1924 private_key_blob_len) == 1) {
1925 wpa_printf(MSG_DEBUG, "OpenSSL: "
1926 "SSL_use_RSAPrivateKey_ASN1 --> OK");
1930 tls_show_errors(MSG_DEBUG, __func__,
1931 "SSL_use_RSAPrivateKey_ASN1 failed");
1934 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1935 private_key_blob_len, passwd) == 0) {
1936 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1945 while (!ok && private_key) {
1946 #ifndef OPENSSL_NO_STDIO
1947 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1948 SSL_FILETYPE_ASN1) == 1) {
1949 wpa_printf(MSG_DEBUG, "OpenSSL: "
1950 "SSL_use_PrivateKey_File (DER) --> OK");
1954 tls_show_errors(MSG_DEBUG, __func__,
1955 "SSL_use_PrivateKey_File (DER) "
1959 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1960 SSL_FILETYPE_PEM) == 1) {
1961 wpa_printf(MSG_DEBUG, "OpenSSL: "
1962 "SSL_use_PrivateKey_File (PEM) --> OK");
1966 tls_show_errors(MSG_DEBUG, __func__,
1967 "SSL_use_PrivateKey_File (PEM) "
1970 #else /* OPENSSL_NO_STDIO */
1971 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1973 #endif /* OPENSSL_NO_STDIO */
1975 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
1977 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
1983 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
1984 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
1985 "access certificate store --> OK");
1994 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
2000 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2003 if (!SSL_check_private_key(conn->ssl)) {
2004 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2009 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2014 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2015 const char *private_key_passwd)
2019 if (private_key == NULL)
2022 if (private_key_passwd) {
2023 passwd = os_strdup(private_key_passwd);
2029 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2030 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2032 #ifndef OPENSSL_NO_STDIO
2033 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2034 SSL_FILETYPE_ASN1) != 1 &&
2035 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2036 SSL_FILETYPE_PEM) != 1 &&
2037 #endif /* OPENSSL_NO_STDIO */
2038 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2039 tls_show_errors(MSG_INFO, __func__,
2040 "Failed to load private key");
2047 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2049 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2050 tls_show_errors(MSG_INFO, __func__,
2051 "Private key failed verification");
2059 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2061 #ifdef OPENSSL_NO_DH
2062 if (dh_file == NULL)
2064 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2065 "dh_file specified");
2067 #else /* OPENSSL_NO_DH */
2071 /* TODO: add support for dh_blob */
2072 if (dh_file == NULL)
2077 bio = BIO_new_file(dh_file, "r");
2079 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2080 dh_file, ERR_error_string(ERR_get_error(), NULL));
2083 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2085 #ifndef OPENSSL_NO_DSA
2086 while (dh == NULL) {
2088 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2089 " trying to parse as DSA params", dh_file,
2090 ERR_error_string(ERR_get_error(), NULL));
2091 bio = BIO_new_file(dh_file, "r");
2094 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2097 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2098 "'%s': %s", dh_file,
2099 ERR_error_string(ERR_get_error(), NULL));
2103 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2104 dh = DSA_dup_DH(dsa);
2107 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2108 "params into DH params");
2113 #endif /* !OPENSSL_NO_DSA */
2115 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2120 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2121 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2123 ERR_error_string(ERR_get_error(), NULL));
2129 #endif /* OPENSSL_NO_DH */
2133 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2135 #ifdef OPENSSL_NO_DH
2136 if (dh_file == NULL)
2138 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2139 "dh_file specified");
2141 #else /* OPENSSL_NO_DH */
2145 /* TODO: add support for dh_blob */
2146 if (dh_file == NULL)
2148 if (ssl_ctx == NULL)
2151 bio = BIO_new_file(dh_file, "r");
2153 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2154 dh_file, ERR_error_string(ERR_get_error(), NULL));
2157 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2159 #ifndef OPENSSL_NO_DSA
2160 while (dh == NULL) {
2162 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2163 " trying to parse as DSA params", dh_file,
2164 ERR_error_string(ERR_get_error(), NULL));
2165 bio = BIO_new_file(dh_file, "r");
2168 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2171 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2172 "'%s': %s", dh_file,
2173 ERR_error_string(ERR_get_error(), NULL));
2177 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2178 dh = DSA_dup_DH(dsa);
2181 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2182 "params into DH params");
2187 #endif /* !OPENSSL_NO_DSA */
2189 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2194 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2195 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2197 ERR_error_string(ERR_get_error(), NULL));
2203 #endif /* OPENSSL_NO_DH */
2207 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
2208 struct tls_keys *keys)
2212 if (conn == NULL || keys == NULL)
2215 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2218 os_memset(keys, 0, sizeof(*keys));
2219 keys->master_key = ssl->session->master_key;
2220 keys->master_key_len = ssl->session->master_key_length;
2221 keys->client_random = ssl->s3->client_random;
2222 keys->client_random_len = SSL3_RANDOM_SIZE;
2223 keys->server_random = ssl->s3->server_random;
2224 keys->server_random_len = SSL3_RANDOM_SIZE;
2230 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2231 const char *label, int server_random_first,
2232 u8 *out, size_t out_len)
2238 static struct wpabuf *
2239 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2243 struct wpabuf *out_data;
2246 * Give TLS handshake data from the server (if available) to OpenSSL
2250 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2252 tls_show_errors(MSG_INFO, __func__,
2253 "Handshake failed - BIO_write");
2257 /* Initiate TLS handshake or continue the existing handshake */
2259 res = SSL_accept(conn->ssl);
2261 res = SSL_connect(conn->ssl);
2263 int err = SSL_get_error(conn->ssl, res);
2264 if (err == SSL_ERROR_WANT_READ)
2265 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2267 else if (err == SSL_ERROR_WANT_WRITE)
2268 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2271 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2276 /* Get the TLS handshake data to be sent to the server */
2277 res = BIO_ctrl_pending(conn->ssl_out);
2278 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2279 out_data = wpabuf_alloc(res);
2280 if (out_data == NULL) {
2281 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2282 "handshake output (%d bytes)", res);
2283 if (BIO_reset(conn->ssl_out) < 0) {
2284 tls_show_errors(MSG_INFO, __func__,
2285 "BIO_reset failed");
2289 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2292 tls_show_errors(MSG_INFO, __func__,
2293 "Handshake failed - BIO_read");
2294 if (BIO_reset(conn->ssl_out) < 0) {
2295 tls_show_errors(MSG_INFO, __func__,
2296 "BIO_reset failed");
2298 wpabuf_free(out_data);
2301 wpabuf_put(out_data, res);
2307 static struct wpabuf *
2308 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2310 struct wpabuf *appl_data;
2313 appl_data = wpabuf_alloc(max_len + 100);
2314 if (appl_data == NULL)
2317 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2318 wpabuf_size(appl_data));
2320 int err = SSL_get_error(conn->ssl, res);
2321 if (err == SSL_ERROR_WANT_READ ||
2322 err == SSL_ERROR_WANT_WRITE) {
2323 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2326 tls_show_errors(MSG_INFO, __func__,
2327 "Failed to read possible "
2328 "Application Data");
2330 wpabuf_free(appl_data);
2334 wpabuf_put(appl_data, res);
2335 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2336 "message", appl_data);
2342 static struct wpabuf *
2343 openssl_connection_handshake(struct tls_connection *conn,
2344 const struct wpabuf *in_data,
2345 struct wpabuf **appl_data, int server)
2347 struct wpabuf *out_data;
2352 out_data = openssl_handshake(conn, in_data, server);
2353 if (out_data == NULL)
2356 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2357 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2364 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2365 const struct wpabuf *in_data,
2366 struct wpabuf **appl_data)
2368 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2372 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2373 struct tls_connection *conn,
2374 const struct wpabuf *in_data,
2375 struct wpabuf **appl_data)
2377 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2381 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2382 struct tls_connection *conn,
2383 const struct wpabuf *in_data)
2391 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2392 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2393 (res = BIO_reset(conn->ssl_out)) < 0) {
2394 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2397 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2399 tls_show_errors(MSG_INFO, __func__,
2400 "Encryption failed - SSL_write");
2404 /* Read encrypted data to be sent to the server */
2405 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2408 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2410 tls_show_errors(MSG_INFO, __func__,
2411 "Encryption failed - BIO_read");
2415 wpabuf_put(buf, res);
2421 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2422 struct tls_connection *conn,
2423 const struct wpabuf *in_data)
2428 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2429 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2430 wpabuf_len(in_data));
2432 tls_show_errors(MSG_INFO, __func__,
2433 "Decryption failed - BIO_write");
2436 if (BIO_reset(conn->ssl_out) < 0) {
2437 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2441 /* Read decrypted data for further processing */
2443 * Even though we try to disable TLS compression, it is possible that
2444 * this cannot be done with all TLS libraries. Add extra buffer space
2445 * to handle the possibility of the decrypted data being longer than
2448 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2451 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2453 tls_show_errors(MSG_INFO, __func__,
2454 "Decryption failed - SSL_read");
2458 wpabuf_put(buf, res);
2464 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2466 return conn ? conn->ssl->hit : 0;
2470 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2473 char buf[100], *pos, *end;
2477 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2482 end = pos + sizeof(buf);
2485 while (*c != TLS_CIPHER_NONE) {
2489 case TLS_CIPHER_RC4_SHA:
2492 case TLS_CIPHER_AES128_SHA:
2493 suite = "AES128-SHA";
2495 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2496 suite = "DHE-RSA-AES128-SHA";
2498 case TLS_CIPHER_ANON_DH_AES128_SHA:
2499 suite = "ADH-AES128-SHA";
2502 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2503 "cipher selection: %d", *c);
2506 ret = os_snprintf(pos, end - pos, ":%s", suite);
2507 if (ret < 0 || ret >= end - pos)
2514 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2516 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2517 tls_show_errors(MSG_INFO, __func__,
2518 "Cipher suite configuration failed");
2526 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2527 char *buf, size_t buflen)
2530 if (conn == NULL || conn->ssl == NULL)
2533 name = SSL_get_cipher(conn->ssl);
2537 os_strlcpy(buf, name, buflen);
2542 int tls_connection_enable_workaround(void *ssl_ctx,
2543 struct tls_connection *conn)
2545 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2551 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2552 /* ClientHello TLS extensions require a patch to openssl, so this function is
2553 * commented out unless explicitly needed for EAP-FAST in order to be able to
2554 * build this file with unmodified openssl. */
2555 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2556 int ext_type, const u8 *data,
2559 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2562 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2563 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2566 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2567 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2570 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2574 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2577 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2581 return conn->failed;
2585 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2589 return conn->read_alerts;
2593 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2597 return conn->write_alerts;
2601 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2602 const struct tls_connection_params *params)
2610 while ((err = ERR_get_error())) {
2611 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2612 __func__, ERR_error_string(err, NULL));
2615 if (params->engine) {
2616 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2617 ret = tls_engine_init(conn, params->engine_id, params->pin,
2618 params->key_id, params->cert_id,
2619 params->ca_cert_id);
2623 if (tls_connection_set_subject_match(conn,
2624 params->subject_match,
2625 params->altsubject_match))
2628 if (params->engine && params->ca_cert_id) {
2629 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2630 params->ca_cert_id))
2631 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2632 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2633 params->ca_cert_blob,
2634 params->ca_cert_blob_len,
2638 if (params->engine && params->cert_id) {
2639 if (tls_connection_engine_client_cert(conn, params->cert_id))
2640 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2641 } else if (tls_connection_client_cert(conn, params->client_cert,
2642 params->client_cert_blob,
2643 params->client_cert_blob_len))
2646 if (params->engine && params->key_id) {
2647 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2648 if (tls_connection_engine_private_key(conn))
2649 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2650 } else if (tls_connection_private_key(tls_ctx, conn,
2651 params->private_key,
2652 params->private_key_passwd,
2653 params->private_key_blob,
2654 params->private_key_blob_len)) {
2655 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2656 params->private_key);
2660 if (tls_connection_dh(conn, params->dh_file)) {
2661 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2666 tls_get_errors(tls_ctx);
2672 int tls_global_set_params(void *tls_ctx,
2673 const struct tls_connection_params *params)
2675 SSL_CTX *ssl_ctx = tls_ctx;
2678 while ((err = ERR_get_error())) {
2679 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2680 __func__, ERR_error_string(err, NULL));
2683 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2686 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2689 if (tls_global_private_key(ssl_ctx, params->private_key,
2690 params->private_key_passwd))
2693 if (tls_global_dh(ssl_ctx, params->dh_file)) {
2694 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2703 int tls_connection_get_keyblock_size(void *tls_ctx,
2704 struct tls_connection *conn)
2706 const EVP_CIPHER *c;
2709 if (conn == NULL || conn->ssl == NULL ||
2710 conn->ssl->enc_read_ctx == NULL ||
2711 conn->ssl->enc_read_ctx->cipher == NULL ||
2712 conn->ssl->read_hash == NULL)
2715 c = conn->ssl->enc_read_ctx->cipher;
2716 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2717 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2719 h = conn->ssl->read_hash;
2722 return 2 * (EVP_CIPHER_key_length(c) +
2724 EVP_CIPHER_iv_length(c));
2728 unsigned int tls_capabilities(void *tls_ctx)
2734 int tls_connection_set_ia(void *tls_ctx, struct tls_connection *conn,
2741 struct wpabuf * tls_connection_ia_send_phase_finished(
2742 void *tls_ctx, struct tls_connection *conn, int final)
2748 int tls_connection_ia_final_phase_finished(void *tls_ctx,
2749 struct tls_connection *conn)
2755 int tls_connection_ia_permute_inner_secret(void *tls_ctx,
2756 struct tls_connection *conn,
2757 const u8 *key, size_t key_len)
2763 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2764 /* Pre-shared secred requires a patch to openssl, so this function is
2765 * commented out unless explicitly needed for EAP-FAST in order to be able to
2766 * build this file with unmodified openssl. */
2768 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2769 STACK_OF(SSL_CIPHER) *peer_ciphers,
2770 SSL_CIPHER **cipher, void *arg)
2772 struct tls_connection *conn = arg;
2775 if (conn == NULL || conn->session_ticket_cb == NULL)
2778 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2779 conn->session_ticket,
2780 conn->session_ticket_len,
2781 s->s3->client_random,
2782 s->s3->server_random, secret);
2783 os_free(conn->session_ticket);
2784 conn->session_ticket = NULL;
2789 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2794 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2795 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
2798 struct tls_connection *conn = arg;
2800 if (conn == NULL || conn->session_ticket_cb == NULL)
2803 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
2805 os_free(conn->session_ticket);
2806 conn->session_ticket = NULL;
2808 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2809 "extension", data, len);
2811 conn->session_ticket = os_malloc(len);
2812 if (conn->session_ticket == NULL)
2815 os_memcpy(conn->session_ticket, data, len);
2816 conn->session_ticket_len = len;
2820 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2821 #ifdef SSL_OP_NO_TICKET
2822 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2823 unsigned char *data, int len, void *arg)
2825 struct tls_connection *conn = arg;
2827 if (conn == NULL || conn->session_ticket_cb == NULL)
2830 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2833 if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2834 os_free(conn->session_ticket);
2835 conn->session_ticket = NULL;
2837 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2838 "extension", data, len);
2839 conn->session_ticket = os_malloc(len);
2840 if (conn->session_ticket == NULL)
2843 os_memcpy(conn->session_ticket, data, len);
2844 conn->session_ticket_len = len;
2847 #else /* SSL_OP_NO_TICKET */
2848 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2850 struct tls_connection *conn = arg;
2852 if (conn == NULL || conn->session_ticket_cb == NULL)
2855 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2856 ext->type, ext->length);
2858 os_free(conn->session_ticket);
2859 conn->session_ticket = NULL;
2861 if (ext->type == 35) {
2862 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2863 "extension", ext->data, ext->length);
2864 conn->session_ticket = os_malloc(ext->length);
2865 if (conn->session_ticket == NULL)
2866 return SSL_AD_INTERNAL_ERROR;
2868 os_memcpy(conn->session_ticket, ext->data, ext->length);
2869 conn->session_ticket_len = ext->length;
2874 #endif /* SSL_OP_NO_TICKET */
2875 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2876 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2879 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2880 struct tls_connection *conn,
2881 tls_session_ticket_cb cb,
2884 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2885 conn->session_ticket_cb = cb;
2886 conn->session_ticket_cb_ctx = ctx;
2889 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2892 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2893 SSL_set_session_ticket_ext_cb(conn->ssl,
2894 tls_session_ticket_ext_cb, conn);
2895 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2896 #ifdef SSL_OP_NO_TICKET
2897 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2898 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2899 #else /* SSL_OP_NO_TICKET */
2900 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2903 #endif /* SSL_OP_NO_TICKET */
2904 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2906 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2908 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2909 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
2910 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2911 #ifdef SSL_OP_NO_TICKET
2912 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2913 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2914 #else /* SSL_OP_NO_TICKET */
2915 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2917 #endif /* SSL_OP_NO_TICKET */
2918 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2922 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2924 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */