2 * WPA Supplicant / SSL/TLS interface functions for openssl
3 * Copyright (c) 2004-2006, 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 */
34 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
35 #define OPENSSL_d2i_TYPE const unsigned char **
37 #define OPENSSL_d2i_TYPE unsigned char **
41 #include <openssl/pem.h>
42 #include "keystore_get.h"
44 static BIO *BIO_from_keystore(const char *key)
47 char value[KEYSTORE_MESSAGE_SIZE];
48 int length = keystore_get(key, value);
49 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL) {
50 BIO_write(bio, value, length);
56 static int tls_openssl_ref_count = 0;
58 struct tls_connection {
60 BIO *ssl_in, *ssl_out;
61 #ifndef OPENSSL_NO_ENGINE
62 ENGINE *engine; /* functional reference to the engine */
63 EVP_PKEY *private_key; /* the private key if using engine */
64 #endif /* OPENSSL_NO_ENGINE */
65 char *subject_match, *altsubject_match;
66 int read_alerts, write_alerts, failed;
68 u8 *pre_shared_secret;
69 size_t pre_shared_secret_len;
73 #ifdef CONFIG_NO_STDOUT_DEBUG
75 static void _tls_show_errors(void)
79 while ((err = ERR_get_error())) {
80 /* Just ignore the errors, since stdout is disabled */
83 #define tls_show_errors(l, f, t) _tls_show_errors()
85 #else /* CONFIG_NO_STDOUT_DEBUG */
87 static void tls_show_errors(int level, const char *func, const char *txt)
91 wpa_printf(level, "OpenSSL: %s - %s %s",
92 func, txt, ERR_error_string(ERR_get_error(), NULL));
94 while ((err = ERR_get_error())) {
95 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
96 ERR_error_string(err, NULL));
100 #endif /* CONFIG_NO_STDOUT_DEBUG */
103 #ifdef CONFIG_NATIVE_WINDOWS
105 /* Windows CryptoAPI and access to certificate stores */
106 #include <wincrypt.h>
108 #ifdef __MINGW32_VERSION
110 * MinGW does not yet include all the needed definitions for CryptoAPI, so
111 * define here whatever extra is needed.
113 #define CALG_SSL3_SHAMD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
114 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
115 #define CERT_STORE_READONLY_FLAG 0x00008000
116 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
117 #define CRYPT_ACQUIRE_COMPARE_KEY_FLAG 0x00000004
120 (*CryptAcquireCertificatePrivateKey)(PCCERT_CONTEXT pCert, DWORD dwFlags,
121 void *pvReserved, HCRYPTPROV *phCryptProv,
122 DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
123 = NULL; /* to be loaded from crypt32.dll */
125 static PCCERT_CONTEXT WINAPI
126 (*CertEnumCertificatesInStore)(HCERTSTORE hCertStore,
127 PCCERT_CONTEXT pPrevCertContext)
128 = NULL; /* to be loaded from crypt32.dll */
130 static int mingw_load_crypto_func(void)
134 /* MinGW does not yet have full CryptoAPI support, so load the needed
137 if (CryptAcquireCertificatePrivateKey)
140 dll = LoadLibrary("crypt32");
142 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not load crypt32 "
147 CryptAcquireCertificatePrivateKey = GetProcAddress(
148 dll, "CryptAcquireCertificatePrivateKey");
149 if (CryptAcquireCertificatePrivateKey == NULL) {
150 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
151 "CryptAcquireCertificatePrivateKey() address from "
156 CertEnumCertificatesInStore = (void *) GetProcAddress(
157 dll, "CertEnumCertificatesInStore");
158 if (CertEnumCertificatesInStore == NULL) {
159 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
160 "CertEnumCertificatesInStore() address from "
168 #else /* __MINGW32_VERSION */
170 static int mingw_load_crypto_func(void)
175 #endif /* __MINGW32_VERSION */
178 struct cryptoapi_rsa_data {
179 const CERT_CONTEXT *cert;
180 HCRYPTPROV crypt_prov;
182 BOOL free_crypt_prov;
186 static void cryptoapi_error(const char *msg)
188 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
189 msg, (unsigned int) GetLastError());
193 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
194 unsigned char *to, RSA *rsa, int padding)
196 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
201 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
202 unsigned char *to, RSA *rsa, int padding)
204 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
209 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
210 unsigned char *to, RSA *rsa, int padding)
212 struct cryptoapi_rsa_data *priv =
213 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
215 DWORD hash_size, len, i;
216 unsigned char *buf = NULL;
220 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
221 ERR_R_PASSED_NULL_PARAMETER);
225 if (padding != RSA_PKCS1_PADDING) {
226 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
227 RSA_R_UNKNOWN_PADDING_TYPE);
231 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
232 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
234 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
235 RSA_R_INVALID_MESSAGE_LENGTH);
239 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
241 cryptoapi_error("CryptCreateHash failed");
245 len = sizeof(hash_size);
246 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
248 cryptoapi_error("CryptGetHashParam failed");
252 if ((int) hash_size != flen) {
253 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
254 (unsigned) hash_size, flen);
255 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
256 RSA_R_INVALID_MESSAGE_LENGTH);
259 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
260 cryptoapi_error("CryptSetHashParam failed");
265 buf = os_malloc(len);
267 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
271 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
272 cryptoapi_error("CryptSignHash failed");
276 for (i = 0; i < len; i++)
277 to[i] = buf[len - i - 1];
282 CryptDestroyHash(hash);
288 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
289 unsigned char *to, RSA *rsa, int padding)
291 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
296 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
300 if (priv->crypt_prov && priv->free_crypt_prov)
301 CryptReleaseContext(priv->crypt_prov, 0);
303 CertFreeCertificateContext(priv->cert);
308 static int cryptoapi_finish(RSA *rsa)
310 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
311 os_free((void *) rsa->meth);
317 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
320 const CERT_CONTEXT *ret = NULL;
322 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
323 store | CERT_STORE_OPEN_EXISTING_FLAG |
324 CERT_STORE_READONLY_FLAG, L"MY");
326 cryptoapi_error("Failed to open 'My system store'");
330 if (strncmp(name, "cert://", 7) == 0) {
331 unsigned short wbuf[255];
332 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
333 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
335 0, CERT_FIND_SUBJECT_STR,
337 } else if (strncmp(name, "hash://", 7) == 0) {
338 CRYPT_HASH_BLOB blob;
340 const char *hash = name + 7;
343 len = os_strlen(hash) / 2;
344 buf = os_malloc(len);
345 if (buf && hexstr2bin(hash, buf, len) == 0) {
348 ret = CertFindCertificateInStore(cs,
357 CertCloseStore(cs, 0);
363 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
366 RSA *rsa = NULL, *pub_rsa;
367 struct cryptoapi_rsa_data *priv;
368 RSA_METHOD *rsa_meth;
371 (strncmp(name, "cert://", 7) != 0 &&
372 strncmp(name, "hash://", 7) != 0))
375 priv = os_zalloc(sizeof(*priv));
376 rsa_meth = os_zalloc(sizeof(*rsa_meth));
377 if (priv == NULL || rsa_meth == NULL) {
378 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
379 "for CryptoAPI RSA method");
385 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
386 if (priv->cert == NULL) {
387 priv->cert = cryptoapi_find_cert(
388 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
390 if (priv->cert == NULL) {
391 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
396 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
397 priv->cert->cbCertEncoded);
399 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
404 if (mingw_load_crypto_func())
407 if (!CryptAcquireCertificatePrivateKey(priv->cert,
408 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
409 NULL, &priv->crypt_prov,
411 &priv->free_crypt_prov)) {
412 cryptoapi_error("Failed to acquire a private key for the "
417 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
418 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
419 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
420 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
421 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
422 rsa_meth->finish = cryptoapi_finish;
423 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
424 rsa_meth->app_data = (char *) priv;
428 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
429 ERR_R_MALLOC_FAILURE);
433 if (!SSL_use_certificate(ssl, cert)) {
438 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
442 rsa->n = BN_dup(pub_rsa->n);
443 rsa->e = BN_dup(pub_rsa->e);
444 if (!RSA_set_method(rsa, rsa_meth))
447 if (!SSL_use_RSAPrivateKey(ssl, rsa))
460 cryptoapi_free_data(priv);
466 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
469 PCCERT_CONTEXT ctx = NULL;
477 if (mingw_load_crypto_func())
480 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
485 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
488 wsprintf(wstore, L"%S", store);
489 cs = CertOpenSystemStore(0, wstore);
492 cs = CertOpenSystemStore(0, store);
495 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
496 "'%s': error=%d", __func__, store,
497 (int) GetLastError());
501 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
502 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
505 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
506 "X509 DER encoding for CA cert");
510 X509_NAME_oneline(X509_get_subject_name(cert), buf,
512 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
513 "system certificate store: subject='%s'", buf);
515 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
516 tls_show_errors(MSG_WARNING, __func__,
517 "Failed to add ca_cert to OpenSSL "
518 "certificate store");
524 if (!CertCloseStore(cs, 0)) {
525 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
526 "'%s': error=%d", __func__, name + 13,
527 (int) GetLastError());
534 #else /* CONFIG_NATIVE_WINDOWS */
536 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
541 #endif /* CONFIG_NATIVE_WINDOWS */
544 static void ssl_info_cb(const SSL *ssl, int where, int ret)
549 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
550 w = where & ~SSL_ST_MASK;
551 if (w & SSL_ST_CONNECT)
553 else if (w & SSL_ST_ACCEPT)
558 if (where & SSL_CB_LOOP) {
559 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
560 str, SSL_state_string_long(ssl));
561 } else if (where & SSL_CB_ALERT) {
562 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
563 where & SSL_CB_READ ?
564 "read (remote end reported an error)" :
565 "write (local SSL3 detected an error)",
566 SSL_alert_type_string_long(ret),
567 SSL_alert_desc_string_long(ret));
568 if ((ret >> 8) == SSL3_AL_FATAL) {
569 struct tls_connection *conn =
570 SSL_get_app_data((SSL *) ssl);
571 if (where & SSL_CB_READ)
574 conn->write_alerts++;
576 } else if (where & SSL_CB_EXIT && ret <= 0) {
577 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
578 str, ret == 0 ? "failed" : "error",
579 SSL_state_string_long(ssl));
584 #ifndef OPENSSL_NO_ENGINE
586 * tls_engine_load_dynamic_generic - load any openssl engine
587 * @pre: an array of commands and values that load an engine initialized
588 * in the engine specific function
589 * @post: an array of commands and values that initialize an already loaded
590 * engine (or %NULL if not required)
591 * @id: the engine id of the engine to load (only required if post is not %NULL
593 * This function is a generic function that loads any openssl engine.
595 * Returns: 0 on success, -1 on failure
597 static int tls_engine_load_dynamic_generic(const char *pre[],
598 const char *post[], const char *id)
601 const char *dynamic_id = "dynamic";
603 engine = ENGINE_by_id(id);
606 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
612 engine = ENGINE_by_id(dynamic_id);
613 if (engine == NULL) {
614 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
616 ERR_error_string(ERR_get_error(), NULL));
620 /* Perform the pre commands. This will load the engine. */
621 while (pre && pre[0]) {
622 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
623 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
624 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
625 "%s %s [%s]", pre[0], pre[1],
626 ERR_error_string(ERR_get_error(), NULL));
634 * Free the reference to the "dynamic" engine. The loaded engine can
635 * now be looked up using ENGINE_by_id().
639 engine = ENGINE_by_id(id);
640 if (engine == NULL) {
641 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
642 id, ERR_error_string(ERR_get_error(), NULL));
646 while (post && post[0]) {
647 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
648 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
649 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
650 " %s %s [%s]", post[0], post[1],
651 ERR_error_string(ERR_get_error(), NULL));
652 ENGINE_remove(engine);
665 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
666 * @pkcs11_so_path: pksc11_so_path from the configuration
667 * @pcks11_module_path: pkcs11_module_path from the configuration
669 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
670 const char *pkcs11_module_path)
672 char *engine_id = "pkcs11";
673 const char *pre_cmd[] = {
674 "SO_PATH", NULL /* pkcs11_so_path */,
675 "ID", NULL /* engine_id */,
677 /* "NO_VCHECK", "1", */
681 const char *post_cmd[] = {
682 "MODULE_PATH", NULL /* pkcs11_module_path */,
686 if (!pkcs11_so_path || !pkcs11_module_path)
689 pre_cmd[1] = pkcs11_so_path;
690 pre_cmd[3] = engine_id;
691 post_cmd[1] = pkcs11_module_path;
693 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
696 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
701 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
702 * @opensc_so_path: opensc_so_path from the configuration
704 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
706 char *engine_id = "opensc";
707 const char *pre_cmd[] = {
708 "SO_PATH", NULL /* opensc_so_path */,
709 "ID", NULL /* engine_id */,
718 pre_cmd[1] = opensc_so_path;
719 pre_cmd[3] = engine_id;
721 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
724 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
726 #endif /* OPENSSL_NO_ENGINE */
729 void * tls_init(const struct tls_config *conf)
733 if (tls_openssl_ref_count == 0) {
734 SSL_load_error_strings();
736 /* TODO: if /dev/urandom is available, PRNG is seeded
737 * automatically. If this is not the case, random data should
742 #endif /* PKCS12_FUNCS */
744 tls_openssl_ref_count++;
746 ssl = SSL_CTX_new(TLSv1_method());
750 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
752 #ifndef OPENSSL_NO_ENGINE
754 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
755 conf->pkcs11_module_path)) {
756 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
757 ERR_load_ENGINE_strings();
758 ENGINE_load_dynamic();
760 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
761 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
762 conf->pkcs11_module_path)) {
767 #endif /* OPENSSL_NO_ENGINE */
773 void tls_deinit(void *ssl_ctx)
775 SSL_CTX *ssl = ssl_ctx;
778 tls_openssl_ref_count--;
779 if (tls_openssl_ref_count == 0) {
780 #ifndef OPENSSL_NO_ENGINE
782 #endif /* OPENSSL_NO_ENGINE */
789 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
790 const char *pin, const char *key_id)
792 #ifndef OPENSSL_NO_ENGINE
794 if (engine_id == NULL) {
795 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
799 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
802 if (key_id == NULL) {
803 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
808 conn->engine = ENGINE_by_id(engine_id);
810 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
811 engine_id, ERR_error_string(ERR_get_error(), NULL));
814 if (ENGINE_init(conn->engine) != 1) {
815 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
816 "(engine: %s) [%s]", engine_id,
817 ERR_error_string(ERR_get_error(), NULL));
820 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
822 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
823 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
824 ERR_error_string(ERR_get_error(), NULL));
827 conn->private_key = ENGINE_load_private_key(conn->engine,
829 if (!conn->private_key) {
830 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
831 " '%s' [%s]", key_id,
832 ERR_error_string(ERR_get_error(), NULL));
833 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
840 ENGINE_free(conn->engine);
844 if (conn->private_key) {
845 EVP_PKEY_free(conn->private_key);
846 conn->private_key = NULL;
850 #else /* OPENSSL_NO_ENGINE */
852 #endif /* OPENSSL_NO_ENGINE */
856 static void tls_engine_deinit(struct tls_connection *conn)
858 #ifndef OPENSSL_NO_ENGINE
859 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
860 if (conn->private_key) {
861 EVP_PKEY_free(conn->private_key);
862 conn->private_key = NULL;
865 ENGINE_finish(conn->engine);
868 #endif /* OPENSSL_NO_ENGINE */
872 int tls_get_errors(void *ssl_ctx)
877 while ((err = ERR_get_error())) {
878 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
879 ERR_error_string(err, NULL));
886 struct tls_connection * tls_connection_init(void *ssl_ctx)
888 SSL_CTX *ssl = ssl_ctx;
889 struct tls_connection *conn;
892 conn = os_zalloc(sizeof(*conn));
895 conn->ssl = SSL_new(ssl);
896 if (conn->ssl == NULL) {
897 tls_show_errors(MSG_INFO, __func__,
898 "Failed to initialize new SSL connection");
903 SSL_set_app_data(conn->ssl, conn);
904 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
905 SSL_OP_SINGLE_DH_USE;
906 #ifdef SSL_OP_NO_COMPRESSION
907 options |= SSL_OP_NO_COMPRESSION;
908 #endif /* SSL_OP_NO_COMPRESSION */
909 SSL_set_options(conn->ssl, options);
911 conn->ssl_in = BIO_new(BIO_s_mem());
913 tls_show_errors(MSG_INFO, __func__,
914 "Failed to create a new BIO for ssl_in");
920 conn->ssl_out = BIO_new(BIO_s_mem());
921 if (!conn->ssl_out) {
922 tls_show_errors(MSG_INFO, __func__,
923 "Failed to create a new BIO for ssl_out");
925 BIO_free(conn->ssl_in);
930 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
936 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
940 os_free(conn->pre_shared_secret);
942 tls_engine_deinit(conn);
943 os_free(conn->subject_match);
944 os_free(conn->altsubject_match);
949 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
951 return conn ? SSL_is_init_finished(conn->ssl) : 0;
955 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
960 /* Shutdown previous TLS connection without notifying the peer
961 * because the connection was already terminated in practice
962 * and "close notify" shutdown alert would confuse AS. */
963 SSL_set_quiet_shutdown(conn->ssl, 1);
964 SSL_shutdown(conn->ssl);
969 static int tls_match_altsubject_component(X509 *cert, int type,
970 const char *value, size_t len)
976 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
978 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
979 gen = sk_GENERAL_NAME_value(ext, i);
980 if (gen->type != type)
982 if (os_strlen((char *) gen->d.ia5->data) == len &&
983 os_memcmp(value, gen->d.ia5->data, len) == 0)
991 static int tls_match_altsubject(X509 *cert, const char *match)
994 const char *pos, *end;
999 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1002 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1005 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1009 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1013 end = os_strchr(pos, ';');
1015 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1016 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1017 os_strncmp(end + 1, "URI:", 4) == 0)
1019 end = os_strchr(end + 1, ';');
1024 len = os_strlen(pos);
1025 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1034 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1040 struct tls_connection *conn;
1041 char *match, *altmatch;
1043 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1044 err = X509_STORE_CTX_get_error(x509_ctx);
1045 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1046 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1047 SSL_get_ex_data_X509_STORE_CTX_idx());
1048 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1050 conn = SSL_get_app_data(ssl);
1051 match = conn ? conn->subject_match : NULL;
1052 altmatch = conn ? conn->altsubject_match : NULL;
1054 if (!preverify_ok) {
1055 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1056 " error %d (%s) depth %d for '%s'", err,
1057 X509_verify_cert_error_string(err), depth, buf);
1059 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - "
1060 "preverify_ok=%d err=%d (%s) depth=%d buf='%s'",
1062 X509_verify_cert_error_string(err), depth, buf);
1063 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1064 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1065 "match with '%s'", buf, match);
1067 } else if (depth == 0 && altmatch &&
1068 !tls_match_altsubject(err_cert, altmatch)) {
1069 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1070 "'%s' not found", altmatch);
1075 return preverify_ok;
1079 #ifndef OPENSSL_NO_STDIO
1080 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1082 SSL_CTX *ssl_ctx = _ssl_ctx;
1083 X509_LOOKUP *lookup;
1086 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1087 X509_LOOKUP_file());
1088 if (lookup == NULL) {
1089 tls_show_errors(MSG_WARNING, __func__,
1090 "Failed add lookup for X509 store");
1094 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1095 unsigned long err = ERR_peek_error();
1096 tls_show_errors(MSG_WARNING, __func__,
1097 "Failed load CA in DER format");
1098 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1099 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1100 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1101 "cert already in hash table error",
1109 #endif /* OPENSSL_NO_STDIO */
1111 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1112 const char *ca_cert, const u8 *ca_cert_blob,
1113 size_t ca_cert_blob_len, const char *ca_path)
1115 SSL_CTX *ssl_ctx = _ssl_ctx;
1118 * Remove previously configured trusted CA certificates before adding
1121 X509_STORE_free(ssl_ctx->cert_store);
1122 ssl_ctx->cert_store = X509_STORE_new();
1123 if (ssl_ctx->cert_store == NULL) {
1124 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1125 "certificate store", __func__);
1130 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1133 tls_show_errors(MSG_WARNING, __func__,
1134 "Failed to parse ca_cert_blob");
1138 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1139 unsigned long err = ERR_peek_error();
1140 tls_show_errors(MSG_WARNING, __func__,
1141 "Failed to add ca_cert_blob to "
1142 "certificate store");
1143 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1144 ERR_GET_REASON(err) ==
1145 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1146 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1147 "cert already in hash table error",
1155 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1156 "to certificate store", __func__);
1157 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1162 if (ca_cert && strncmp("keystore://", ca_cert, 11) == 0) {
1163 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1164 STACK_OF(X509_INFO) *stack = NULL;
1167 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1173 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1174 X509_INFO *info = sk_X509_INFO_value(stack, i);
1176 X509_STORE_add_cert(ssl_ctx->cert_store, info->x509);
1179 X509_STORE_add_crl(ssl_ctx->cert_store, info->crl);
1182 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1183 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1188 #ifdef CONFIG_NATIVE_WINDOWS
1189 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1191 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1192 "system certificate store");
1193 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1196 #endif /* CONFIG_NATIVE_WINDOWS */
1198 if (ca_cert || ca_path) {
1199 #ifndef OPENSSL_NO_STDIO
1200 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1202 tls_show_errors(MSG_WARNING, __func__,
1203 "Failed to load root certificates");
1205 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1206 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1207 "DER format CA certificate",
1212 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1213 "certificate(s) loaded");
1214 tls_get_errors(ssl_ctx);
1216 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1217 #else /* OPENSSL_NO_STDIO */
1218 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1221 #endif /* OPENSSL_NO_STDIO */
1223 /* No ca_cert configured - do not try to verify server
1225 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1232 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1235 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1237 tls_show_errors(MSG_WARNING, __func__,
1238 "Failed to load root certificates");
1242 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1243 "certificate(s) loaded");
1245 #ifndef OPENSSL_NO_STDIO
1246 /* Add the same CAs to the client certificate requests */
1247 SSL_CTX_set_client_CA_list(ssl_ctx,
1248 SSL_load_client_CA_file(ca_cert));
1249 #endif /* OPENSSL_NO_STDIO */
1256 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1261 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1263 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1264 "certificate store when enabling "
1268 flags = X509_V_FLAG_CRL_CHECK;
1270 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1271 X509_STORE_set_flags(cs, flags);
1277 static int tls_connection_set_subject_match(struct tls_connection *conn,
1278 const char *subject_match,
1279 const char *altsubject_match)
1281 os_free(conn->subject_match);
1282 conn->subject_match = NULL;
1283 if (subject_match) {
1284 conn->subject_match = os_strdup(subject_match);
1285 if (conn->subject_match == NULL)
1289 os_free(conn->altsubject_match);
1290 conn->altsubject_match = NULL;
1291 if (altsubject_match) {
1292 conn->altsubject_match = os_strdup(altsubject_match);
1293 if (conn->altsubject_match == NULL)
1301 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1308 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1309 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1310 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1312 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1315 SSL_set_accept_state(conn->ssl);
1321 static int tls_connection_client_cert(struct tls_connection *conn,
1322 const char *client_cert,
1323 const u8 *client_cert_blob,
1324 size_t client_cert_blob_len)
1326 if (client_cert == NULL && client_cert_blob == NULL)
1329 if (client_cert_blob &&
1330 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1331 client_cert_blob_len) == 1) {
1332 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1335 } else if (client_cert_blob) {
1336 tls_show_errors(MSG_DEBUG, __func__,
1337 "SSL_use_certificate_ASN1 failed");
1340 if (client_cert == NULL)
1344 if (strncmp("keystore://", client_cert, 11) == 0) {
1345 BIO *bio = BIO_from_keystore(&client_cert[11]);
1349 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1353 if (SSL_use_certificate(conn->ssl, x509) == 1) {
1362 #ifndef OPENSSL_NO_STDIO
1363 if (SSL_use_certificate_file(conn->ssl, client_cert,
1364 SSL_FILETYPE_ASN1) == 1) {
1365 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1369 tls_show_errors(MSG_DEBUG, __func__,
1370 "SSL_use_certificate_file (DER) failed");
1373 if (SSL_use_certificate_file(conn->ssl, client_cert,
1374 SSL_FILETYPE_PEM) == 1) {
1375 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1379 tls_show_errors(MSG_DEBUG, __func__,
1380 "SSL_use_certificate_file (PEM) failed");
1382 #else /* OPENSSL_NO_STDIO */
1383 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1384 #endif /* OPENSSL_NO_STDIO */
1390 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1392 #ifndef OPENSSL_NO_STDIO
1393 if (client_cert == NULL)
1396 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1397 SSL_FILETYPE_ASN1) != 1 &&
1398 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1399 SSL_FILETYPE_PEM) != 1) {
1400 tls_show_errors(MSG_INFO, __func__,
1401 "Failed to load client certificate");
1405 #else /* OPENSSL_NO_STDIO */
1406 if (client_cert == NULL)
1408 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1410 #endif /* OPENSSL_NO_STDIO */
1414 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1416 if (password == NULL) {
1419 os_strncpy(buf, (char *) password, size);
1420 buf[size - 1] = '\0';
1421 return os_strlen(buf);
1426 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1431 STACK_OF(X509) *certs;
1438 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1439 tls_show_errors(MSG_DEBUG, __func__,
1440 "Failed to parse PKCS12 file");
1444 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1447 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1449 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1450 "subject='%s'", buf);
1452 if (SSL_use_certificate(ssl, cert) != 1)
1455 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1462 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1464 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1467 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1470 EVP_PKEY_free(pkey);
1474 while ((cert = sk_X509_pop(certs)) != NULL) {
1475 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1477 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1478 " from PKCS12: subject='%s'", buf);
1480 * There is no SSL equivalent for the chain cert - so
1481 * always add it to the context...
1483 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1488 sk_X509_free(certs);
1494 tls_get_errors(ssl_ctx);
1498 #endif /* PKCS12_FUNCS */
1501 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1508 f = fopen(private_key, "rb");
1512 p12 = d2i_PKCS12_fp(f, NULL);
1516 tls_show_errors(MSG_INFO, __func__,
1517 "Failed to use PKCS#12 file");
1521 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1523 #else /* PKCS12_FUNCS */
1524 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1527 #endif /* PKCS12_FUNCS */
1531 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1532 const u8 *blob, size_t len, const char *passwd)
1537 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1539 tls_show_errors(MSG_INFO, __func__,
1540 "Failed to use PKCS#12 blob");
1544 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1546 #else /* PKCS12_FUNCS */
1547 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1550 #endif /* PKCS12_FUNCS */
1554 static int tls_connection_engine_private_key(struct tls_connection *conn)
1556 #ifndef OPENSSL_NO_ENGINE
1557 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1558 tls_show_errors(MSG_ERROR, __func__,
1559 "ENGINE: cannot use private key for TLS");
1562 if (!SSL_check_private_key(conn->ssl)) {
1563 tls_show_errors(MSG_INFO, __func__,
1564 "Private key failed verification");
1568 #else /* OPENSSL_NO_ENGINE */
1569 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1570 "engine support was not compiled in");
1572 #endif /* OPENSSL_NO_ENGINE */
1576 static int tls_connection_private_key(void *_ssl_ctx,
1577 struct tls_connection *conn,
1578 const char *private_key,
1579 const char *private_key_passwd,
1580 const u8 *private_key_blob,
1581 size_t private_key_blob_len)
1583 SSL_CTX *ssl_ctx = _ssl_ctx;
1587 if (private_key == NULL && private_key_blob == NULL)
1590 if (private_key_passwd) {
1591 passwd = os_strdup(private_key_passwd);
1597 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1598 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1601 while (private_key_blob) {
1602 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1603 (u8 *) private_key_blob,
1604 private_key_blob_len) == 1) {
1605 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1606 "ASN1(EVP_PKEY_RSA) --> OK");
1610 tls_show_errors(MSG_DEBUG, __func__,
1611 "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
1615 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1616 (u8 *) private_key_blob,
1617 private_key_blob_len) == 1) {
1618 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1619 "ASN1(EVP_PKEY_DSA) --> OK");
1623 tls_show_errors(MSG_DEBUG, __func__,
1624 "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
1628 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1629 (u8 *) private_key_blob,
1630 private_key_blob_len) == 1) {
1631 wpa_printf(MSG_DEBUG, "OpenSSL: "
1632 "SSL_use_RSAPrivateKey_ASN1 --> OK");
1636 tls_show_errors(MSG_DEBUG, __func__,
1637 "SSL_use_RSAPrivateKey_ASN1 failed");
1640 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1641 private_key_blob_len, passwd) == 0) {
1642 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1652 if (!ok && private_key && strncmp("keystore://", private_key, 11) == 0) {
1653 BIO *bio = BIO_from_keystore(&private_key[11]);
1654 EVP_PKEY *pkey = NULL;
1656 pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
1660 if (SSL_use_PrivateKey(conn->ssl, pkey) == 1) {
1663 EVP_PKEY_free(pkey);
1668 while (!ok && private_key) {
1669 #ifndef OPENSSL_NO_STDIO
1670 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1671 SSL_FILETYPE_ASN1) == 1) {
1672 wpa_printf(MSG_DEBUG, "OpenSSL: "
1673 "SSL_use_PrivateKey_File (DER) --> OK");
1677 tls_show_errors(MSG_DEBUG, __func__,
1678 "SSL_use_PrivateKey_File (DER) "
1682 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1683 SSL_FILETYPE_PEM) == 1) {
1684 wpa_printf(MSG_DEBUG, "OpenSSL: "
1685 "SSL_use_PrivateKey_File (PEM) --> OK");
1689 tls_show_errors(MSG_DEBUG, __func__,
1690 "SSL_use_PrivateKey_File (PEM) "
1693 #else /* OPENSSL_NO_STDIO */
1694 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1696 #endif /* OPENSSL_NO_STDIO */
1698 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
1700 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
1706 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
1707 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
1708 "access certificate store --> OK");
1717 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
1723 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1726 if (!SSL_check_private_key(conn->ssl)) {
1727 tls_show_errors(MSG_INFO, __func__, "Private key failed "
1732 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
1737 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
1738 const char *private_key_passwd)
1742 if (private_key == NULL)
1745 if (private_key_passwd) {
1746 passwd = os_strdup(private_key_passwd);
1752 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1753 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1755 #ifndef OPENSSL_NO_STDIO
1756 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1757 SSL_FILETYPE_ASN1) != 1 &&
1758 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1759 SSL_FILETYPE_PEM) != 1 &&
1760 #endif /* OPENSSL_NO_STDIO */
1761 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
1762 tls_show_errors(MSG_INFO, __func__,
1763 "Failed to load private key");
1770 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1772 if (!SSL_CTX_check_private_key(ssl_ctx)) {
1773 tls_show_errors(MSG_INFO, __func__,
1774 "Private key failed verification");
1782 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
1784 #ifdef OPENSSL_NO_DH
1785 if (dh_file == NULL)
1787 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1788 "dh_file specified");
1790 #else /* OPENSSL_NO_DH */
1794 /* TODO: add support for dh_blob */
1795 if (dh_file == NULL)
1800 bio = BIO_new_file(dh_file, "r");
1802 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1803 dh_file, ERR_error_string(ERR_get_error(), NULL));
1806 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1808 #ifndef OPENSSL_NO_DSA
1809 while (dh == NULL) {
1811 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1812 " trying to parse as DSA params", dh_file,
1813 ERR_error_string(ERR_get_error(), NULL));
1814 bio = BIO_new_file(dh_file, "r");
1817 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1820 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1821 "'%s': %s", dh_file,
1822 ERR_error_string(ERR_get_error(), NULL));
1826 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1827 dh = DSA_dup_DH(dsa);
1830 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1831 "params into DH params");
1836 #endif /* !OPENSSL_NO_DSA */
1838 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1843 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
1844 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1846 ERR_error_string(ERR_get_error(), NULL));
1852 #endif /* OPENSSL_NO_DH */
1856 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
1857 struct tls_keys *keys)
1861 if (conn == NULL || keys == NULL)
1864 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
1867 os_memset(keys, 0, sizeof(*keys));
1868 keys->master_key = ssl->session->master_key;
1869 keys->master_key_len = ssl->session->master_key_length;
1870 keys->client_random = ssl->s3->client_random;
1871 keys->client_random_len = SSL3_RANDOM_SIZE;
1872 keys->server_random = ssl->s3->server_random;
1873 keys->server_random_len = SSL3_RANDOM_SIZE;
1879 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
1880 const char *label, int server_random_first,
1881 u8 *out, size_t out_len)
1887 u8 * tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
1888 const u8 *in_data, size_t in_len,
1889 size_t *out_len, u8 **appl_data,
1890 size_t *appl_data_len)
1899 * Give TLS handshake data from the server (if available) to OpenSSL
1903 BIO_write(conn->ssl_in, in_data, in_len) < 0) {
1904 tls_show_errors(MSG_INFO, __func__,
1905 "Handshake failed - BIO_write");
1909 /* Initiate TLS handshake or continue the existing handshake */
1910 res = SSL_connect(conn->ssl);
1912 int err = SSL_get_error(conn->ssl, res);
1913 if (err == SSL_ERROR_WANT_READ)
1914 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
1916 else if (err == SSL_ERROR_WANT_WRITE)
1917 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
1920 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
1925 /* Get the TLS handshake data to be sent to the server */
1926 res = BIO_ctrl_pending(conn->ssl_out);
1927 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
1928 out_data = os_malloc(res == 0 ? 1 : res);
1929 if (out_data == NULL) {
1930 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
1931 "handshake output (%d bytes)", res);
1932 if (BIO_reset(conn->ssl_out) < 0) {
1933 tls_show_errors(MSG_INFO, __func__,
1934 "BIO_reset failed");
1939 res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
1941 tls_show_errors(MSG_INFO, __func__,
1942 "Handshake failed - BIO_read");
1943 if (BIO_reset(conn->ssl_out) < 0) {
1944 tls_show_errors(MSG_INFO, __func__,
1945 "BIO_reset failed");
1952 if (SSL_is_init_finished(conn->ssl) && appl_data) {
1953 *appl_data = os_malloc(in_len);
1955 res = SSL_read(conn->ssl, *appl_data, in_len);
1957 tls_show_errors(MSG_INFO, __func__,
1958 "Failed to read possible "
1959 "Application Data");
1960 os_free(*appl_data);
1963 *appl_data_len = res;
1964 wpa_hexdump_key(MSG_MSGDUMP, "SSL: Application"
1965 " Data in Finish message",
1966 *appl_data, *appl_data_len);
1975 u8 * tls_connection_server_handshake(void *ssl_ctx,
1976 struct tls_connection *conn,
1977 const u8 *in_data, size_t in_len,
1985 BIO_write(conn->ssl_in, in_data, in_len) < 0) {
1986 tls_show_errors(MSG_INFO, __func__,
1987 "Handshake failed - BIO_write");
1991 res = SSL_read(conn->ssl, buf, sizeof(buf));
1993 wpa_printf(MSG_DEBUG, "SSL: Unexpected data from SSL_read "
1997 res = BIO_ctrl_pending(conn->ssl_out);
1998 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
1999 out_data = os_malloc(res == 0 ? 1 : res);
2000 if (out_data == NULL) {
2001 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2002 "handshake output (%d bytes)", res);
2003 if (BIO_reset(conn->ssl_out) < 0) {
2004 tls_show_errors(MSG_INFO, __func__,
2005 "BIO_reset failed");
2010 res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
2012 tls_show_errors(MSG_INFO, __func__,
2013 "Handshake failed - BIO_read");
2014 if (BIO_reset(conn->ssl_out) < 0) {
2015 tls_show_errors(MSG_INFO, __func__,
2016 "BIO_reset failed");
2026 int tls_connection_encrypt(void *ssl_ctx, struct tls_connection *conn,
2027 const u8 *in_data, size_t in_len,
2028 u8 *out_data, size_t out_len)
2035 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2036 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2037 (res = BIO_reset(conn->ssl_out)) < 0) {
2038 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2041 res = SSL_write(conn->ssl, in_data, in_len);
2043 tls_show_errors(MSG_INFO, __func__,
2044 "Encryption failed - SSL_write");
2048 /* Read encrypted data to be sent to the server */
2049 res = BIO_read(conn->ssl_out, out_data, out_len);
2051 tls_show_errors(MSG_INFO, __func__,
2052 "Encryption failed - BIO_read");
2060 int tls_connection_decrypt(void *ssl_ctx, struct tls_connection *conn,
2061 const u8 *in_data, size_t in_len,
2062 u8 *out_data, size_t out_len)
2066 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2067 res = BIO_write(conn->ssl_in, in_data, in_len);
2069 tls_show_errors(MSG_INFO, __func__,
2070 "Decryption failed - BIO_write");
2073 if (BIO_reset(conn->ssl_out) < 0) {
2074 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2078 /* Read decrypted data for further processing */
2079 res = SSL_read(conn->ssl, out_data, out_len);
2081 tls_show_errors(MSG_INFO, __func__,
2082 "Decryption failed - SSL_read");
2090 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2092 return conn ? conn->ssl->hit : 0;
2096 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2097 /* Pre-shared secred requires a patch to openssl, so this function is
2098 * commented out unless explicitly needed for EAP-FAST in order to be able to
2099 * build this file with unmodified openssl. */
2101 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2102 STACK_OF(SSL_CIPHER) *peer_ciphers,
2103 SSL_CIPHER **cipher, void *arg)
2105 struct tls_connection *conn = arg;
2107 if (conn == NULL || conn->pre_shared_secret == 0)
2110 os_memcpy(secret, conn->pre_shared_secret,
2111 conn->pre_shared_secret_len);
2112 *secret_len = conn->pre_shared_secret_len;
2118 int tls_connection_set_master_key(void *ssl_ctx, struct tls_connection *conn,
2119 const u8 *key, size_t key_len)
2121 if (conn == NULL || key_len > SSL_MAX_MASTER_KEY_LENGTH)
2124 os_free(conn->pre_shared_secret);
2125 conn->pre_shared_secret = NULL;
2126 conn->pre_shared_secret_len = 0;
2129 conn->pre_shared_secret = os_malloc(key_len);
2130 if (conn->pre_shared_secret) {
2131 os_memcpy(conn->pre_shared_secret, key, key_len);
2132 conn->pre_shared_secret_len = key_len;
2134 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2138 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2144 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2147 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2150 char buf[100], *pos, *end;
2154 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2159 end = pos + sizeof(buf);
2162 while (*c != TLS_CIPHER_NONE) {
2166 case TLS_CIPHER_RC4_SHA:
2169 case TLS_CIPHER_AES128_SHA:
2170 suite = "AES128-SHA";
2172 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2173 suite = "DHE-RSA-AES128-SHA";
2175 case TLS_CIPHER_ANON_DH_AES128_SHA:
2176 suite = "ADH-AES128-SHA";
2179 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2180 "cipher selection: %d", *c);
2183 ret = os_snprintf(pos, end - pos, ":%s", suite);
2184 if (ret < 0 || ret >= end - pos)
2191 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2193 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2194 tls_show_errors(MSG_INFO, __func__,
2195 "Cipher suite configuration failed");
2203 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2204 char *buf, size_t buflen)
2207 if (conn == NULL || conn->ssl == NULL)
2210 name = SSL_get_cipher(conn->ssl);
2214 os_snprintf(buf, buflen, "%s", name);
2215 buf[buflen - 1] = '\0';
2220 int tls_connection_enable_workaround(void *ssl_ctx,
2221 struct tls_connection *conn)
2223 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2229 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2230 /* ClientHello TLS extensions require a patch to openssl, so this function is
2231 * commented out unless explicitly needed for EAP-FAST in order to be able to
2232 * build this file with unmodified openssl. */
2233 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2234 int ext_type, const u8 *data,
2237 if (conn == NULL || conn->ssl == NULL)
2240 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2246 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2249 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2253 return conn->failed;
2257 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2261 return conn->read_alerts;
2265 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2269 return conn->write_alerts;
2273 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2274 const struct tls_connection_params *params)
2282 while ((err = ERR_get_error())) {
2283 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2284 __func__, ERR_error_string(err, NULL));
2287 if (tls_connection_set_subject_match(conn,
2288 params->subject_match,
2289 params->altsubject_match))
2291 if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2292 params->ca_cert_blob,
2293 params->ca_cert_blob_len,
2296 if (tls_connection_client_cert(conn, params->client_cert,
2297 params->client_cert_blob,
2298 params->client_cert_blob_len))
2301 if (params->engine) {
2302 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2303 ret = tls_engine_init(conn, params->engine_id, params->pin,
2307 if (tls_connection_engine_private_key(conn))
2308 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2309 } else if (tls_connection_private_key(tls_ctx, conn,
2310 params->private_key,
2311 params->private_key_passwd,
2312 params->private_key_blob,
2313 params->private_key_blob_len)) {
2314 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2315 params->private_key);
2319 if (tls_connection_dh(conn, params->dh_file)) {
2320 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2325 tls_get_errors(tls_ctx);
2331 int tls_global_set_params(void *tls_ctx,
2332 const struct tls_connection_params *params)
2334 SSL_CTX *ssl_ctx = tls_ctx;
2337 while ((err = ERR_get_error())) {
2338 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2339 __func__, ERR_error_string(err, NULL));
2342 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2345 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2348 if (tls_global_private_key(ssl_ctx, params->private_key,
2349 params->private_key_passwd))
2356 int tls_connection_get_keyblock_size(void *tls_ctx,
2357 struct tls_connection *conn)
2359 const EVP_CIPHER *c;
2362 if (conn == NULL || conn->ssl == NULL ||
2363 conn->ssl->enc_read_ctx == NULL ||
2364 conn->ssl->enc_read_ctx->cipher == NULL ||
2365 conn->ssl->read_hash == NULL)
2368 c = conn->ssl->enc_read_ctx->cipher;
2369 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2370 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2372 h = conn->ssl->read_hash;
2375 return 2 * (EVP_CIPHER_key_length(c) +
2377 EVP_CIPHER_iv_length(c));
2381 unsigned int tls_capabilities(void *tls_ctx)
2387 int tls_connection_set_ia(void *tls_ctx, struct tls_connection *conn,
2394 int tls_connection_ia_send_phase_finished(void *tls_ctx,
2395 struct tls_connection *conn,
2397 u8 *out_data, size_t out_len)
2403 int tls_connection_ia_final_phase_finished(void *tls_ctx,
2404 struct tls_connection *conn)
2410 int tls_connection_ia_permute_inner_secret(void *tls_ctx,
2411 struct tls_connection *conn,
2412 const u8 *key, size_t key_len)