Use common driver code for Linux hwaddr get/set
[hostap-gosc2009.git] / src / crypto / tls_openssl.c
blob1914b5d3844637e0e8191d669f4b75789d82462e
1 /*
2 * SSL/TLS interface functions for OpenSSL
3 * Copyright (c) 2004-2009, 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
10 * license.
12 * See README and COPYING for more details.
15 #include "includes.h"
17 #ifndef CONFIG_SMARTCARD
18 #ifndef OPENSSL_NO_ENGINE
19 #define OPENSSL_NO_ENGINE
20 #endif
21 #endif
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 */
31 #include "common.h"
32 #include "tls.h"
34 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
35 #define OPENSSL_d2i_TYPE const unsigned char **
36 #else
37 #define OPENSSL_d2i_TYPE unsigned char **
38 #endif
40 #ifdef SSL_F_SSL_SET_SESSION_TICKET_EXT
41 #ifdef SSL_OP_NO_TICKET
43 * Session ticket override patch was merged into OpenSSL 0.9.9 tree on
44 * 2008-11-15. This version uses a bit different API compared to the old patch.
46 #define CONFIG_OPENSSL_TICKET_OVERRIDE
47 #endif
48 #endif
50 static int tls_openssl_ref_count = 0;
52 struct tls_connection {
53 SSL *ssl;
54 BIO *ssl_in, *ssl_out;
55 #ifndef OPENSSL_NO_ENGINE
56 ENGINE *engine; /* functional reference to the engine */
57 EVP_PKEY *private_key; /* the private key if using engine */
58 #endif /* OPENSSL_NO_ENGINE */
59 char *subject_match, *altsubject_match;
60 int read_alerts, write_alerts, failed;
62 tls_session_ticket_cb session_ticket_cb;
63 void *session_ticket_cb_ctx;
65 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
66 u8 *session_ticket;
67 size_t session_ticket_len;
71 #ifdef CONFIG_NO_STDOUT_DEBUG
73 static void _tls_show_errors(void)
75 unsigned long err;
77 while ((err = ERR_get_error())) {
78 /* Just ignore the errors, since stdout is disabled */
81 #define tls_show_errors(l, f, t) _tls_show_errors()
83 #else /* CONFIG_NO_STDOUT_DEBUG */
85 static void tls_show_errors(int level, const char *func, const char *txt)
87 unsigned long err;
89 wpa_printf(level, "OpenSSL: %s - %s %s",
90 func, txt, ERR_error_string(ERR_get_error(), NULL));
92 while ((err = ERR_get_error())) {
93 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
94 ERR_error_string(err, NULL));
98 #endif /* CONFIG_NO_STDOUT_DEBUG */
101 #ifdef CONFIG_NATIVE_WINDOWS
103 /* Windows CryptoAPI and access to certificate stores */
104 #include <wincrypt.h>
106 #ifdef __MINGW32_VERSION
108 * MinGW does not yet include all the needed definitions for CryptoAPI, so
109 * define here whatever extra is needed.
111 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
112 #define CERT_STORE_READONLY_FLAG 0x00008000
113 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
115 #endif /* __MINGW32_VERSION */
118 struct cryptoapi_rsa_data {
119 const CERT_CONTEXT *cert;
120 HCRYPTPROV crypt_prov;
121 DWORD key_spec;
122 BOOL free_crypt_prov;
126 static void cryptoapi_error(const char *msg)
128 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
129 msg, (unsigned int) GetLastError());
133 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
134 unsigned char *to, RSA *rsa, int padding)
136 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
137 return 0;
141 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
142 unsigned char *to, RSA *rsa, int padding)
144 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
145 return 0;
149 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
150 unsigned char *to, RSA *rsa, int padding)
152 struct cryptoapi_rsa_data *priv =
153 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
154 HCRYPTHASH hash;
155 DWORD hash_size, len, i;
156 unsigned char *buf = NULL;
157 int ret = 0;
159 if (priv == NULL) {
160 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
161 ERR_R_PASSED_NULL_PARAMETER);
162 return 0;
165 if (padding != RSA_PKCS1_PADDING) {
166 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
167 RSA_R_UNKNOWN_PADDING_TYPE);
168 return 0;
171 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
172 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
173 __func__);
174 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
175 RSA_R_INVALID_MESSAGE_LENGTH);
176 return 0;
179 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
181 cryptoapi_error("CryptCreateHash failed");
182 return 0;
185 len = sizeof(hash_size);
186 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
187 0)) {
188 cryptoapi_error("CryptGetHashParam failed");
189 goto err;
192 if ((int) hash_size != flen) {
193 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
194 (unsigned) hash_size, flen);
195 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
196 RSA_R_INVALID_MESSAGE_LENGTH);
197 goto err;
199 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
200 cryptoapi_error("CryptSetHashParam failed");
201 goto err;
204 len = RSA_size(rsa);
205 buf = os_malloc(len);
206 if (buf == NULL) {
207 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
208 goto err;
211 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
212 cryptoapi_error("CryptSignHash failed");
213 goto err;
216 for (i = 0; i < len; i++)
217 to[i] = buf[len - i - 1];
218 ret = len;
220 err:
221 os_free(buf);
222 CryptDestroyHash(hash);
224 return ret;
228 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
229 unsigned char *to, RSA *rsa, int padding)
231 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
232 return 0;
236 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
238 if (priv == NULL)
239 return;
240 if (priv->crypt_prov && priv->free_crypt_prov)
241 CryptReleaseContext(priv->crypt_prov, 0);
242 if (priv->cert)
243 CertFreeCertificateContext(priv->cert);
244 os_free(priv);
248 static int cryptoapi_finish(RSA *rsa)
250 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
251 os_free((void *) rsa->meth);
252 rsa->meth = NULL;
253 return 1;
257 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
259 HCERTSTORE cs;
260 const CERT_CONTEXT *ret = NULL;
262 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
263 store | CERT_STORE_OPEN_EXISTING_FLAG |
264 CERT_STORE_READONLY_FLAG, L"MY");
265 if (cs == NULL) {
266 cryptoapi_error("Failed to open 'My system store'");
267 return NULL;
270 if (strncmp(name, "cert://", 7) == 0) {
271 unsigned short wbuf[255];
272 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
273 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
274 PKCS_7_ASN_ENCODING,
275 0, CERT_FIND_SUBJECT_STR,
276 wbuf, NULL);
277 } else if (strncmp(name, "hash://", 7) == 0) {
278 CRYPT_HASH_BLOB blob;
279 int len;
280 const char *hash = name + 7;
281 unsigned char *buf;
283 len = os_strlen(hash) / 2;
284 buf = os_malloc(len);
285 if (buf && hexstr2bin(hash, buf, len) == 0) {
286 blob.cbData = len;
287 blob.pbData = buf;
288 ret = CertFindCertificateInStore(cs,
289 X509_ASN_ENCODING |
290 PKCS_7_ASN_ENCODING,
291 0, CERT_FIND_HASH,
292 &blob, NULL);
294 os_free(buf);
297 CertCloseStore(cs, 0);
299 return ret;
303 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
305 X509 *cert = NULL;
306 RSA *rsa = NULL, *pub_rsa;
307 struct cryptoapi_rsa_data *priv;
308 RSA_METHOD *rsa_meth;
310 if (name == NULL ||
311 (strncmp(name, "cert://", 7) != 0 &&
312 strncmp(name, "hash://", 7) != 0))
313 return -1;
315 priv = os_zalloc(sizeof(*priv));
316 rsa_meth = os_zalloc(sizeof(*rsa_meth));
317 if (priv == NULL || rsa_meth == NULL) {
318 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
319 "for CryptoAPI RSA method");
320 os_free(priv);
321 os_free(rsa_meth);
322 return -1;
325 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
326 if (priv->cert == NULL) {
327 priv->cert = cryptoapi_find_cert(
328 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
330 if (priv->cert == NULL) {
331 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
332 "'%s'", name);
333 goto err;
336 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
337 priv->cert->cbCertEncoded);
338 if (cert == NULL) {
339 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
340 "encoding");
341 goto err;
344 if (!CryptAcquireCertificatePrivateKey(priv->cert,
345 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
346 NULL, &priv->crypt_prov,
347 &priv->key_spec,
348 &priv->free_crypt_prov)) {
349 cryptoapi_error("Failed to acquire a private key for the "
350 "certificate");
351 goto err;
354 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
355 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
356 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
357 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
358 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
359 rsa_meth->finish = cryptoapi_finish;
360 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
361 rsa_meth->app_data = (char *) priv;
363 rsa = RSA_new();
364 if (rsa == NULL) {
365 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
366 ERR_R_MALLOC_FAILURE);
367 goto err;
370 if (!SSL_use_certificate(ssl, cert)) {
371 RSA_free(rsa);
372 rsa = NULL;
373 goto err;
375 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
376 X509_free(cert);
377 cert = NULL;
379 rsa->n = BN_dup(pub_rsa->n);
380 rsa->e = BN_dup(pub_rsa->e);
381 if (!RSA_set_method(rsa, rsa_meth))
382 goto err;
384 if (!SSL_use_RSAPrivateKey(ssl, rsa))
385 goto err;
386 RSA_free(rsa);
388 return 0;
390 err:
391 if (cert)
392 X509_free(cert);
393 if (rsa)
394 RSA_free(rsa);
395 else {
396 os_free(rsa_meth);
397 cryptoapi_free_data(priv);
399 return -1;
403 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
405 HCERTSTORE cs;
406 PCCERT_CONTEXT ctx = NULL;
407 X509 *cert;
408 char buf[128];
409 const char *store;
410 #ifdef UNICODE
411 WCHAR *wstore;
412 #endif /* UNICODE */
414 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
415 return -1;
417 store = name + 13;
418 #ifdef UNICODE
419 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
420 if (wstore == NULL)
421 return -1;
422 wsprintf(wstore, L"%S", store);
423 cs = CertOpenSystemStore(0, wstore);
424 os_free(wstore);
425 #else /* UNICODE */
426 cs = CertOpenSystemStore(0, store);
427 #endif /* UNICODE */
428 if (cs == NULL) {
429 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
430 "'%s': error=%d", __func__, store,
431 (int) GetLastError());
432 return -1;
435 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
436 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
437 ctx->cbCertEncoded);
438 if (cert == NULL) {
439 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
440 "X509 DER encoding for CA cert");
441 continue;
444 X509_NAME_oneline(X509_get_subject_name(cert), buf,
445 sizeof(buf));
446 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
447 "system certificate store: subject='%s'", buf);
449 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
450 tls_show_errors(MSG_WARNING, __func__,
451 "Failed to add ca_cert to OpenSSL "
452 "certificate store");
455 X509_free(cert);
458 if (!CertCloseStore(cs, 0)) {
459 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
460 "'%s': error=%d", __func__, name + 13,
461 (int) GetLastError());
464 return 0;
468 #else /* CONFIG_NATIVE_WINDOWS */
470 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
472 return -1;
475 #endif /* CONFIG_NATIVE_WINDOWS */
478 static void ssl_info_cb(const SSL *ssl, int where, int ret)
480 const char *str;
481 int w;
483 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
484 w = where & ~SSL_ST_MASK;
485 if (w & SSL_ST_CONNECT)
486 str = "SSL_connect";
487 else if (w & SSL_ST_ACCEPT)
488 str = "SSL_accept";
489 else
490 str = "undefined";
492 if (where & SSL_CB_LOOP) {
493 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
494 str, SSL_state_string_long(ssl));
495 } else if (where & SSL_CB_ALERT) {
496 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
497 where & SSL_CB_READ ?
498 "read (remote end reported an error)" :
499 "write (local SSL3 detected an error)",
500 SSL_alert_type_string_long(ret),
501 SSL_alert_desc_string_long(ret));
502 if ((ret >> 8) == SSL3_AL_FATAL) {
503 struct tls_connection *conn =
504 SSL_get_app_data((SSL *) ssl);
505 if (where & SSL_CB_READ)
506 conn->read_alerts++;
507 else
508 conn->write_alerts++;
510 } else if (where & SSL_CB_EXIT && ret <= 0) {
511 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
512 str, ret == 0 ? "failed" : "error",
513 SSL_state_string_long(ssl));
518 #ifndef OPENSSL_NO_ENGINE
520 * tls_engine_load_dynamic_generic - load any openssl engine
521 * @pre: an array of commands and values that load an engine initialized
522 * in the engine specific function
523 * @post: an array of commands and values that initialize an already loaded
524 * engine (or %NULL if not required)
525 * @id: the engine id of the engine to load (only required if post is not %NULL
527 * This function is a generic function that loads any openssl engine.
529 * Returns: 0 on success, -1 on failure
531 static int tls_engine_load_dynamic_generic(const char *pre[],
532 const char *post[], const char *id)
534 ENGINE *engine;
535 const char *dynamic_id = "dynamic";
537 engine = ENGINE_by_id(id);
538 if (engine) {
539 ENGINE_free(engine);
540 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
541 "available", id);
542 return 0;
544 ERR_clear_error();
546 engine = ENGINE_by_id(dynamic_id);
547 if (engine == NULL) {
548 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
549 dynamic_id,
550 ERR_error_string(ERR_get_error(), NULL));
551 return -1;
554 /* Perform the pre commands. This will load the engine. */
555 while (pre && pre[0]) {
556 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
557 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
558 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
559 "%s %s [%s]", pre[0], pre[1],
560 ERR_error_string(ERR_get_error(), NULL));
561 ENGINE_free(engine);
562 return -1;
564 pre += 2;
568 * Free the reference to the "dynamic" engine. The loaded engine can
569 * now be looked up using ENGINE_by_id().
571 ENGINE_free(engine);
573 engine = ENGINE_by_id(id);
574 if (engine == NULL) {
575 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
576 id, ERR_error_string(ERR_get_error(), NULL));
577 return -1;
580 while (post && post[0]) {
581 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
582 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
583 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
584 " %s %s [%s]", post[0], post[1],
585 ERR_error_string(ERR_get_error(), NULL));
586 ENGINE_remove(engine);
587 ENGINE_free(engine);
588 return -1;
590 post += 2;
592 ENGINE_free(engine);
594 return 0;
599 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
600 * @pkcs11_so_path: pksc11_so_path from the configuration
601 * @pcks11_module_path: pkcs11_module_path from the configuration
603 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
604 const char *pkcs11_module_path)
606 char *engine_id = "pkcs11";
607 const char *pre_cmd[] = {
608 "SO_PATH", NULL /* pkcs11_so_path */,
609 "ID", NULL /* engine_id */,
610 "LIST_ADD", "1",
611 /* "NO_VCHECK", "1", */
612 "LOAD", NULL,
613 NULL, NULL
615 const char *post_cmd[] = {
616 "MODULE_PATH", NULL /* pkcs11_module_path */,
617 NULL, NULL
620 if (!pkcs11_so_path || !pkcs11_module_path)
621 return 0;
623 pre_cmd[1] = pkcs11_so_path;
624 pre_cmd[3] = engine_id;
625 post_cmd[1] = pkcs11_module_path;
627 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
628 pkcs11_so_path);
630 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
635 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
636 * @opensc_so_path: opensc_so_path from the configuration
638 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
640 char *engine_id = "opensc";
641 const char *pre_cmd[] = {
642 "SO_PATH", NULL /* opensc_so_path */,
643 "ID", NULL /* engine_id */,
644 "LIST_ADD", "1",
645 "LOAD", NULL,
646 NULL, NULL
649 if (!opensc_so_path)
650 return 0;
652 pre_cmd[1] = opensc_so_path;
653 pre_cmd[3] = engine_id;
655 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
656 opensc_so_path);
658 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
660 #endif /* OPENSSL_NO_ENGINE */
663 void * tls_init(const struct tls_config *conf)
665 SSL_CTX *ssl;
667 if (tls_openssl_ref_count == 0) {
668 #ifdef CONFIG_FIPS
669 #ifdef OPENSSL_FIPS
670 if (conf->fips_mode) {
671 if (!FIPS_mode_set(1)) {
672 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
673 "mode");
674 ERR_load_crypto_strings();
675 ERR_print_errors_fp(stderr);
676 return NULL;
677 } else
678 wpa_printf(MSG_INFO, "Running in FIPS mode");
680 #else /* OPENSSL_FIPS */
681 if (conf->fips_mode) {
682 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
683 "supported");
684 return NULL;
686 #endif /* OPENSSL_FIPS */
687 #endif /* CONFIG_FIPS */
688 SSL_load_error_strings();
689 SSL_library_init();
690 #ifndef OPENSSL_NO_SHA256
691 EVP_add_digest(EVP_sha256());
692 #endif /* OPENSSL_NO_SHA256 */
693 /* TODO: if /dev/urandom is available, PRNG is seeded
694 * automatically. If this is not the case, random data should
695 * be added here. */
697 #ifdef PKCS12_FUNCS
698 PKCS12_PBE_add();
699 #endif /* PKCS12_FUNCS */
701 tls_openssl_ref_count++;
703 ssl = SSL_CTX_new(TLSv1_method());
704 if (ssl == NULL)
705 return NULL;
707 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
709 #ifndef OPENSSL_NO_ENGINE
710 if (conf &&
711 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
712 conf->pkcs11_module_path)) {
713 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
714 ERR_load_ENGINE_strings();
715 ENGINE_load_dynamic();
717 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
718 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
719 conf->pkcs11_module_path)) {
720 tls_deinit(ssl);
721 return NULL;
724 #endif /* OPENSSL_NO_ENGINE */
726 return ssl;
730 void tls_deinit(void *ssl_ctx)
732 SSL_CTX *ssl = ssl_ctx;
733 SSL_CTX_free(ssl);
735 tls_openssl_ref_count--;
736 if (tls_openssl_ref_count == 0) {
737 #ifndef OPENSSL_NO_ENGINE
738 ENGINE_cleanup();
739 #endif /* OPENSSL_NO_ENGINE */
740 CRYPTO_cleanup_all_ex_data();
741 ERR_remove_state(0);
742 ERR_free_strings();
743 EVP_cleanup();
748 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
749 const char *pin, const char *key_id,
750 const char *cert_id, const char *ca_cert_id)
752 #ifndef OPENSSL_NO_ENGINE
753 int ret = -1;
754 if (engine_id == NULL) {
755 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
756 return -1;
758 if (pin == NULL) {
759 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
760 return -1;
762 if (key_id == NULL) {
763 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
764 return -1;
767 ERR_clear_error();
768 conn->engine = ENGINE_by_id(engine_id);
769 if (!conn->engine) {
770 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
771 engine_id, ERR_error_string(ERR_get_error(), NULL));
772 goto err;
774 if (ENGINE_init(conn->engine) != 1) {
775 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
776 "(engine: %s) [%s]", engine_id,
777 ERR_error_string(ERR_get_error(), NULL));
778 goto err;
780 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
782 if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
783 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
784 ERR_error_string(ERR_get_error(), NULL));
785 goto err;
787 /* load private key first in-case PIN is required for cert */
788 conn->private_key = ENGINE_load_private_key(conn->engine,
789 key_id, NULL, NULL);
790 if (!conn->private_key) {
791 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
792 " '%s' [%s]", key_id,
793 ERR_error_string(ERR_get_error(), NULL));
794 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
795 goto err;
798 /* handle a certificate and/or CA certificate */
799 if (cert_id || ca_cert_id) {
800 const char *cmd_name = "LOAD_CERT_CTRL";
802 /* test if the engine supports a LOAD_CERT_CTRL */
803 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
804 0, (void *)cmd_name, NULL)) {
805 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
806 " loading certificates");
807 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
808 goto err;
812 return 0;
814 err:
815 if (conn->engine) {
816 ENGINE_free(conn->engine);
817 conn->engine = NULL;
820 if (conn->private_key) {
821 EVP_PKEY_free(conn->private_key);
822 conn->private_key = NULL;
825 return ret;
826 #else /* OPENSSL_NO_ENGINE */
827 return 0;
828 #endif /* OPENSSL_NO_ENGINE */
832 static void tls_engine_deinit(struct tls_connection *conn)
834 #ifndef OPENSSL_NO_ENGINE
835 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
836 if (conn->private_key) {
837 EVP_PKEY_free(conn->private_key);
838 conn->private_key = NULL;
840 if (conn->engine) {
841 ENGINE_finish(conn->engine);
842 conn->engine = NULL;
844 #endif /* OPENSSL_NO_ENGINE */
848 int tls_get_errors(void *ssl_ctx)
850 int count = 0;
851 unsigned long err;
853 while ((err = ERR_get_error())) {
854 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
855 ERR_error_string(err, NULL));
856 count++;
859 return count;
862 struct tls_connection * tls_connection_init(void *ssl_ctx)
864 SSL_CTX *ssl = ssl_ctx;
865 struct tls_connection *conn;
866 long options;
868 conn = os_zalloc(sizeof(*conn));
869 if (conn == NULL)
870 return NULL;
871 conn->ssl = SSL_new(ssl);
872 if (conn->ssl == NULL) {
873 tls_show_errors(MSG_INFO, __func__,
874 "Failed to initialize new SSL connection");
875 os_free(conn);
876 return NULL;
879 SSL_set_app_data(conn->ssl, conn);
880 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
881 SSL_OP_SINGLE_DH_USE;
882 #ifdef SSL_OP_NO_COMPRESSION
883 options |= SSL_OP_NO_COMPRESSION;
884 #endif /* SSL_OP_NO_COMPRESSION */
885 SSL_set_options(conn->ssl, options);
887 conn->ssl_in = BIO_new(BIO_s_mem());
888 if (!conn->ssl_in) {
889 tls_show_errors(MSG_INFO, __func__,
890 "Failed to create a new BIO for ssl_in");
891 SSL_free(conn->ssl);
892 os_free(conn);
893 return NULL;
896 conn->ssl_out = BIO_new(BIO_s_mem());
897 if (!conn->ssl_out) {
898 tls_show_errors(MSG_INFO, __func__,
899 "Failed to create a new BIO for ssl_out");
900 SSL_free(conn->ssl);
901 BIO_free(conn->ssl_in);
902 os_free(conn);
903 return NULL;
906 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
908 return conn;
912 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
914 if (conn == NULL)
915 return;
916 SSL_free(conn->ssl);
917 tls_engine_deinit(conn);
918 os_free(conn->subject_match);
919 os_free(conn->altsubject_match);
920 os_free(conn->session_ticket);
921 os_free(conn);
925 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
927 return conn ? SSL_is_init_finished(conn->ssl) : 0;
931 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
933 if (conn == NULL)
934 return -1;
936 /* Shutdown previous TLS connection without notifying the peer
937 * because the connection was already terminated in practice
938 * and "close notify" shutdown alert would confuse AS. */
939 SSL_set_quiet_shutdown(conn->ssl, 1);
940 SSL_shutdown(conn->ssl);
941 return 0;
945 static int tls_match_altsubject_component(X509 *cert, int type,
946 const char *value, size_t len)
948 GENERAL_NAME *gen;
949 void *ext;
950 int i, found = 0;
952 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
954 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
955 gen = sk_GENERAL_NAME_value(ext, i);
956 if (gen->type != type)
957 continue;
958 if (os_strlen((char *) gen->d.ia5->data) == len &&
959 os_memcmp(value, gen->d.ia5->data, len) == 0)
960 found++;
963 return found;
967 static int tls_match_altsubject(X509 *cert, const char *match)
969 int type;
970 const char *pos, *end;
971 size_t len;
973 pos = match;
974 do {
975 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
976 type = GEN_EMAIL;
977 pos += 6;
978 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
979 type = GEN_DNS;
980 pos += 4;
981 } else if (os_strncmp(pos, "URI:", 4) == 0) {
982 type = GEN_URI;
983 pos += 4;
984 } else {
985 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
986 "match '%s'", pos);
987 return 0;
989 end = os_strchr(pos, ';');
990 while (end) {
991 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
992 os_strncmp(end + 1, "DNS:", 4) == 0 ||
993 os_strncmp(end + 1, "URI:", 4) == 0)
994 break;
995 end = os_strchr(end + 1, ';');
997 if (end)
998 len = end - pos;
999 else
1000 len = os_strlen(pos);
1001 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1002 return 1;
1003 pos = end + 1;
1004 } while (end);
1006 return 0;
1010 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1012 char buf[256];
1013 X509 *err_cert;
1014 int err, depth;
1015 SSL *ssl;
1016 struct tls_connection *conn;
1017 char *match, *altmatch;
1019 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1020 err = X509_STORE_CTX_get_error(x509_ctx);
1021 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1022 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1023 SSL_get_ex_data_X509_STORE_CTX_idx());
1024 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1026 conn = SSL_get_app_data(ssl);
1027 match = conn ? conn->subject_match : NULL;
1028 altmatch = conn ? conn->altsubject_match : NULL;
1030 if (!preverify_ok) {
1031 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1032 " error %d (%s) depth %d for '%s'", err,
1033 X509_verify_cert_error_string(err), depth, buf);
1034 } else {
1035 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - "
1036 "preverify_ok=%d err=%d (%s) depth=%d buf='%s'",
1037 preverify_ok, err,
1038 X509_verify_cert_error_string(err), depth, buf);
1039 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1040 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1041 "match with '%s'", buf, match);
1042 preverify_ok = 0;
1043 } else if (depth == 0 && altmatch &&
1044 !tls_match_altsubject(err_cert, altmatch)) {
1045 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1046 "'%s' not found", altmatch);
1047 preverify_ok = 0;
1051 return preverify_ok;
1055 #ifndef OPENSSL_NO_STDIO
1056 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1058 SSL_CTX *ssl_ctx = _ssl_ctx;
1059 X509_LOOKUP *lookup;
1060 int ret = 0;
1062 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1063 X509_LOOKUP_file());
1064 if (lookup == NULL) {
1065 tls_show_errors(MSG_WARNING, __func__,
1066 "Failed add lookup for X509 store");
1067 return -1;
1070 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1071 unsigned long err = ERR_peek_error();
1072 tls_show_errors(MSG_WARNING, __func__,
1073 "Failed load CA in DER format");
1074 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1075 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1076 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1077 "cert already in hash table error",
1078 __func__);
1079 } else
1080 ret = -1;
1083 return ret;
1085 #endif /* OPENSSL_NO_STDIO */
1088 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1089 const char *ca_cert, const u8 *ca_cert_blob,
1090 size_t ca_cert_blob_len, const char *ca_path)
1092 SSL_CTX *ssl_ctx = _ssl_ctx;
1095 * Remove previously configured trusted CA certificates before adding
1096 * new ones.
1098 X509_STORE_free(ssl_ctx->cert_store);
1099 ssl_ctx->cert_store = X509_STORE_new();
1100 if (ssl_ctx->cert_store == NULL) {
1101 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1102 "certificate store", __func__);
1103 return -1;
1106 if (ca_cert_blob) {
1107 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1108 ca_cert_blob_len);
1109 if (cert == NULL) {
1110 tls_show_errors(MSG_WARNING, __func__,
1111 "Failed to parse ca_cert_blob");
1112 return -1;
1115 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1116 unsigned long err = ERR_peek_error();
1117 tls_show_errors(MSG_WARNING, __func__,
1118 "Failed to add ca_cert_blob to "
1119 "certificate store");
1120 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1121 ERR_GET_REASON(err) ==
1122 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1123 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1124 "cert already in hash table error",
1125 __func__);
1126 } else {
1127 X509_free(cert);
1128 return -1;
1131 X509_free(cert);
1132 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1133 "to certificate store", __func__);
1134 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1135 return 0;
1138 #ifdef CONFIG_NATIVE_WINDOWS
1139 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1140 0) {
1141 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1142 "system certificate store");
1143 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1144 return 0;
1146 #endif /* CONFIG_NATIVE_WINDOWS */
1148 if (ca_cert || ca_path) {
1149 #ifndef OPENSSL_NO_STDIO
1150 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1151 1) {
1152 tls_show_errors(MSG_WARNING, __func__,
1153 "Failed to load root certificates");
1154 if (ca_cert &&
1155 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1156 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1157 "DER format CA certificate",
1158 __func__);
1159 } else
1160 return -1;
1161 } else {
1162 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1163 "certificate(s) loaded");
1164 tls_get_errors(ssl_ctx);
1166 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1167 #else /* OPENSSL_NO_STDIO */
1168 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1169 __func__);
1170 return -1;
1171 #endif /* OPENSSL_NO_STDIO */
1172 } else {
1173 /* No ca_cert configured - do not try to verify server
1174 * certificate */
1175 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1178 return 0;
1182 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1184 if (ca_cert) {
1185 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1187 tls_show_errors(MSG_WARNING, __func__,
1188 "Failed to load root certificates");
1189 return -1;
1192 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1193 "certificate(s) loaded");
1195 #ifndef OPENSSL_NO_STDIO
1196 /* Add the same CAs to the client certificate requests */
1197 SSL_CTX_set_client_CA_list(ssl_ctx,
1198 SSL_load_client_CA_file(ca_cert));
1199 #endif /* OPENSSL_NO_STDIO */
1202 return 0;
1206 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1208 int flags;
1210 if (check_crl) {
1211 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1212 if (cs == NULL) {
1213 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1214 "certificate store when enabling "
1215 "check_crl");
1216 return -1;
1218 flags = X509_V_FLAG_CRL_CHECK;
1219 if (check_crl == 2)
1220 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1221 X509_STORE_set_flags(cs, flags);
1223 return 0;
1227 static int tls_connection_set_subject_match(struct tls_connection *conn,
1228 const char *subject_match,
1229 const char *altsubject_match)
1231 os_free(conn->subject_match);
1232 conn->subject_match = NULL;
1233 if (subject_match) {
1234 conn->subject_match = os_strdup(subject_match);
1235 if (conn->subject_match == NULL)
1236 return -1;
1239 os_free(conn->altsubject_match);
1240 conn->altsubject_match = NULL;
1241 if (altsubject_match) {
1242 conn->altsubject_match = os_strdup(altsubject_match);
1243 if (conn->altsubject_match == NULL)
1244 return -1;
1247 return 0;
1251 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1252 int verify_peer)
1254 static int counter = 0;
1256 if (conn == NULL)
1257 return -1;
1259 if (verify_peer) {
1260 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1261 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1262 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1263 } else {
1264 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1267 SSL_set_accept_state(conn->ssl);
1270 * Set session id context in order to avoid fatal errors when client
1271 * tries to resume a session. However, set the context to a unique
1272 * value in order to effectively disable session resumption for now
1273 * since not all areas of the server code are ready for it (e.g.,
1274 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1275 * handshake).
1277 counter++;
1278 SSL_set_session_id_context(conn->ssl,
1279 (const unsigned char *) &counter,
1280 sizeof(counter));
1282 return 0;
1286 static int tls_connection_client_cert(struct tls_connection *conn,
1287 const char *client_cert,
1288 const u8 *client_cert_blob,
1289 size_t client_cert_blob_len)
1291 if (client_cert == NULL && client_cert_blob == NULL)
1292 return 0;
1294 if (client_cert_blob &&
1295 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1296 client_cert_blob_len) == 1) {
1297 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1298 "OK");
1299 return 0;
1300 } else if (client_cert_blob) {
1301 tls_show_errors(MSG_DEBUG, __func__,
1302 "SSL_use_certificate_ASN1 failed");
1305 if (client_cert == NULL)
1306 return -1;
1308 #ifndef OPENSSL_NO_STDIO
1309 if (SSL_use_certificate_file(conn->ssl, client_cert,
1310 SSL_FILETYPE_ASN1) == 1) {
1311 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1312 " --> OK");
1313 return 0;
1314 } else {
1315 tls_show_errors(MSG_DEBUG, __func__,
1316 "SSL_use_certificate_file (DER) failed");
1319 if (SSL_use_certificate_file(conn->ssl, client_cert,
1320 SSL_FILETYPE_PEM) == 1) {
1321 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1322 " --> OK");
1323 return 0;
1324 } else {
1325 tls_show_errors(MSG_DEBUG, __func__,
1326 "SSL_use_certificate_file (PEM) failed");
1328 #else /* OPENSSL_NO_STDIO */
1329 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1330 #endif /* OPENSSL_NO_STDIO */
1332 return -1;
1336 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1338 #ifndef OPENSSL_NO_STDIO
1339 if (client_cert == NULL)
1340 return 0;
1342 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1343 SSL_FILETYPE_ASN1) != 1 &&
1344 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1345 SSL_FILETYPE_PEM) != 1) {
1346 tls_show_errors(MSG_INFO, __func__,
1347 "Failed to load client certificate");
1348 return -1;
1350 return 0;
1351 #else /* OPENSSL_NO_STDIO */
1352 if (client_cert == NULL)
1353 return 0;
1354 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1355 return -1;
1356 #endif /* OPENSSL_NO_STDIO */
1360 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1362 if (password == NULL) {
1363 return 0;
1365 os_strlcpy(buf, (char *) password, size);
1366 return os_strlen(buf);
1370 #ifdef PKCS12_FUNCS
1371 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1372 const char *passwd)
1374 EVP_PKEY *pkey;
1375 X509 *cert;
1376 STACK_OF(X509) *certs;
1377 int res = 0;
1378 char buf[256];
1380 pkey = NULL;
1381 cert = NULL;
1382 certs = NULL;
1383 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1384 tls_show_errors(MSG_DEBUG, __func__,
1385 "Failed to parse PKCS12 file");
1386 PKCS12_free(p12);
1387 return -1;
1389 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1391 if (cert) {
1392 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1393 sizeof(buf));
1394 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1395 "subject='%s'", buf);
1396 if (ssl) {
1397 if (SSL_use_certificate(ssl, cert) != 1)
1398 res = -1;
1399 } else {
1400 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1401 res = -1;
1403 X509_free(cert);
1406 if (pkey) {
1407 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1408 if (ssl) {
1409 if (SSL_use_PrivateKey(ssl, pkey) != 1)
1410 res = -1;
1411 } else {
1412 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1413 res = -1;
1415 EVP_PKEY_free(pkey);
1418 if (certs) {
1419 while ((cert = sk_X509_pop(certs)) != NULL) {
1420 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1421 sizeof(buf));
1422 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1423 " from PKCS12: subject='%s'", buf);
1425 * There is no SSL equivalent for the chain cert - so
1426 * always add it to the context...
1428 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1429 res = -1;
1430 break;
1433 sk_X509_free(certs);
1436 PKCS12_free(p12);
1438 if (res < 0)
1439 tls_get_errors(ssl_ctx);
1441 return res;
1443 #endif /* PKCS12_FUNCS */
1446 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1447 const char *passwd)
1449 #ifdef PKCS12_FUNCS
1450 FILE *f;
1451 PKCS12 *p12;
1453 f = fopen(private_key, "rb");
1454 if (f == NULL)
1455 return -1;
1457 p12 = d2i_PKCS12_fp(f, NULL);
1458 fclose(f);
1460 if (p12 == NULL) {
1461 tls_show_errors(MSG_INFO, __func__,
1462 "Failed to use PKCS#12 file");
1463 return -1;
1466 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1468 #else /* PKCS12_FUNCS */
1469 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1470 "p12/pfx files");
1471 return -1;
1472 #endif /* PKCS12_FUNCS */
1476 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1477 const u8 *blob, size_t len, const char *passwd)
1479 #ifdef PKCS12_FUNCS
1480 PKCS12 *p12;
1482 p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1483 if (p12 == NULL) {
1484 tls_show_errors(MSG_INFO, __func__,
1485 "Failed to use PKCS#12 blob");
1486 return -1;
1489 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1491 #else /* PKCS12_FUNCS */
1492 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1493 "p12/pfx blobs");
1494 return -1;
1495 #endif /* PKCS12_FUNCS */
1499 #ifndef OPENSSL_NO_ENGINE
1500 static int tls_engine_get_cert(struct tls_connection *conn,
1501 const char *cert_id,
1502 X509 **cert)
1504 /* this runs after the private key is loaded so no PIN is required */
1505 struct {
1506 const char *cert_id;
1507 X509 *cert;
1508 } params;
1509 params.cert_id = cert_id;
1510 params.cert = NULL;
1512 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1513 0, &params, NULL, 1)) {
1514 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1515 " '%s' [%s]", cert_id,
1516 ERR_error_string(ERR_get_error(), NULL));
1517 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1519 if (!params.cert) {
1520 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1521 " '%s'", cert_id);
1522 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1524 *cert = params.cert;
1525 return 0;
1527 #endif /* OPENSSL_NO_ENGINE */
1530 static int tls_connection_engine_client_cert(struct tls_connection *conn,
1531 const char *cert_id)
1533 #ifndef OPENSSL_NO_ENGINE
1534 X509 *cert;
1536 if (tls_engine_get_cert(conn, cert_id, &cert))
1537 return -1;
1539 if (!SSL_use_certificate(conn->ssl, cert)) {
1540 tls_show_errors(MSG_ERROR, __func__,
1541 "SSL_use_certificate failed");
1542 X509_free(cert);
1543 return -1;
1545 X509_free(cert);
1546 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1547 "OK");
1548 return 0;
1550 #else /* OPENSSL_NO_ENGINE */
1551 return -1;
1552 #endif /* OPENSSL_NO_ENGINE */
1556 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1557 struct tls_connection *conn,
1558 const char *ca_cert_id)
1560 #ifndef OPENSSL_NO_ENGINE
1561 X509 *cert;
1562 SSL_CTX *ssl_ctx = _ssl_ctx;
1564 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1565 return -1;
1567 /* start off the same as tls_connection_ca_cert */
1568 X509_STORE_free(ssl_ctx->cert_store);
1569 ssl_ctx->cert_store = X509_STORE_new();
1570 if (ssl_ctx->cert_store == NULL) {
1571 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1572 "certificate store", __func__);
1573 X509_free(cert);
1574 return -1;
1576 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1577 unsigned long err = ERR_peek_error();
1578 tls_show_errors(MSG_WARNING, __func__,
1579 "Failed to add CA certificate from engine "
1580 "to certificate store");
1581 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1582 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1583 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1584 " already in hash table error",
1585 __func__);
1586 } else {
1587 X509_free(cert);
1588 return -1;
1591 X509_free(cert);
1592 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1593 "to certificate store", __func__);
1594 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1595 return 0;
1597 #else /* OPENSSL_NO_ENGINE */
1598 return -1;
1599 #endif /* OPENSSL_NO_ENGINE */
1603 static int tls_connection_engine_private_key(struct tls_connection *conn)
1605 #ifndef OPENSSL_NO_ENGINE
1606 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1607 tls_show_errors(MSG_ERROR, __func__,
1608 "ENGINE: cannot use private key for TLS");
1609 return -1;
1611 if (!SSL_check_private_key(conn->ssl)) {
1612 tls_show_errors(MSG_INFO, __func__,
1613 "Private key failed verification");
1614 return -1;
1616 return 0;
1617 #else /* OPENSSL_NO_ENGINE */
1618 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1619 "engine support was not compiled in");
1620 return -1;
1621 #endif /* OPENSSL_NO_ENGINE */
1625 static int tls_connection_private_key(void *_ssl_ctx,
1626 struct tls_connection *conn,
1627 const char *private_key,
1628 const char *private_key_passwd,
1629 const u8 *private_key_blob,
1630 size_t private_key_blob_len)
1632 SSL_CTX *ssl_ctx = _ssl_ctx;
1633 char *passwd;
1634 int ok;
1636 if (private_key == NULL && private_key_blob == NULL)
1637 return 0;
1639 if (private_key_passwd) {
1640 passwd = os_strdup(private_key_passwd);
1641 if (passwd == NULL)
1642 return -1;
1643 } else
1644 passwd = NULL;
1646 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1647 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1649 ok = 0;
1650 while (private_key_blob) {
1651 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1652 (u8 *) private_key_blob,
1653 private_key_blob_len) == 1) {
1654 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1655 "ASN1(EVP_PKEY_RSA) --> OK");
1656 ok = 1;
1657 break;
1658 } else {
1659 tls_show_errors(MSG_DEBUG, __func__,
1660 "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
1661 " failed");
1664 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1665 (u8 *) private_key_blob,
1666 private_key_blob_len) == 1) {
1667 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1668 "ASN1(EVP_PKEY_DSA) --> OK");
1669 ok = 1;
1670 break;
1671 } else {
1672 tls_show_errors(MSG_DEBUG, __func__,
1673 "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
1674 " failed");
1677 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1678 (u8 *) private_key_blob,
1679 private_key_blob_len) == 1) {
1680 wpa_printf(MSG_DEBUG, "OpenSSL: "
1681 "SSL_use_RSAPrivateKey_ASN1 --> OK");
1682 ok = 1;
1683 break;
1684 } else {
1685 tls_show_errors(MSG_DEBUG, __func__,
1686 "SSL_use_RSAPrivateKey_ASN1 failed");
1689 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1690 private_key_blob_len, passwd) == 0) {
1691 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1692 "OK");
1693 ok = 1;
1694 break;
1697 break;
1700 while (!ok && private_key) {
1701 #ifndef OPENSSL_NO_STDIO
1702 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1703 SSL_FILETYPE_ASN1) == 1) {
1704 wpa_printf(MSG_DEBUG, "OpenSSL: "
1705 "SSL_use_PrivateKey_File (DER) --> OK");
1706 ok = 1;
1707 break;
1708 } else {
1709 tls_show_errors(MSG_DEBUG, __func__,
1710 "SSL_use_PrivateKey_File (DER) "
1711 "failed");
1714 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1715 SSL_FILETYPE_PEM) == 1) {
1716 wpa_printf(MSG_DEBUG, "OpenSSL: "
1717 "SSL_use_PrivateKey_File (PEM) --> OK");
1718 ok = 1;
1719 break;
1720 } else {
1721 tls_show_errors(MSG_DEBUG, __func__,
1722 "SSL_use_PrivateKey_File (PEM) "
1723 "failed");
1725 #else /* OPENSSL_NO_STDIO */
1726 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1727 __func__);
1728 #endif /* OPENSSL_NO_STDIO */
1730 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
1731 == 0) {
1732 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
1733 "--> OK");
1734 ok = 1;
1735 break;
1738 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
1739 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
1740 "access certificate store --> OK");
1741 ok = 1;
1742 break;
1745 break;
1748 if (!ok) {
1749 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
1750 os_free(passwd);
1751 ERR_clear_error();
1752 return -1;
1754 ERR_clear_error();
1755 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1756 os_free(passwd);
1758 if (!SSL_check_private_key(conn->ssl)) {
1759 tls_show_errors(MSG_INFO, __func__, "Private key failed "
1760 "verification");
1761 return -1;
1764 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
1765 return 0;
1769 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
1770 const char *private_key_passwd)
1772 char *passwd;
1774 if (private_key == NULL)
1775 return 0;
1777 if (private_key_passwd) {
1778 passwd = os_strdup(private_key_passwd);
1779 if (passwd == NULL)
1780 return -1;
1781 } else
1782 passwd = NULL;
1784 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1785 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1786 if (
1787 #ifndef OPENSSL_NO_STDIO
1788 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1789 SSL_FILETYPE_ASN1) != 1 &&
1790 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1791 SSL_FILETYPE_PEM) != 1 &&
1792 #endif /* OPENSSL_NO_STDIO */
1793 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
1794 tls_show_errors(MSG_INFO, __func__,
1795 "Failed to load private key");
1796 os_free(passwd);
1797 ERR_clear_error();
1798 return -1;
1800 os_free(passwd);
1801 ERR_clear_error();
1802 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1804 if (!SSL_CTX_check_private_key(ssl_ctx)) {
1805 tls_show_errors(MSG_INFO, __func__,
1806 "Private key failed verification");
1807 return -1;
1810 return 0;
1814 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
1816 #ifdef OPENSSL_NO_DH
1817 if (dh_file == NULL)
1818 return 0;
1819 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1820 "dh_file specified");
1821 return -1;
1822 #else /* OPENSSL_NO_DH */
1823 DH *dh;
1824 BIO *bio;
1826 /* TODO: add support for dh_blob */
1827 if (dh_file == NULL)
1828 return 0;
1829 if (conn == NULL)
1830 return -1;
1832 bio = BIO_new_file(dh_file, "r");
1833 if (bio == NULL) {
1834 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1835 dh_file, ERR_error_string(ERR_get_error(), NULL));
1836 return -1;
1838 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1839 BIO_free(bio);
1840 #ifndef OPENSSL_NO_DSA
1841 while (dh == NULL) {
1842 DSA *dsa;
1843 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1844 " trying to parse as DSA params", dh_file,
1845 ERR_error_string(ERR_get_error(), NULL));
1846 bio = BIO_new_file(dh_file, "r");
1847 if (bio == NULL)
1848 break;
1849 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1850 BIO_free(bio);
1851 if (!dsa) {
1852 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1853 "'%s': %s", dh_file,
1854 ERR_error_string(ERR_get_error(), NULL));
1855 break;
1858 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1859 dh = DSA_dup_DH(dsa);
1860 DSA_free(dsa);
1861 if (dh == NULL) {
1862 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1863 "params into DH params");
1864 break;
1866 break;
1868 #endif /* !OPENSSL_NO_DSA */
1869 if (dh == NULL) {
1870 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1871 "'%s'", dh_file);
1872 return -1;
1875 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
1876 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1877 "%s", dh_file,
1878 ERR_error_string(ERR_get_error(), NULL));
1879 DH_free(dh);
1880 return -1;
1882 DH_free(dh);
1883 return 0;
1884 #endif /* OPENSSL_NO_DH */
1888 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
1890 #ifdef OPENSSL_NO_DH
1891 if (dh_file == NULL)
1892 return 0;
1893 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1894 "dh_file specified");
1895 return -1;
1896 #else /* OPENSSL_NO_DH */
1897 DH *dh;
1898 BIO *bio;
1900 /* TODO: add support for dh_blob */
1901 if (dh_file == NULL)
1902 return 0;
1903 if (ssl_ctx == NULL)
1904 return -1;
1906 bio = BIO_new_file(dh_file, "r");
1907 if (bio == NULL) {
1908 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1909 dh_file, ERR_error_string(ERR_get_error(), NULL));
1910 return -1;
1912 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1913 BIO_free(bio);
1914 #ifndef OPENSSL_NO_DSA
1915 while (dh == NULL) {
1916 DSA *dsa;
1917 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1918 " trying to parse as DSA params", dh_file,
1919 ERR_error_string(ERR_get_error(), NULL));
1920 bio = BIO_new_file(dh_file, "r");
1921 if (bio == NULL)
1922 break;
1923 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1924 BIO_free(bio);
1925 if (!dsa) {
1926 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1927 "'%s': %s", dh_file,
1928 ERR_error_string(ERR_get_error(), NULL));
1929 break;
1932 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1933 dh = DSA_dup_DH(dsa);
1934 DSA_free(dsa);
1935 if (dh == NULL) {
1936 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1937 "params into DH params");
1938 break;
1940 break;
1942 #endif /* !OPENSSL_NO_DSA */
1943 if (dh == NULL) {
1944 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1945 "'%s'", dh_file);
1946 return -1;
1949 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
1950 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1951 "%s", dh_file,
1952 ERR_error_string(ERR_get_error(), NULL));
1953 DH_free(dh);
1954 return -1;
1956 DH_free(dh);
1957 return 0;
1958 #endif /* OPENSSL_NO_DH */
1962 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
1963 struct tls_keys *keys)
1965 SSL *ssl;
1967 if (conn == NULL || keys == NULL)
1968 return -1;
1969 ssl = conn->ssl;
1970 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
1971 return -1;
1973 os_memset(keys, 0, sizeof(*keys));
1974 keys->master_key = ssl->session->master_key;
1975 keys->master_key_len = ssl->session->master_key_length;
1976 keys->client_random = ssl->s3->client_random;
1977 keys->client_random_len = SSL3_RANDOM_SIZE;
1978 keys->server_random = ssl->s3->server_random;
1979 keys->server_random_len = SSL3_RANDOM_SIZE;
1981 return 0;
1985 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
1986 const char *label, int server_random_first,
1987 u8 *out, size_t out_len)
1989 return -1;
1993 static struct wpabuf *
1994 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
1995 int server)
1997 int res;
1998 struct wpabuf *out_data;
2001 * Give TLS handshake data from the server (if available) to OpenSSL
2002 * for processing.
2004 if (in_data &&
2005 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2006 < 0) {
2007 tls_show_errors(MSG_INFO, __func__,
2008 "Handshake failed - BIO_write");
2009 return NULL;
2012 /* Initiate TLS handshake or continue the existing handshake */
2013 if (server)
2014 res = SSL_accept(conn->ssl);
2015 else
2016 res = SSL_connect(conn->ssl);
2017 if (res != 1) {
2018 int err = SSL_get_error(conn->ssl, res);
2019 if (err == SSL_ERROR_WANT_READ)
2020 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2021 "more data");
2022 else if (err == SSL_ERROR_WANT_WRITE)
2023 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2024 "write");
2025 else {
2026 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2027 conn->failed++;
2031 /* Get the TLS handshake data to be sent to the server */
2032 res = BIO_ctrl_pending(conn->ssl_out);
2033 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2034 out_data = wpabuf_alloc(res);
2035 if (out_data == NULL) {
2036 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2037 "handshake output (%d bytes)", res);
2038 if (BIO_reset(conn->ssl_out) < 0) {
2039 tls_show_errors(MSG_INFO, __func__,
2040 "BIO_reset failed");
2042 return NULL;
2044 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
2045 res);
2046 if (res < 0) {
2047 tls_show_errors(MSG_INFO, __func__,
2048 "Handshake failed - BIO_read");
2049 if (BIO_reset(conn->ssl_out) < 0) {
2050 tls_show_errors(MSG_INFO, __func__,
2051 "BIO_reset failed");
2053 wpabuf_free(out_data);
2054 return NULL;
2056 wpabuf_put(out_data, res);
2058 return out_data;
2062 static struct wpabuf *
2063 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
2065 struct wpabuf *appl_data;
2066 int res;
2068 appl_data = wpabuf_alloc(max_len + 100);
2069 if (appl_data == NULL)
2070 return NULL;
2072 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
2073 wpabuf_size(appl_data));
2074 if (res < 0) {
2075 int err = SSL_get_error(conn->ssl, res);
2076 if (err == SSL_ERROR_WANT_READ ||
2077 err == SSL_ERROR_WANT_WRITE) {
2078 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
2079 "included");
2080 } else {
2081 tls_show_errors(MSG_INFO, __func__,
2082 "Failed to read possible "
2083 "Application Data");
2085 wpabuf_free(appl_data);
2086 return NULL;
2089 wpabuf_put(appl_data, res);
2090 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
2091 "message", appl_data);
2093 return appl_data;
2097 static struct wpabuf *
2098 openssl_connection_handshake(struct tls_connection *conn,
2099 const struct wpabuf *in_data,
2100 struct wpabuf **appl_data, int server)
2102 struct wpabuf *out_data;
2104 if (appl_data)
2105 *appl_data = NULL;
2107 out_data = openssl_handshake(conn, in_data, server);
2108 if (out_data == NULL)
2109 return NULL;
2111 if (SSL_is_init_finished(conn->ssl) && appl_data && in_data)
2112 *appl_data = openssl_get_appl_data(conn, wpabuf_len(in_data));
2114 return out_data;
2118 struct wpabuf *
2119 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2120 const struct wpabuf *in_data,
2121 struct wpabuf **appl_data)
2123 return openssl_connection_handshake(conn, in_data, appl_data, 0);
2127 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
2128 struct tls_connection *conn,
2129 const struct wpabuf *in_data,
2130 struct wpabuf **appl_data)
2132 return openssl_connection_handshake(conn, in_data, appl_data, 1);
2136 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
2137 struct tls_connection *conn,
2138 const struct wpabuf *in_data)
2140 int res;
2141 struct wpabuf *buf;
2143 if (conn == NULL)
2144 return NULL;
2146 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2147 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2148 (res = BIO_reset(conn->ssl_out)) < 0) {
2149 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2150 return NULL;
2152 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
2153 if (res < 0) {
2154 tls_show_errors(MSG_INFO, __func__,
2155 "Encryption failed - SSL_write");
2156 return NULL;
2159 /* Read encrypted data to be sent to the server */
2160 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
2161 if (buf == NULL)
2162 return NULL;
2163 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
2164 if (res < 0) {
2165 tls_show_errors(MSG_INFO, __func__,
2166 "Encryption failed - BIO_read");
2167 wpabuf_free(buf);
2168 return NULL;
2170 wpabuf_put(buf, res);
2172 return buf;
2176 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
2177 struct tls_connection *conn,
2178 const struct wpabuf *in_data)
2180 int res;
2181 struct wpabuf *buf;
2183 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2184 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
2185 wpabuf_len(in_data));
2186 if (res < 0) {
2187 tls_show_errors(MSG_INFO, __func__,
2188 "Decryption failed - BIO_write");
2189 return NULL;
2191 if (BIO_reset(conn->ssl_out) < 0) {
2192 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2193 return NULL;
2196 /* Read decrypted data for further processing */
2198 * Even though we try to disable TLS compression, it is possible that
2199 * this cannot be done with all TLS libraries. Add extra buffer space
2200 * to handle the possibility of the decrypted data being longer than
2201 * input data.
2203 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
2204 if (buf == NULL)
2205 return NULL;
2206 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
2207 if (res < 0) {
2208 tls_show_errors(MSG_INFO, __func__,
2209 "Decryption failed - SSL_read");
2210 wpabuf_free(buf);
2211 return NULL;
2213 wpabuf_put(buf, res);
2215 return buf;
2219 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2221 return conn ? conn->ssl->hit : 0;
2225 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2226 u8 *ciphers)
2228 char buf[100], *pos, *end;
2229 u8 *c;
2230 int ret;
2232 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2233 return -1;
2235 buf[0] = '\0';
2236 pos = buf;
2237 end = pos + sizeof(buf);
2239 c = ciphers;
2240 while (*c != TLS_CIPHER_NONE) {
2241 const char *suite;
2243 switch (*c) {
2244 case TLS_CIPHER_RC4_SHA:
2245 suite = "RC4-SHA";
2246 break;
2247 case TLS_CIPHER_AES128_SHA:
2248 suite = "AES128-SHA";
2249 break;
2250 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2251 suite = "DHE-RSA-AES128-SHA";
2252 break;
2253 case TLS_CIPHER_ANON_DH_AES128_SHA:
2254 suite = "ADH-AES128-SHA";
2255 break;
2256 default:
2257 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2258 "cipher selection: %d", *c);
2259 return -1;
2261 ret = os_snprintf(pos, end - pos, ":%s", suite);
2262 if (ret < 0 || ret >= end - pos)
2263 break;
2264 pos += ret;
2266 c++;
2269 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2271 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2272 tls_show_errors(MSG_INFO, __func__,
2273 "Cipher suite configuration failed");
2274 return -1;
2277 return 0;
2281 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2282 char *buf, size_t buflen)
2284 const char *name;
2285 if (conn == NULL || conn->ssl == NULL)
2286 return -1;
2288 name = SSL_get_cipher(conn->ssl);
2289 if (name == NULL)
2290 return -1;
2292 os_strlcpy(buf, name, buflen);
2293 return 0;
2297 int tls_connection_enable_workaround(void *ssl_ctx,
2298 struct tls_connection *conn)
2300 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2302 return 0;
2306 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2307 /* ClientHello TLS extensions require a patch to openssl, so this function is
2308 * commented out unless explicitly needed for EAP-FAST in order to be able to
2309 * build this file with unmodified openssl. */
2310 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2311 int ext_type, const u8 *data,
2312 size_t data_len)
2314 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
2315 return -1;
2317 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2318 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
2319 data_len) != 1)
2320 return -1;
2321 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2322 if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2323 data_len) != 1)
2324 return -1;
2325 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2327 return 0;
2329 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2332 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2334 if (conn == NULL)
2335 return -1;
2336 return conn->failed;
2340 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2342 if (conn == NULL)
2343 return -1;
2344 return conn->read_alerts;
2348 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2350 if (conn == NULL)
2351 return -1;
2352 return conn->write_alerts;
2356 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2357 const struct tls_connection_params *params)
2359 int ret;
2360 unsigned long err;
2362 if (conn == NULL)
2363 return -1;
2365 while ((err = ERR_get_error())) {
2366 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2367 __func__, ERR_error_string(err, NULL));
2370 if (params->engine) {
2371 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2372 ret = tls_engine_init(conn, params->engine_id, params->pin,
2373 params->key_id, params->cert_id,
2374 params->ca_cert_id);
2375 if (ret)
2376 return ret;
2378 if (tls_connection_set_subject_match(conn,
2379 params->subject_match,
2380 params->altsubject_match))
2381 return -1;
2383 if (params->engine && params->ca_cert_id) {
2384 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2385 params->ca_cert_id))
2386 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2387 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2388 params->ca_cert_blob,
2389 params->ca_cert_blob_len,
2390 params->ca_path))
2391 return -1;
2393 if (params->engine && params->cert_id) {
2394 if (tls_connection_engine_client_cert(conn, params->cert_id))
2395 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2396 } else if (tls_connection_client_cert(conn, params->client_cert,
2397 params->client_cert_blob,
2398 params->client_cert_blob_len))
2399 return -1;
2401 if (params->engine && params->key_id) {
2402 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2403 if (tls_connection_engine_private_key(conn))
2404 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2405 } else if (tls_connection_private_key(tls_ctx, conn,
2406 params->private_key,
2407 params->private_key_passwd,
2408 params->private_key_blob,
2409 params->private_key_blob_len)) {
2410 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2411 params->private_key);
2412 return -1;
2415 if (tls_connection_dh(conn, params->dh_file)) {
2416 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2417 params->dh_file);
2418 return -1;
2421 tls_get_errors(tls_ctx);
2423 return 0;
2427 int tls_global_set_params(void *tls_ctx,
2428 const struct tls_connection_params *params)
2430 SSL_CTX *ssl_ctx = tls_ctx;
2431 unsigned long err;
2433 while ((err = ERR_get_error())) {
2434 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2435 __func__, ERR_error_string(err, NULL));
2438 if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2439 return -1;
2441 if (tls_global_client_cert(ssl_ctx, params->client_cert))
2442 return -1;
2444 if (tls_global_private_key(ssl_ctx, params->private_key,
2445 params->private_key_passwd))
2446 return -1;
2448 if (tls_global_dh(ssl_ctx, params->dh_file)) {
2449 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2450 params->dh_file);
2451 return -1;
2454 return 0;
2458 int tls_connection_get_keyblock_size(void *tls_ctx,
2459 struct tls_connection *conn)
2461 const EVP_CIPHER *c;
2462 const EVP_MD *h;
2464 if (conn == NULL || conn->ssl == NULL ||
2465 conn->ssl->enc_read_ctx == NULL ||
2466 conn->ssl->enc_read_ctx->cipher == NULL ||
2467 conn->ssl->read_hash == NULL)
2468 return -1;
2470 c = conn->ssl->enc_read_ctx->cipher;
2471 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2472 h = EVP_MD_CTX_md(conn->ssl->read_hash);
2473 #else
2474 h = conn->ssl->read_hash;
2475 #endif
2477 return 2 * (EVP_CIPHER_key_length(c) +
2478 EVP_MD_size(h) +
2479 EVP_CIPHER_iv_length(c));
2483 unsigned int tls_capabilities(void *tls_ctx)
2485 return 0;
2489 int tls_connection_set_ia(void *tls_ctx, struct tls_connection *conn,
2490 int tls_ia)
2492 return -1;
2496 struct wpabuf * tls_connection_ia_send_phase_finished(
2497 void *tls_ctx, struct tls_connection *conn, int final)
2499 return NULL;
2503 int tls_connection_ia_final_phase_finished(void *tls_ctx,
2504 struct tls_connection *conn)
2506 return -1;
2510 int tls_connection_ia_permute_inner_secret(void *tls_ctx,
2511 struct tls_connection *conn,
2512 const u8 *key, size_t key_len)
2514 return -1;
2518 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2519 /* Pre-shared secred requires a patch to openssl, so this function is
2520 * commented out unless explicitly needed for EAP-FAST in order to be able to
2521 * build this file with unmodified openssl. */
2523 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2524 STACK_OF(SSL_CIPHER) *peer_ciphers,
2525 SSL_CIPHER **cipher, void *arg)
2527 struct tls_connection *conn = arg;
2528 int ret;
2530 if (conn == NULL || conn->session_ticket_cb == NULL)
2531 return 0;
2533 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2534 conn->session_ticket,
2535 conn->session_ticket_len,
2536 s->s3->client_random,
2537 s->s3->server_random, secret);
2538 os_free(conn->session_ticket);
2539 conn->session_ticket = NULL;
2541 if (ret <= 0)
2542 return 0;
2544 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2545 return 1;
2549 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2550 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
2551 int len, void *arg)
2553 struct tls_connection *conn = arg;
2555 if (conn == NULL || conn->session_ticket_cb == NULL)
2556 return 0;
2558 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
2560 os_free(conn->session_ticket);
2561 conn->session_ticket = NULL;
2563 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2564 "extension", data, len);
2566 conn->session_ticket = os_malloc(len);
2567 if (conn->session_ticket == NULL)
2568 return 0;
2570 os_memcpy(conn->session_ticket, data, len);
2571 conn->session_ticket_len = len;
2573 return 1;
2575 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2576 #ifdef SSL_OP_NO_TICKET
2577 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2578 unsigned char *data, int len, void *arg)
2580 struct tls_connection *conn = arg;
2582 if (conn == NULL || conn->session_ticket_cb == NULL)
2583 return;
2585 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2586 type, len);
2588 if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2589 os_free(conn->session_ticket);
2590 conn->session_ticket = NULL;
2592 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2593 "extension", data, len);
2594 conn->session_ticket = os_malloc(len);
2595 if (conn->session_ticket == NULL)
2596 return;
2598 os_memcpy(conn->session_ticket, data, len);
2599 conn->session_ticket_len = len;
2602 #else /* SSL_OP_NO_TICKET */
2603 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2605 struct tls_connection *conn = arg;
2607 if (conn == NULL || conn->session_ticket_cb == NULL)
2608 return 0;
2610 wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2611 ext->type, ext->length);
2613 os_free(conn->session_ticket);
2614 conn->session_ticket = NULL;
2616 if (ext->type == 35) {
2617 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2618 "extension", ext->data, ext->length);
2619 conn->session_ticket = os_malloc(ext->length);
2620 if (conn->session_ticket == NULL)
2621 return SSL_AD_INTERNAL_ERROR;
2623 os_memcpy(conn->session_ticket, ext->data, ext->length);
2624 conn->session_ticket_len = ext->length;
2627 return 0;
2629 #endif /* SSL_OP_NO_TICKET */
2630 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2631 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2634 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2635 struct tls_connection *conn,
2636 tls_session_ticket_cb cb,
2637 void *ctx)
2639 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
2640 conn->session_ticket_cb = cb;
2641 conn->session_ticket_cb_ctx = ctx;
2643 if (cb) {
2644 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2645 conn) != 1)
2646 return -1;
2647 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2648 SSL_set_session_ticket_ext_cb(conn->ssl,
2649 tls_session_ticket_ext_cb, conn);
2650 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2651 #ifdef SSL_OP_NO_TICKET
2652 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2653 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2654 #else /* SSL_OP_NO_TICKET */
2655 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2656 conn) != 1)
2657 return -1;
2658 #endif /* SSL_OP_NO_TICKET */
2659 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2660 } else {
2661 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2662 return -1;
2663 #ifdef CONFIG_OPENSSL_TICKET_OVERRIDE
2664 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
2665 #else /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2666 #ifdef SSL_OP_NO_TICKET
2667 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2668 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2669 #else /* SSL_OP_NO_TICKET */
2670 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2671 return -1;
2672 #endif /* SSL_OP_NO_TICKET */
2673 #endif /* CONFIG_OPENSSL_TICKET_OVERRIDE */
2676 return 0;
2677 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
2678 return -1;
2679 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */