]> git.ipfire.org Git - thirdparty/hostap.git/blame - src/crypto/tls_openssl.c
OpenSSL: Handshake completion and resumption state into debug log
[thirdparty/hostap.git] / src / crypto / tls_openssl.c
CommitLineData
6fc6879b 1/*
81c85c06 2 * SSL/TLS interface functions for OpenSSL
16bc3b89 3 * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
6fc6879b 4 *
0f3d578e
JM
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
6fc6879b
JM
7 */
8
9#include "includes.h"
10
11#ifndef CONFIG_SMARTCARD
12#ifndef OPENSSL_NO_ENGINE
1176ab6d 13#ifndef ANDROID
6fc6879b
JM
14#define OPENSSL_NO_ENGINE
15#endif
16#endif
1176ab6d 17#endif
6fc6879b
JM
18
19#include <openssl/ssl.h>
20#include <openssl/err.h>
21#include <openssl/pkcs12.h>
22#include <openssl/x509v3.h>
23#ifndef OPENSSL_NO_ENGINE
24#include <openssl/engine.h>
25#endif /* OPENSSL_NO_ENGINE */
690e543e
JM
26#ifndef OPENSSL_NO_DSA
27#include <openssl/dsa.h>
28#endif
29#ifndef OPENSSL_NO_DH
30#include <openssl/dh.h>
31#endif
6fc6879b
JM
32
33#include "common.h"
00468b46 34#include "crypto.h"
fa0e7151 35#include "sha1.h"
16bc3b89 36#include "sha256.h"
6fc6879b
JM
37#include "tls.h"
38
a8572960
AL
39#if OPENSSL_VERSION_NUMBER < 0x10000000L
40/* ERR_remove_thread_state replaces ERR_remove_state and the latter is
41 * deprecated. However, OpenSSL 0.9.8 doesn't include
42 * ERR_remove_thread_state. */
43#define ERR_remove_thread_state(tid) ERR_remove_state(0)
44#endif
45
a8572960
AL
46#if defined(OPENSSL_IS_BORINGSSL)
47/* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
48typedef size_t stack_index_t;
49#else
50typedef int stack_index_t;
0cf03892
JM
51#endif
52
080585c0
JM
53#ifdef SSL_set_tlsext_status_type
54#ifndef OPENSSL_NO_TLSEXT
55#define HAVE_OCSP
56#include <openssl/ocsp.h>
57#endif /* OPENSSL_NO_TLSEXT */
58#endif /* SSL_set_tlsext_status_type */
59
1d415f1f
KR
60#ifdef ANDROID
61#include <openssl/pem.h>
62#include <keystore/keystore_get.h>
63
64static BIO * BIO_from_keystore(const char *key)
65{
66 BIO *bio = NULL;
67 uint8_t *value = NULL;
68 int length = keystore_get(key, strlen(key), &value);
69 if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
70 BIO_write(bio, value, length);
71 free(value);
72 return bio;
73}
74#endif /* ANDROID */
75
6fc6879b
JM
76static int tls_openssl_ref_count = 0;
77
7c0e1e27 78struct tls_context {
00468b46
JM
79 void (*event_cb)(void *ctx, enum tls_event ev,
80 union tls_event_data *data);
81 void *cb_ctx;
1b414f59 82 int cert_in_cb;
080585c0 83 char *ocsp_stapling_response;
00468b46
JM
84};
85
7c0e1e27 86static struct tls_context *tls_global = NULL;
00468b46
JM
87
88
6fc6879b 89struct tls_connection {
7c0e1e27 90 struct tls_context *context;
68ae4773 91 SSL_CTX *ssl_ctx;
6fc6879b
JM
92 SSL *ssl;
93 BIO *ssl_in, *ssl_out;
94#ifndef OPENSSL_NO_ENGINE
95 ENGINE *engine; /* functional reference to the engine */
96 EVP_PKEY *private_key; /* the private key if using engine */
97#endif /* OPENSSL_NO_ENGINE */
cebee30f 98 char *subject_match, *altsubject_match, *suffix_match, *domain_match;
6fc6879b
JM
99 int read_alerts, write_alerts, failed;
100
101 tls_session_ticket_cb session_ticket_cb;
102 void *session_ticket_cb_ctx;
103
104 /* SessionTicket received from OpenSSL hello_extension_cb (server) */
105 u8 *session_ticket;
106 size_t session_ticket_len;
00468b46 107
8d6399e4
JM
108 unsigned int ca_cert_verify:1;
109 unsigned int cert_probe:1;
110 unsigned int server_cert_only:1;
bb52293e 111 unsigned int invalid_hb_used:1;
00468b46
JM
112
113 u8 srv_cert_hash[32];
235279e7
JM
114
115 unsigned int flags;
080585c0
JM
116
117 X509 *peer_cert;
118 X509 *peer_issuer;
6bf61fb2 119 X509 *peer_issuer_issuer;
005c5dcf
JM
120
121#if OPENSSL_VERSION_NUMBER >= 0x10100000L
122 unsigned char client_random[SSL3_RANDOM_SIZE];
123 unsigned char server_random[SSL3_RANDOM_SIZE];
124#endif
6fc6879b
JM
125};
126
127
7c0e1e27
PS
128static struct tls_context * tls_context_new(const struct tls_config *conf)
129{
130 struct tls_context *context = os_zalloc(sizeof(*context));
131 if (context == NULL)
132 return NULL;
133 if (conf) {
134 context->event_cb = conf->event_cb;
135 context->cb_ctx = conf->cb_ctx;
136 context->cert_in_cb = conf->cert_in_cb;
137 }
138 return context;
139}
140
141
6fc6879b
JM
142#ifdef CONFIG_NO_STDOUT_DEBUG
143
144static void _tls_show_errors(void)
145{
146 unsigned long err;
147
148 while ((err = ERR_get_error())) {
149 /* Just ignore the errors, since stdout is disabled */
150 }
151}
152#define tls_show_errors(l, f, t) _tls_show_errors()
153
154#else /* CONFIG_NO_STDOUT_DEBUG */
155
156static void tls_show_errors(int level, const char *func, const char *txt)
157{
158 unsigned long err;
159
160 wpa_printf(level, "OpenSSL: %s - %s %s",
161 func, txt, ERR_error_string(ERR_get_error(), NULL));
162
163 while ((err = ERR_get_error())) {
164 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
165 ERR_error_string(err, NULL));
166 }
167}
168
169#endif /* CONFIG_NO_STDOUT_DEBUG */
170
171
172#ifdef CONFIG_NATIVE_WINDOWS
173
174/* Windows CryptoAPI and access to certificate stores */
175#include <wincrypt.h>
176
177#ifdef __MINGW32_VERSION
178/*
179 * MinGW does not yet include all the needed definitions for CryptoAPI, so
180 * define here whatever extra is needed.
181 */
6fc6879b
JM
182#define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
183#define CERT_STORE_READONLY_FLAG 0x00008000
184#define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
6fc6879b
JM
185
186#endif /* __MINGW32_VERSION */
187
188
189struct cryptoapi_rsa_data {
190 const CERT_CONTEXT *cert;
191 HCRYPTPROV crypt_prov;
192 DWORD key_spec;
193 BOOL free_crypt_prov;
194};
195
196
197static void cryptoapi_error(const char *msg)
198{
199 wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
200 msg, (unsigned int) GetLastError());
201}
202
203
204static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
205 unsigned char *to, RSA *rsa, int padding)
206{
207 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
208 return 0;
209}
210
211
212static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
213 unsigned char *to, RSA *rsa, int padding)
214{
215 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
216 return 0;
217}
218
219
220static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
221 unsigned char *to, RSA *rsa, int padding)
222{
223 struct cryptoapi_rsa_data *priv =
224 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
225 HCRYPTHASH hash;
226 DWORD hash_size, len, i;
227 unsigned char *buf = NULL;
228 int ret = 0;
229
230 if (priv == NULL) {
231 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
232 ERR_R_PASSED_NULL_PARAMETER);
233 return 0;
234 }
235
236 if (padding != RSA_PKCS1_PADDING) {
237 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
238 RSA_R_UNKNOWN_PADDING_TYPE);
239 return 0;
240 }
241
242 if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
243 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
244 __func__);
245 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
246 RSA_R_INVALID_MESSAGE_LENGTH);
247 return 0;
248 }
249
250 if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
251 {
252 cryptoapi_error("CryptCreateHash failed");
253 return 0;
254 }
255
256 len = sizeof(hash_size);
257 if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
258 0)) {
259 cryptoapi_error("CryptGetHashParam failed");
260 goto err;
261 }
262
263 if ((int) hash_size != flen) {
264 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
265 (unsigned) hash_size, flen);
266 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
267 RSA_R_INVALID_MESSAGE_LENGTH);
268 goto err;
269 }
270 if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
271 cryptoapi_error("CryptSetHashParam failed");
272 goto err;
273 }
274
275 len = RSA_size(rsa);
276 buf = os_malloc(len);
277 if (buf == NULL) {
278 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
279 goto err;
280 }
281
282 if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
283 cryptoapi_error("CryptSignHash failed");
284 goto err;
285 }
286
287 for (i = 0; i < len; i++)
288 to[i] = buf[len - i - 1];
289 ret = len;
290
291err:
292 os_free(buf);
293 CryptDestroyHash(hash);
294
295 return ret;
296}
297
298
299static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
300 unsigned char *to, RSA *rsa, int padding)
301{
302 wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
303 return 0;
304}
305
306
307static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
308{
309 if (priv == NULL)
310 return;
311 if (priv->crypt_prov && priv->free_crypt_prov)
312 CryptReleaseContext(priv->crypt_prov, 0);
313 if (priv->cert)
314 CertFreeCertificateContext(priv->cert);
315 os_free(priv);
316}
317
318
319static int cryptoapi_finish(RSA *rsa)
320{
321 cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
322 os_free((void *) rsa->meth);
323 rsa->meth = NULL;
324 return 1;
325}
326
327
328static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
329{
330 HCERTSTORE cs;
331 const CERT_CONTEXT *ret = NULL;
332
333 cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
334 store | CERT_STORE_OPEN_EXISTING_FLAG |
335 CERT_STORE_READONLY_FLAG, L"MY");
336 if (cs == NULL) {
337 cryptoapi_error("Failed to open 'My system store'");
338 return NULL;
339 }
340
341 if (strncmp(name, "cert://", 7) == 0) {
342 unsigned short wbuf[255];
343 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
344 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
345 PKCS_7_ASN_ENCODING,
346 0, CERT_FIND_SUBJECT_STR,
347 wbuf, NULL);
348 } else if (strncmp(name, "hash://", 7) == 0) {
349 CRYPT_HASH_BLOB blob;
350 int len;
351 const char *hash = name + 7;
352 unsigned char *buf;
353
354 len = os_strlen(hash) / 2;
355 buf = os_malloc(len);
356 if (buf && hexstr2bin(hash, buf, len) == 0) {
357 blob.cbData = len;
358 blob.pbData = buf;
359 ret = CertFindCertificateInStore(cs,
360 X509_ASN_ENCODING |
361 PKCS_7_ASN_ENCODING,
362 0, CERT_FIND_HASH,
363 &blob, NULL);
364 }
365 os_free(buf);
366 }
367
368 CertCloseStore(cs, 0);
369
370 return ret;
371}
372
373
374static int tls_cryptoapi_cert(SSL *ssl, const char *name)
375{
376 X509 *cert = NULL;
377 RSA *rsa = NULL, *pub_rsa;
378 struct cryptoapi_rsa_data *priv;
379 RSA_METHOD *rsa_meth;
380
381 if (name == NULL ||
382 (strncmp(name, "cert://", 7) != 0 &&
383 strncmp(name, "hash://", 7) != 0))
384 return -1;
385
386 priv = os_zalloc(sizeof(*priv));
387 rsa_meth = os_zalloc(sizeof(*rsa_meth));
388 if (priv == NULL || rsa_meth == NULL) {
389 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
390 "for CryptoAPI RSA method");
391 os_free(priv);
392 os_free(rsa_meth);
393 return -1;
394 }
395
396 priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
397 if (priv->cert == NULL) {
398 priv->cert = cryptoapi_find_cert(
399 name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
400 }
401 if (priv->cert == NULL) {
402 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
403 "'%s'", name);
404 goto err;
405 }
406
fee31f76
JM
407 cert = d2i_X509(NULL,
408 (const unsigned char **) &priv->cert->pbCertEncoded,
6fc6879b
JM
409 priv->cert->cbCertEncoded);
410 if (cert == NULL) {
411 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
412 "encoding");
413 goto err;
414 }
415
6fc6879b
JM
416 if (!CryptAcquireCertificatePrivateKey(priv->cert,
417 CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
418 NULL, &priv->crypt_prov,
419 &priv->key_spec,
420 &priv->free_crypt_prov)) {
421 cryptoapi_error("Failed to acquire a private key for the "
422 "certificate");
423 goto err;
424 }
425
426 rsa_meth->name = "Microsoft CryptoAPI RSA Method";
427 rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
428 rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
429 rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
430 rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
431 rsa_meth->finish = cryptoapi_finish;
432 rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
433 rsa_meth->app_data = (char *) priv;
434
435 rsa = RSA_new();
436 if (rsa == NULL) {
437 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
438 ERR_R_MALLOC_FAILURE);
439 goto err;
440 }
441
442 if (!SSL_use_certificate(ssl, cert)) {
443 RSA_free(rsa);
444 rsa = NULL;
445 goto err;
446 }
447 pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
448 X509_free(cert);
449 cert = NULL;
450
451 rsa->n = BN_dup(pub_rsa->n);
452 rsa->e = BN_dup(pub_rsa->e);
453 if (!RSA_set_method(rsa, rsa_meth))
454 goto err;
455
456 if (!SSL_use_RSAPrivateKey(ssl, rsa))
457 goto err;
458 RSA_free(rsa);
459
460 return 0;
461
462err:
463 if (cert)
464 X509_free(cert);
465 if (rsa)
466 RSA_free(rsa);
467 else {
468 os_free(rsa_meth);
469 cryptoapi_free_data(priv);
470 }
471 return -1;
472}
473
474
475static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
476{
477 HCERTSTORE cs;
478 PCCERT_CONTEXT ctx = NULL;
479 X509 *cert;
480 char buf[128];
481 const char *store;
482#ifdef UNICODE
483 WCHAR *wstore;
484#endif /* UNICODE */
485
6fc6879b
JM
486 if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
487 return -1;
488
489 store = name + 13;
490#ifdef UNICODE
491 wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
492 if (wstore == NULL)
493 return -1;
494 wsprintf(wstore, L"%S", store);
495 cs = CertOpenSystemStore(0, wstore);
496 os_free(wstore);
497#else /* UNICODE */
498 cs = CertOpenSystemStore(0, store);
499#endif /* UNICODE */
500 if (cs == NULL) {
501 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
502 "'%s': error=%d", __func__, store,
503 (int) GetLastError());
504 return -1;
505 }
506
507 while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
fee31f76
JM
508 cert = d2i_X509(NULL,
509 (const unsigned char **) &ctx->pbCertEncoded,
6fc6879b
JM
510 ctx->cbCertEncoded);
511 if (cert == NULL) {
512 wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
513 "X509 DER encoding for CA cert");
514 continue;
515 }
516
517 X509_NAME_oneline(X509_get_subject_name(cert), buf,
518 sizeof(buf));
519 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
520 "system certificate store: subject='%s'", buf);
521
522 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
523 tls_show_errors(MSG_WARNING, __func__,
524 "Failed to add ca_cert to OpenSSL "
525 "certificate store");
526 }
527
528 X509_free(cert);
529 }
530
531 if (!CertCloseStore(cs, 0)) {
532 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
533 "'%s': error=%d", __func__, name + 13,
534 (int) GetLastError());
535 }
536
537 return 0;
538}
539
540
541#else /* CONFIG_NATIVE_WINDOWS */
542
543static int tls_cryptoapi_cert(SSL *ssl, const char *name)
544{
545 return -1;
546}
547
548#endif /* CONFIG_NATIVE_WINDOWS */
549
550
551static void ssl_info_cb(const SSL *ssl, int where, int ret)
552{
553 const char *str;
554 int w;
555
556 wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
557 w = where & ~SSL_ST_MASK;
558 if (w & SSL_ST_CONNECT)
559 str = "SSL_connect";
560 else if (w & SSL_ST_ACCEPT)
561 str = "SSL_accept";
562 else
563 str = "undefined";
564
565 if (where & SSL_CB_LOOP) {
566 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
567 str, SSL_state_string_long(ssl));
568 } else if (where & SSL_CB_ALERT) {
7c0e1e27 569 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
6fc6879b
JM
570 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
571 where & SSL_CB_READ ?
572 "read (remote end reported an error)" :
573 "write (local SSL3 detected an error)",
574 SSL_alert_type_string_long(ret),
575 SSL_alert_desc_string_long(ret));
576 if ((ret >> 8) == SSL3_AL_FATAL) {
6fc6879b
JM
577 if (where & SSL_CB_READ)
578 conn->read_alerts++;
579 else
580 conn->write_alerts++;
581 }
7c0e1e27 582 if (conn->context->event_cb != NULL) {
dd7fec1f 583 union tls_event_data ev;
7c0e1e27 584 struct tls_context *context = conn->context;
dd7fec1f
PS
585 os_memset(&ev, 0, sizeof(ev));
586 ev.alert.is_local = !(where & SSL_CB_READ);
587 ev.alert.type = SSL_alert_type_string_long(ret);
588 ev.alert.description = SSL_alert_desc_string_long(ret);
7c0e1e27 589 context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
dd7fec1f 590 }
6fc6879b
JM
591 } else if (where & SSL_CB_EXIT && ret <= 0) {
592 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
593 str, ret == 0 ? "failed" : "error",
594 SSL_state_string_long(ssl));
595 }
596}
597
598
599#ifndef OPENSSL_NO_ENGINE
600/**
601 * tls_engine_load_dynamic_generic - load any openssl engine
602 * @pre: an array of commands and values that load an engine initialized
603 * in the engine specific function
604 * @post: an array of commands and values that initialize an already loaded
605 * engine (or %NULL if not required)
606 * @id: the engine id of the engine to load (only required if post is not %NULL
607 *
608 * This function is a generic function that loads any openssl engine.
609 *
610 * Returns: 0 on success, -1 on failure
611 */
612static int tls_engine_load_dynamic_generic(const char *pre[],
613 const char *post[], const char *id)
614{
615 ENGINE *engine;
616 const char *dynamic_id = "dynamic";
617
618 engine = ENGINE_by_id(id);
619 if (engine) {
620 ENGINE_free(engine);
621 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
622 "available", id);
623 return 0;
624 }
625 ERR_clear_error();
626
627 engine = ENGINE_by_id(dynamic_id);
628 if (engine == NULL) {
629 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
630 dynamic_id,
631 ERR_error_string(ERR_get_error(), NULL));
632 return -1;
633 }
634
635 /* Perform the pre commands. This will load the engine. */
636 while (pre && pre[0]) {
637 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
638 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
639 wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
640 "%s %s [%s]", pre[0], pre[1],
641 ERR_error_string(ERR_get_error(), NULL));
642 ENGINE_free(engine);
643 return -1;
644 }
645 pre += 2;
646 }
647
648 /*
649 * Free the reference to the "dynamic" engine. The loaded engine can
650 * now be looked up using ENGINE_by_id().
651 */
652 ENGINE_free(engine);
653
654 engine = ENGINE_by_id(id);
655 if (engine == NULL) {
656 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
657 id, ERR_error_string(ERR_get_error(), NULL));
658 return -1;
659 }
660
661 while (post && post[0]) {
662 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
663 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
664 wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
665 " %s %s [%s]", post[0], post[1],
666 ERR_error_string(ERR_get_error(), NULL));
667 ENGINE_remove(engine);
668 ENGINE_free(engine);
669 return -1;
670 }
671 post += 2;
672 }
673 ENGINE_free(engine);
674
675 return 0;
676}
677
678
679/**
680 * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
681 * @pkcs11_so_path: pksc11_so_path from the configuration
682 * @pcks11_module_path: pkcs11_module_path from the configuration
683 */
684static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
685 const char *pkcs11_module_path)
686{
687 char *engine_id = "pkcs11";
688 const char *pre_cmd[] = {
689 "SO_PATH", NULL /* pkcs11_so_path */,
690 "ID", NULL /* engine_id */,
691 "LIST_ADD", "1",
692 /* "NO_VCHECK", "1", */
693 "LOAD", NULL,
694 NULL, NULL
695 };
696 const char *post_cmd[] = {
697 "MODULE_PATH", NULL /* pkcs11_module_path */,
698 NULL, NULL
699 };
700
5c8ab0d4 701 if (!pkcs11_so_path)
6fc6879b
JM
702 return 0;
703
704 pre_cmd[1] = pkcs11_so_path;
705 pre_cmd[3] = engine_id;
5c8ab0d4
DW
706 if (pkcs11_module_path)
707 post_cmd[1] = pkcs11_module_path;
708 else
709 post_cmd[0] = NULL;
6fc6879b
JM
710
711 wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
712 pkcs11_so_path);
713
714 return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
715}
716
717
718/**
719 * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
720 * @opensc_so_path: opensc_so_path from the configuration
721 */
722static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
723{
724 char *engine_id = "opensc";
725 const char *pre_cmd[] = {
726 "SO_PATH", NULL /* opensc_so_path */,
727 "ID", NULL /* engine_id */,
728 "LIST_ADD", "1",
729 "LOAD", NULL,
730 NULL, NULL
731 };
732
733 if (!opensc_so_path)
734 return 0;
735
736 pre_cmd[1] = opensc_so_path;
737 pre_cmd[3] = engine_id;
738
739 wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
740 opensc_so_path);
741
742 return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
743}
744#endif /* OPENSSL_NO_ENGINE */
745
746
747void * tls_init(const struct tls_config *conf)
748{
749 SSL_CTX *ssl;
7c0e1e27 750 struct tls_context *context;
b7328434 751 const char *ciphers;
6fc6879b
JM
752
753 if (tls_openssl_ref_count == 0) {
7c0e1e27
PS
754 tls_global = context = tls_context_new(conf);
755 if (context == NULL)
00468b46 756 return NULL;
76f04b38
JM
757#ifdef CONFIG_FIPS
758#ifdef OPENSSL_FIPS
cf123d7f 759 if (conf && conf->fips_mode) {
4fc53159
JM
760 static int fips_enabled = 0;
761
762 if (!fips_enabled && !FIPS_mode_set(1)) {
76f04b38
JM
763 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
764 "mode");
765 ERR_load_crypto_strings();
766 ERR_print_errors_fp(stderr);
b36540db
JM
767 os_free(tls_global);
768 tls_global = NULL;
76f04b38 769 return NULL;
4fc53159 770 } else {
76f04b38 771 wpa_printf(MSG_INFO, "Running in FIPS mode");
4fc53159
JM
772 fips_enabled = 1;
773 }
76f04b38
JM
774 }
775#else /* OPENSSL_FIPS */
cf123d7f 776 if (conf && conf->fips_mode) {
76f04b38
JM
777 wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
778 "supported");
b36540db
JM
779 os_free(tls_global);
780 tls_global = NULL;
76f04b38
JM
781 return NULL;
782 }
783#endif /* OPENSSL_FIPS */
784#endif /* CONFIG_FIPS */
6fc6879b
JM
785 SSL_load_error_strings();
786 SSL_library_init();
fee31f76 787#ifndef OPENSSL_NO_SHA256
e1ffdfc1
JM
788 EVP_add_digest(EVP_sha256());
789#endif /* OPENSSL_NO_SHA256 */
6fc6879b
JM
790 /* TODO: if /dev/urandom is available, PRNG is seeded
791 * automatically. If this is not the case, random data should
792 * be added here. */
793
794#ifdef PKCS12_FUNCS
1056dad7
JM
795#ifndef OPENSSL_NO_RC2
796 /*
797 * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
798 * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
799 * versions, but it looks like OpenSSL 1.0.0 does not do that
800 * anymore.
801 */
802 EVP_add_cipher(EVP_rc2_40_cbc());
803#endif /* OPENSSL_NO_RC2 */
6fc6879b
JM
804 PKCS12_PBE_add();
805#endif /* PKCS12_FUNCS */
7c0e1e27 806 } else {
7c0e1e27
PS
807 context = tls_context_new(conf);
808 if (context == NULL)
809 return NULL;
6fc6879b
JM
810 }
811 tls_openssl_ref_count++;
812
35efa247 813 ssl = SSL_CTX_new(SSLv23_method());
7c0e1e27
PS
814 if (ssl == NULL) {
815 tls_openssl_ref_count--;
a288da61
JM
816 if (context != tls_global)
817 os_free(context);
7c0e1e27
PS
818 if (tls_openssl_ref_count == 0) {
819 os_free(tls_global);
820 tls_global = NULL;
7c0e1e27 821 }
6fc6879b 822 return NULL;
7c0e1e27 823 }
6fc6879b 824
35efa247
JM
825 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
826 SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
827
6fc6879b 828 SSL_CTX_set_info_callback(ssl, ssl_info_cb);
7c0e1e27 829 SSL_CTX_set_app_data(ssl, context);
6fc6879b
JM
830
831#ifndef OPENSSL_NO_ENGINE
ddda6276
DW
832 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
833 ERR_load_ENGINE_strings();
834 ENGINE_load_dynamic();
835
6fc6879b
JM
836 if (conf &&
837 (conf->opensc_engine_path || conf->pkcs11_engine_path ||
838 conf->pkcs11_module_path)) {
6fc6879b
JM
839 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
840 tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
841 conf->pkcs11_module_path)) {
842 tls_deinit(ssl);
843 return NULL;
844 }
845 }
846#endif /* OPENSSL_NO_ENGINE */
847
b7328434
JM
848 if (conf && conf->openssl_ciphers)
849 ciphers = conf->openssl_ciphers;
850 else
851 ciphers = "DEFAULT:!EXP:!LOW";
852 if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
853 wpa_printf(MSG_ERROR,
854 "OpenSSL: Failed to set cipher string '%s'",
855 ciphers);
856 tls_deinit(ssl);
857 return NULL;
858 }
859
6fc6879b
JM
860 return ssl;
861}
862
863
864void tls_deinit(void *ssl_ctx)
865{
866 SSL_CTX *ssl = ssl_ctx;
7c0e1e27
PS
867 struct tls_context *context = SSL_CTX_get_app_data(ssl);
868 if (context != tls_global)
869 os_free(context);
6fc6879b
JM
870 SSL_CTX_free(ssl);
871
872 tls_openssl_ref_count--;
873 if (tls_openssl_ref_count == 0) {
874#ifndef OPENSSL_NO_ENGINE
875 ENGINE_cleanup();
876#endif /* OPENSSL_NO_ENGINE */
877 CRYPTO_cleanup_all_ex_data();
a8572960 878 ERR_remove_thread_state(NULL);
6fc6879b
JM
879 ERR_free_strings();
880 EVP_cleanup();
080585c0
JM
881 os_free(tls_global->ocsp_stapling_response);
882 tls_global->ocsp_stapling_response = NULL;
00468b46
JM
883 os_free(tls_global);
884 tls_global = NULL;
6fc6879b
JM
885 }
886}
887
888
fd4fb281
MG
889#ifndef OPENSSL_NO_ENGINE
890
891/* Cryptoki return values */
892#define CKR_PIN_INCORRECT 0x000000a0
893#define CKR_PIN_INVALID 0x000000a1
894#define CKR_PIN_LEN_RANGE 0x000000a2
895
896/* libp11 */
897#define ERR_LIB_PKCS11 ERR_LIB_USER
898
899static int tls_is_pin_error(unsigned int err)
900{
901 return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
902 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
903 ERR_GET_REASON(err) == CKR_PIN_INVALID ||
904 ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
905}
906
907#endif /* OPENSSL_NO_ENGINE */
908
909
6fc6879b 910static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
e59c91af
DS
911 const char *pin, const char *key_id,
912 const char *cert_id, const char *ca_cert_id)
6fc6879b
JM
913{
914#ifndef OPENSSL_NO_ENGINE
915 int ret = -1;
916 if (engine_id == NULL) {
917 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
918 return -1;
919 }
6fc6879b
JM
920
921 ERR_clear_error();
1176ab6d
KR
922#ifdef ANDROID
923 ENGINE_load_dynamic();
924#endif
6fc6879b
JM
925 conn->engine = ENGINE_by_id(engine_id);
926 if (!conn->engine) {
927 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
928 engine_id, ERR_error_string(ERR_get_error(), NULL));
929 goto err;
930 }
931 if (ENGINE_init(conn->engine) != 1) {
932 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
933 "(engine: %s) [%s]", engine_id,
934 ERR_error_string(ERR_get_error(), NULL));
935 goto err;
936 }
937 wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
938
1176ab6d 939#ifndef ANDROID
a642a52b 940 if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
6fc6879b
JM
941 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
942 ERR_error_string(ERR_get_error(), NULL));
943 goto err;
944 }
1176ab6d 945#endif
3d268b8d 946 if (key_id) {
a642a52b
DW
947 /*
948 * Ensure that the ENGINE does not attempt to use the OpenSSL
949 * UI system to obtain a PIN, if we didn't provide one.
950 */
951 struct {
952 const void *password;
953 const char *prompt_info;
954 } key_cb = { "", NULL };
955
3d268b8d
DW
956 /* load private key first in-case PIN is required for cert */
957 conn->private_key = ENGINE_load_private_key(conn->engine,
a642a52b
DW
958 key_id, NULL,
959 &key_cb);
3d268b8d 960 if (!conn->private_key) {
fd4fb281
MG
961 unsigned long err = ERR_get_error();
962
3d268b8d
DW
963 wpa_printf(MSG_ERROR,
964 "ENGINE: cannot load private key with id '%s' [%s]",
965 key_id,
fd4fb281
MG
966 ERR_error_string(err, NULL));
967 if (tls_is_pin_error(err))
968 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
969 else
970 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3d268b8d
DW
971 goto err;
972 }
6fc6879b 973 }
e59c91af
DS
974
975 /* handle a certificate and/or CA certificate */
976 if (cert_id || ca_cert_id) {
977 const char *cmd_name = "LOAD_CERT_CTRL";
978
979 /* test if the engine supports a LOAD_CERT_CTRL */
980 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
981 0, (void *)cmd_name, NULL)) {
982 wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
983 " loading certificates");
984 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
985 goto err;
986 }
987 }
988
6fc6879b
JM
989 return 0;
990
991err:
992 if (conn->engine) {
993 ENGINE_free(conn->engine);
994 conn->engine = NULL;
995 }
996
997 if (conn->private_key) {
998 EVP_PKEY_free(conn->private_key);
999 conn->private_key = NULL;
1000 }
1001
1002 return ret;
1003#else /* OPENSSL_NO_ENGINE */
1004 return 0;
1005#endif /* OPENSSL_NO_ENGINE */
1006}
1007
1008
1009static void tls_engine_deinit(struct tls_connection *conn)
1010{
1011#ifndef OPENSSL_NO_ENGINE
1012 wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1013 if (conn->private_key) {
1014 EVP_PKEY_free(conn->private_key);
1015 conn->private_key = NULL;
1016 }
1017 if (conn->engine) {
1018 ENGINE_finish(conn->engine);
1019 conn->engine = NULL;
1020 }
1021#endif /* OPENSSL_NO_ENGINE */
1022}
1023
1024
1025int tls_get_errors(void *ssl_ctx)
1026{
1027 int count = 0;
1028 unsigned long err;
1029
1030 while ((err = ERR_get_error())) {
1031 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1032 ERR_error_string(err, NULL));
1033 count++;
1034 }
1035
1036 return count;
1037}
1038
bb52293e
JM
1039
1040static void tls_msg_cb(int write_p, int version, int content_type,
1041 const void *buf, size_t len, SSL *ssl, void *arg)
1042{
1043 struct tls_connection *conn = arg;
1044 const u8 *pos = buf;
1045
1046 wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
1047 write_p ? "TX" : "RX", version, content_type);
1048 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1049 if (content_type == 24 && len >= 3 && pos[0] == 1) {
1050 size_t payload_len = WPA_GET_BE16(pos + 1);
1051 if (payload_len + 3 > len) {
1052 wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1053 conn->invalid_hb_used = 1;
1054 }
1055 }
1056}
1057
1058
6a31a31d 1059struct tls_connection * tls_connection_init(void *ssl_ctx)
6fc6879b 1060{
6a31a31d
JM
1061 SSL_CTX *ssl = ssl_ctx;
1062 struct tls_connection *conn;
fca25ef4 1063 long options;
6a31a31d 1064 struct tls_context *context = SSL_CTX_get_app_data(ssl);
6fc6879b 1065
6a31a31d
JM
1066 conn = os_zalloc(sizeof(*conn));
1067 if (conn == NULL)
1068 return NULL;
68ae4773 1069 conn->ssl_ctx = ssl_ctx;
6a31a31d
JM
1070 conn->ssl = SSL_new(ssl);
1071 if (conn->ssl == NULL) {
6fc6879b
JM
1072 tls_show_errors(MSG_INFO, __func__,
1073 "Failed to initialize new SSL connection");
6a31a31d
JM
1074 os_free(conn);
1075 return NULL;
6fc6879b
JM
1076 }
1077
6a31a31d
JM
1078 conn->context = context;
1079 SSL_set_app_data(conn->ssl, conn);
1080 SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1081 SSL_set_msg_callback_arg(conn->ssl, conn);
fca25ef4
JM
1082 options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1083 SSL_OP_SINGLE_DH_USE;
1084#ifdef SSL_OP_NO_COMPRESSION
1085 options |= SSL_OP_NO_COMPRESSION;
1086#endif /* SSL_OP_NO_COMPRESSION */
6a31a31d 1087 SSL_set_options(conn->ssl, options);
6fc6879b 1088
6a31a31d
JM
1089 conn->ssl_in = BIO_new(BIO_s_mem());
1090 if (!conn->ssl_in) {
6fc6879b
JM
1091 tls_show_errors(MSG_INFO, __func__,
1092 "Failed to create a new BIO for ssl_in");
6a31a31d
JM
1093 SSL_free(conn->ssl);
1094 os_free(conn);
1095 return NULL;
6fc6879b
JM
1096 }
1097
6a31a31d
JM
1098 conn->ssl_out = BIO_new(BIO_s_mem());
1099 if (!conn->ssl_out) {
6fc6879b
JM
1100 tls_show_errors(MSG_INFO, __func__,
1101 "Failed to create a new BIO for ssl_out");
1102 SSL_free(conn->ssl);
6a31a31d 1103 BIO_free(conn->ssl_in);
6fc6879b
JM
1104 os_free(conn);
1105 return NULL;
1106 }
1107
6a31a31d
JM
1108 SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1109
6fc6879b
JM
1110 return conn;
1111}
1112
1113
1114void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1115{
1116 if (conn == NULL)
1117 return;
1118 SSL_free(conn->ssl);
1119 tls_engine_deinit(conn);
1120 os_free(conn->subject_match);
1121 os_free(conn->altsubject_match);
01f809c7 1122 os_free(conn->suffix_match);
cebee30f 1123 os_free(conn->domain_match);
6fc6879b
JM
1124 os_free(conn->session_ticket);
1125 os_free(conn);
1126}
1127
1128
1129int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1130{
1131 return conn ? SSL_is_init_finished(conn->ssl) : 0;
1132}
1133
1134
1135int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1136{
1137 if (conn == NULL)
1138 return -1;
1139
1140 /* Shutdown previous TLS connection without notifying the peer
1141 * because the connection was already terminated in practice
1142 * and "close notify" shutdown alert would confuse AS. */
1143 SSL_set_quiet_shutdown(conn->ssl, 1);
1144 SSL_shutdown(conn->ssl);
a7803b0c 1145 return SSL_clear(conn->ssl) == 1 ? 0 : -1;
6fc6879b
JM
1146}
1147
1148
1149static int tls_match_altsubject_component(X509 *cert, int type,
1150 const char *value, size_t len)
1151{
1152 GENERAL_NAME *gen;
1153 void *ext;
a8572960
AL
1154 int found = 0;
1155 stack_index_t i;
6fc6879b
JM
1156
1157 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1158
1159 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1160 gen = sk_GENERAL_NAME_value(ext, i);
1161 if (gen->type != type)
1162 continue;
1163 if (os_strlen((char *) gen->d.ia5->data) == len &&
1164 os_memcmp(value, gen->d.ia5->data, len) == 0)
1165 found++;
1166 }
1167
1168 return found;
1169}
1170
1171
1172static int tls_match_altsubject(X509 *cert, const char *match)
1173{
1174 int type;
1175 const char *pos, *end;
1176 size_t len;
1177
1178 pos = match;
1179 do {
1180 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1181 type = GEN_EMAIL;
1182 pos += 6;
1183 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1184 type = GEN_DNS;
1185 pos += 4;
1186 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1187 type = GEN_URI;
1188 pos += 4;
1189 } else {
1190 wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1191 "match '%s'", pos);
1192 return 0;
1193 }
1194 end = os_strchr(pos, ';');
1195 while (end) {
1196 if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1197 os_strncmp(end + 1, "DNS:", 4) == 0 ||
1198 os_strncmp(end + 1, "URI:", 4) == 0)
1199 break;
1200 end = os_strchr(end + 1, ';');
1201 }
1202 if (end)
1203 len = end - pos;
1204 else
1205 len = os_strlen(pos);
1206 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1207 return 1;
1208 pos = end + 1;
1209 } while (end);
1210
1211 return 0;
1212}
1213
1214
461e3ebe 1215#ifndef CONFIG_NATIVE_WINDOWS
cebee30f
JM
1216static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1217 int full)
01f809c7
JM
1218{
1219 size_t i, match_len;
1220
1221 /* Check for embedded nuls that could mess up suffix matching */
1222 for (i = 0; i < len; i++) {
1223 if (val[i] == '\0') {
1224 wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1225 return 0;
1226 }
1227 }
1228
1229 match_len = os_strlen(match);
cebee30f 1230 if (match_len > len || (full && match_len != len))
01f809c7
JM
1231 return 0;
1232
1233 if (os_strncasecmp((const char *) val + len - match_len, match,
1234 match_len) != 0)
1235 return 0; /* no match */
1236
1237 if (match_len == len)
1238 return 1; /* exact match */
1239
1240 if (val[len - match_len - 1] == '.')
1241 return 1; /* full label match completes suffix match */
1242
1243 wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1244 return 0;
1245}
461e3ebe 1246#endif /* CONFIG_NATIVE_WINDOWS */
01f809c7
JM
1247
1248
cebee30f 1249static int tls_match_suffix(X509 *cert, const char *match, int full)
01f809c7 1250{
461e3ebe
JM
1251#ifdef CONFIG_NATIVE_WINDOWS
1252 /* wincrypt.h has conflicting X509_NAME definition */
1253 return -1;
1254#else /* CONFIG_NATIVE_WINDOWS */
01f809c7
JM
1255 GENERAL_NAME *gen;
1256 void *ext;
1257 int i;
98a1571d 1258 stack_index_t j;
01f809c7
JM
1259 int dns_name = 0;
1260 X509_NAME *name;
1261
cebee30f
JM
1262 wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
1263 full ? "": "suffix ", match);
01f809c7
JM
1264
1265 ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1266
98a1571d
JM
1267 for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
1268 gen = sk_GENERAL_NAME_value(ext, j);
01f809c7
JM
1269 if (gen->type != GEN_DNS)
1270 continue;
1271 dns_name++;
1272 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
1273 gen->d.dNSName->data,
1274 gen->d.dNSName->length);
1275 if (domain_suffix_match(gen->d.dNSName->data,
cebee30f
JM
1276 gen->d.dNSName->length, match, full) ==
1277 1) {
1278 wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
1279 full ? "Match" : "Suffix match");
01f809c7
JM
1280 return 1;
1281 }
1282 }
1283
1284 if (dns_name) {
1285 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
1286 return 0;
1287 }
1288
1289 name = X509_get_subject_name(cert);
1290 i = -1;
1291 for (;;) {
1292 X509_NAME_ENTRY *e;
1293 ASN1_STRING *cn;
1294
1295 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
1296 if (i == -1)
1297 break;
1298 e = X509_NAME_get_entry(name, i);
1299 if (e == NULL)
1300 continue;
1301 cn = X509_NAME_ENTRY_get_data(e);
1302 if (cn == NULL)
1303 continue;
1304 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
1305 cn->data, cn->length);
cebee30f
JM
1306 if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
1307 {
1308 wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
1309 full ? "Match" : "Suffix match");
01f809c7
JM
1310 return 1;
1311 }
1312 }
1313
cebee30f
JM
1314 wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
1315 full ? "": "suffix ");
01f809c7 1316 return 0;
461e3ebe 1317#endif /* CONFIG_NATIVE_WINDOWS */
01f809c7
JM
1318}
1319
1320
00468b46
JM
1321static enum tls_fail_reason openssl_tls_fail_reason(int err)
1322{
1323 switch (err) {
1324 case X509_V_ERR_CERT_REVOKED:
1325 return TLS_FAIL_REVOKED;
1326 case X509_V_ERR_CERT_NOT_YET_VALID:
1327 case X509_V_ERR_CRL_NOT_YET_VALID:
1328 return TLS_FAIL_NOT_YET_VALID;
1329 case X509_V_ERR_CERT_HAS_EXPIRED:
1330 case X509_V_ERR_CRL_HAS_EXPIRED:
1331 return TLS_FAIL_EXPIRED;
1332 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
1333 case X509_V_ERR_UNABLE_TO_GET_CRL:
1334 case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
1335 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
1336 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
1337 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
1338 case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
1339 case X509_V_ERR_CERT_CHAIN_TOO_LONG:
1340 case X509_V_ERR_PATH_LENGTH_EXCEEDED:
1341 case X509_V_ERR_INVALID_CA:
1342 return TLS_FAIL_UNTRUSTED;
1343 case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
1344 case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
1345 case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
1346 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
1347 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
1348 case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
1349 case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
1350 case X509_V_ERR_CERT_UNTRUSTED:
1351 case X509_V_ERR_CERT_REJECTED:
1352 return TLS_FAIL_BAD_CERTIFICATE;
1353 default:
1354 return TLS_FAIL_UNSPECIFIED;
1355 }
1356}
1357
1358
1359static struct wpabuf * get_x509_cert(X509 *cert)
1360{
1361 struct wpabuf *buf;
1362 u8 *tmp;
1363
1364 int cert_len = i2d_X509(cert, NULL);
1365 if (cert_len <= 0)
1366 return NULL;
1367
1368 buf = wpabuf_alloc(cert_len);
1369 if (buf == NULL)
1370 return NULL;
1371
1372 tmp = wpabuf_put(buf, cert_len);
1373 i2d_X509(cert, &tmp);
1374 return buf;
1375}
1376
1377
1378static void openssl_tls_fail_event(struct tls_connection *conn,
1379 X509 *err_cert, int err, int depth,
1380 const char *subject, const char *err_str,
1381 enum tls_fail_reason reason)
1382{
1383 union tls_event_data ev;
1384 struct wpabuf *cert = NULL;
7c0e1e27 1385 struct tls_context *context = conn->context;
00468b46 1386
7c0e1e27 1387 if (context->event_cb == NULL)
00468b46
JM
1388 return;
1389
1390 cert = get_x509_cert(err_cert);
1391 os_memset(&ev, 0, sizeof(ev));
1392 ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
1393 reason : openssl_tls_fail_reason(err);
1394 ev.cert_fail.depth = depth;
1395 ev.cert_fail.subject = subject;
1396 ev.cert_fail.reason_txt = err_str;
1397 ev.cert_fail.cert = cert;
7c0e1e27 1398 context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
00468b46
JM
1399 wpabuf_free(cert);
1400}
1401
1402
1403static void openssl_tls_cert_event(struct tls_connection *conn,
1404 X509 *err_cert, int depth,
1405 const char *subject)
1406{
1407 struct wpabuf *cert = NULL;
1408 union tls_event_data ev;
7c0e1e27 1409 struct tls_context *context = conn->context;
d07d3fbd
JM
1410 char *altsubject[TLS_MAX_ALT_SUBJECT];
1411 int alt, num_altsubject = 0;
1412 GENERAL_NAME *gen;
1413 void *ext;
1414 stack_index_t i;
00468b46
JM
1415#ifdef CONFIG_SHA256
1416 u8 hash[32];
1417#endif /* CONFIG_SHA256 */
1418
7c0e1e27 1419 if (context->event_cb == NULL)
00468b46
JM
1420 return;
1421
1422 os_memset(&ev, 0, sizeof(ev));
7c0e1e27 1423 if (conn->cert_probe || context->cert_in_cb) {
00468b46
JM
1424 cert = get_x509_cert(err_cert);
1425 ev.peer_cert.cert = cert;
1426 }
1427#ifdef CONFIG_SHA256
1428 if (cert) {
1429 const u8 *addr[1];
1430 size_t len[1];
1431 addr[0] = wpabuf_head(cert);
1432 len[0] = wpabuf_len(cert);
1433 if (sha256_vector(1, addr, len, hash) == 0) {
1434 ev.peer_cert.hash = hash;
1435 ev.peer_cert.hash_len = sizeof(hash);
1436 }
1437 }
1438#endif /* CONFIG_SHA256 */
1439 ev.peer_cert.depth = depth;
1440 ev.peer_cert.subject = subject;
d07d3fbd
JM
1441
1442 ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
1443 for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1444 char *pos;
1445
1446 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
1447 break;
1448 gen = sk_GENERAL_NAME_value(ext, i);
1449 if (gen->type != GEN_EMAIL &&
1450 gen->type != GEN_DNS &&
1451 gen->type != GEN_URI)
1452 continue;
1453
1454 pos = os_malloc(10 + gen->d.ia5->length + 1);
1455 if (pos == NULL)
1456 break;
1457 altsubject[num_altsubject++] = pos;
1458
1459 switch (gen->type) {
1460 case GEN_EMAIL:
1461 os_memcpy(pos, "EMAIL:", 6);
1462 pos += 6;
1463 break;
1464 case GEN_DNS:
1465 os_memcpy(pos, "DNS:", 4);
1466 pos += 4;
1467 break;
1468 case GEN_URI:
1469 os_memcpy(pos, "URI:", 4);
1470 pos += 4;
1471 break;
1472 }
1473
1474 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
1475 pos += gen->d.ia5->length;
1476 *pos = '\0';
1477 }
1478
1479 for (alt = 0; alt < num_altsubject; alt++)
1480 ev.peer_cert.altsubject[alt] = altsubject[alt];
1481 ev.peer_cert.num_altsubject = num_altsubject;
1482
7c0e1e27 1483 context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
00468b46 1484 wpabuf_free(cert);
d07d3fbd
JM
1485 for (alt = 0; alt < num_altsubject; alt++)
1486 os_free(altsubject[alt]);
00468b46
JM
1487}
1488
1489
6fc6879b
JM
1490static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1491{
1492 char buf[256];
1493 X509 *err_cert;
1494 int err, depth;
1495 SSL *ssl;
1496 struct tls_connection *conn;
7c0e1e27 1497 struct tls_context *context;
cebee30f 1498 char *match, *altmatch, *suffix_match, *domain_match;
00468b46 1499 const char *err_str;
6fc6879b
JM
1500
1501 err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
97efe70b
EL
1502 if (!err_cert)
1503 return 0;
1504
6fc6879b
JM
1505 err = X509_STORE_CTX_get_error(x509_ctx);
1506 depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1507 ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1508 SSL_get_ex_data_X509_STORE_CTX_idx());
1509 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1510
1511 conn = SSL_get_app_data(ssl);
0bdaa741
JM
1512 if (conn == NULL)
1513 return 0;
080585c0
JM
1514
1515 if (depth == 0)
1516 conn->peer_cert = err_cert;
1517 else if (depth == 1)
1518 conn->peer_issuer = err_cert;
6bf61fb2
JM
1519 else if (depth == 2)
1520 conn->peer_issuer_issuer = err_cert;
080585c0 1521
7c0e1e27 1522 context = conn->context;
0bdaa741
JM
1523 match = conn->subject_match;
1524 altmatch = conn->altsubject_match;
01f809c7 1525 suffix_match = conn->suffix_match;
cebee30f 1526 domain_match = conn->domain_match;
6fc6879b 1527
00468b46
JM
1528 if (!preverify_ok && !conn->ca_cert_verify)
1529 preverify_ok = 1;
1530 if (!preverify_ok && depth > 0 && conn->server_cert_only)
1531 preverify_ok = 1;
235279e7
JM
1532 if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1533 (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1534 err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1535 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
1536 "time mismatch");
1537 preverify_ok = 1;
1538 }
00468b46
JM
1539
1540 err_str = X509_verify_cert_error_string(err);
1541
1542#ifdef CONFIG_SHA256
00033a09
RA
1543 /*
1544 * Do not require preverify_ok so we can explicity allow otherwise
1545 * invalid pinned server certificates.
1546 */
1547 if (depth == 0 && conn->server_cert_only) {
00468b46
JM
1548 struct wpabuf *cert;
1549 cert = get_x509_cert(err_cert);
1550 if (!cert) {
1551 wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
1552 "server certificate data");
6fc6879b 1553 preverify_ok = 0;
00468b46
JM
1554 } else {
1555 u8 hash[32];
1556 const u8 *addr[1];
1557 size_t len[1];
1558 addr[0] = wpabuf_head(cert);
1559 len[0] = wpabuf_len(cert);
1560 if (sha256_vector(1, addr, len, hash) < 0 ||
1561 os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1562 err_str = "Server certificate mismatch";
1563 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1564 preverify_ok = 0;
00033a09
RA
1565 } else if (!preverify_ok) {
1566 /*
1567 * Certificate matches pinned certificate, allow
1568 * regardless of other problems.
1569 */
1570 wpa_printf(MSG_DEBUG,
1571 "OpenSSL: Ignore validation issues for a pinned server certificate");
1572 preverify_ok = 1;
00468b46
JM
1573 }
1574 wpabuf_free(cert);
6fc6879b
JM
1575 }
1576 }
00468b46
JM
1577#endif /* CONFIG_SHA256 */
1578
1579 if (!preverify_ok) {
1580 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1581 " error %d (%s) depth %d for '%s'", err, err_str,
1582 depth, buf);
1583 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1584 err_str, TLS_FAIL_UNSPECIFIED);
1585 return preverify_ok;
1586 }
1587
1588 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
1589 "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1590 preverify_ok, err, err_str,
1591 conn->ca_cert_verify, depth, buf);
1592 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1593 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1594 "match with '%s'", buf, match);
1595 preverify_ok = 0;
1596 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1597 "Subject mismatch",
1598 TLS_FAIL_SUBJECT_MISMATCH);
1599 } else if (depth == 0 && altmatch &&
1600 !tls_match_altsubject(err_cert, altmatch)) {
1601 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1602 "'%s' not found", altmatch);
1603 preverify_ok = 0;
1604 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1605 "AltSubject mismatch",
1606 TLS_FAIL_ALTSUBJECT_MISMATCH);
01f809c7 1607 } else if (depth == 0 && suffix_match &&
cebee30f 1608 !tls_match_suffix(err_cert, suffix_match, 0)) {
01f809c7
JM
1609 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
1610 suffix_match);
1611 preverify_ok = 0;
1612 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1613 "Domain suffix mismatch",
1614 TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
cebee30f
JM
1615 } else if (depth == 0 && domain_match &&
1616 !tls_match_suffix(err_cert, domain_match, 1)) {
1617 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
1618 domain_match);
1619 preverify_ok = 0;
1620 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1621 "Domain mismatch",
1622 TLS_FAIL_DOMAIN_MISMATCH);
00468b46
JM
1623 } else
1624 openssl_tls_cert_event(conn, err_cert, depth, buf);
1625
1626 if (conn->cert_probe && preverify_ok && depth == 0) {
1627 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
1628 "on probe-only run");
1629 preverify_ok = 0;
1630 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1631 "Server certificate chain probe",
1632 TLS_FAIL_SERVER_CHAIN_PROBE);
1633 }
6fc6879b 1634
7c0e1e27
PS
1635 if (preverify_ok && context->event_cb != NULL)
1636 context->event_cb(context->cb_ctx,
1637 TLS_CERT_CHAIN_SUCCESS, NULL);
dd7fec1f 1638
6fc6879b
JM
1639 return preverify_ok;
1640}
1641
1642
1643#ifndef OPENSSL_NO_STDIO
1644static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1645{
1646 SSL_CTX *ssl_ctx = _ssl_ctx;
1647 X509_LOOKUP *lookup;
1648 int ret = 0;
1649
68ae4773 1650 lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
6fc6879b
JM
1651 X509_LOOKUP_file());
1652 if (lookup == NULL) {
1653 tls_show_errors(MSG_WARNING, __func__,
1654 "Failed add lookup for X509 store");
1655 return -1;
1656 }
1657
1658 if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1659 unsigned long err = ERR_peek_error();
1660 tls_show_errors(MSG_WARNING, __func__,
1661 "Failed load CA in DER format");
1662 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1663 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1664 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1665 "cert already in hash table error",
1666 __func__);
1667 } else
1668 ret = -1;
1669 }
1670
1671 return ret;
1672}
1673#endif /* OPENSSL_NO_STDIO */
1674
1675
1676static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1677 const char *ca_cert, const u8 *ca_cert_blob,
1678 size_t ca_cert_blob_len, const char *ca_path)
1679{
1680 SSL_CTX *ssl_ctx = _ssl_ctx;
68ae4773 1681 X509_STORE *store;
6fc6879b
JM
1682
1683 /*
1684 * Remove previously configured trusted CA certificates before adding
1685 * new ones.
1686 */
68ae4773
JM
1687 store = X509_STORE_new();
1688 if (store == NULL) {
6fc6879b
JM
1689 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1690 "certificate store", __func__);
1691 return -1;
1692 }
68ae4773 1693 SSL_CTX_set_cert_store(ssl_ctx, store);
6fc6879b 1694
00468b46
JM
1695 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1696 conn->ca_cert_verify = 1;
1697
1698 if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1699 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1700 "chain");
1701 conn->cert_probe = 1;
1702 conn->ca_cert_verify = 0;
1703 return 0;
1704 }
1705
1706 if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1707#ifdef CONFIG_SHA256
1708 const char *pos = ca_cert + 7;
1709 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1710 wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1711 "hash value '%s'", ca_cert);
1712 return -1;
1713 }
1714 pos += 14;
1715 if (os_strlen(pos) != 32 * 2) {
1716 wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1717 "hash length in ca_cert '%s'", ca_cert);
1718 return -1;
1719 }
1720 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1721 wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1722 "value in ca_cert '%s'", ca_cert);
1723 return -1;
1724 }
1725 conn->server_cert_only = 1;
1726 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1727 "certificate match");
1728 return 0;
1729#else /* CONFIG_SHA256 */
1730 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1731 "cannot validate server certificate hash");
1732 return -1;
1733#endif /* CONFIG_SHA256 */
1734 }
1735
6fc6879b 1736 if (ca_cert_blob) {
fee31f76
JM
1737 X509 *cert = d2i_X509(NULL,
1738 (const unsigned char **) &ca_cert_blob,
6fc6879b
JM
1739 ca_cert_blob_len);
1740 if (cert == NULL) {
1741 tls_show_errors(MSG_WARNING, __func__,
1742 "Failed to parse ca_cert_blob");
1743 return -1;
1744 }
1745
68ae4773
JM
1746 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
1747 cert)) {
6fc6879b
JM
1748 unsigned long err = ERR_peek_error();
1749 tls_show_errors(MSG_WARNING, __func__,
1750 "Failed to add ca_cert_blob to "
1751 "certificate store");
1752 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1753 ERR_GET_REASON(err) ==
1754 X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1755 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1756 "cert already in hash table error",
1757 __func__);
1758 } else {
1759 X509_free(cert);
1760 return -1;
1761 }
1762 }
1763 X509_free(cert);
1764 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1765 "to certificate store", __func__);
6fc6879b
JM
1766 return 0;
1767 }
1768
2a0cd067
DS
1769#ifdef ANDROID
1770 if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1771 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1772 STACK_OF(X509_INFO) *stack = NULL;
a8572960 1773 stack_index_t i;
2a0cd067
DS
1774
1775 if (bio) {
1776 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1777 BIO_free(bio);
1778 }
1779 if (!stack)
1780 return -1;
1781
1782 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1783 X509_INFO *info = sk_X509_INFO_value(stack, i);
1784 if (info->x509) {
1785 X509_STORE_add_cert(ssl_ctx->cert_store,
1786 info->x509);
1787 }
1788 if (info->crl) {
1789 X509_STORE_add_crl(ssl_ctx->cert_store,
1790 info->crl);
1791 }
1792 }
1793 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1794 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1795 return 0;
1796 }
1797#endif /* ANDROID */
1798
6fc6879b
JM
1799#ifdef CONFIG_NATIVE_WINDOWS
1800 if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1801 0) {
1802 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1803 "system certificate store");
6fc6879b
JM
1804 return 0;
1805 }
1806#endif /* CONFIG_NATIVE_WINDOWS */
1807
1808 if (ca_cert || ca_path) {
1809#ifndef OPENSSL_NO_STDIO
1810 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1811 1) {
1812 tls_show_errors(MSG_WARNING, __func__,
1813 "Failed to load root certificates");
1814 if (ca_cert &&
1815 tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1816 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1817 "DER format CA certificate",
1818 __func__);
1819 } else
1820 return -1;
1821 } else {
1822 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1823 "certificate(s) loaded");
1824 tls_get_errors(ssl_ctx);
1825 }
6fc6879b
JM
1826#else /* OPENSSL_NO_STDIO */
1827 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1828 __func__);
1829 return -1;
1830#endif /* OPENSSL_NO_STDIO */
1831 } else {
1832 /* No ca_cert configured - do not try to verify server
1833 * certificate */
00468b46 1834 conn->ca_cert_verify = 0;
6fc6879b
JM
1835 }
1836
1837 return 0;
1838}
1839
1840
1841static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1842{
1843 if (ca_cert) {
1844 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1845 {
1846 tls_show_errors(MSG_WARNING, __func__,
1847 "Failed to load root certificates");
1848 return -1;
1849 }
1850
1851 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1852 "certificate(s) loaded");
1853
1854#ifndef OPENSSL_NO_STDIO
1855 /* Add the same CAs to the client certificate requests */
1856 SSL_CTX_set_client_CA_list(ssl_ctx,
1857 SSL_load_client_CA_file(ca_cert));
1858#endif /* OPENSSL_NO_STDIO */
1859 }
1860
1861 return 0;
1862}
1863
1864
1865int tls_global_set_verify(void *ssl_ctx, int check_crl)
1866{
1867 int flags;
1868
1869 if (check_crl) {
1870 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1871 if (cs == NULL) {
1872 tls_show_errors(MSG_INFO, __func__, "Failed to get "
1873 "certificate store when enabling "
1874 "check_crl");
1875 return -1;
1876 }
1877 flags = X509_V_FLAG_CRL_CHECK;
1878 if (check_crl == 2)
1879 flags |= X509_V_FLAG_CRL_CHECK_ALL;
1880 X509_STORE_set_flags(cs, flags);
1881 }
1882 return 0;
1883}
1884
1885
1886static int tls_connection_set_subject_match(struct tls_connection *conn,
1887 const char *subject_match,
01f809c7 1888 const char *altsubject_match,
cebee30f
JM
1889 const char *suffix_match,
1890 const char *domain_match)
6fc6879b
JM
1891{
1892 os_free(conn->subject_match);
1893 conn->subject_match = NULL;
1894 if (subject_match) {
1895 conn->subject_match = os_strdup(subject_match);
1896 if (conn->subject_match == NULL)
1897 return -1;
1898 }
1899
1900 os_free(conn->altsubject_match);
1901 conn->altsubject_match = NULL;
1902 if (altsubject_match) {
1903 conn->altsubject_match = os_strdup(altsubject_match);
1904 if (conn->altsubject_match == NULL)
1905 return -1;
1906 }
1907
01f809c7
JM
1908 os_free(conn->suffix_match);
1909 conn->suffix_match = NULL;
1910 if (suffix_match) {
1911 conn->suffix_match = os_strdup(suffix_match);
1912 if (conn->suffix_match == NULL)
1913 return -1;
1914 }
1915
cebee30f
JM
1916 os_free(conn->domain_match);
1917 conn->domain_match = NULL;
1918 if (domain_match) {
1919 conn->domain_match = os_strdup(domain_match);
1920 if (conn->domain_match == NULL)
1921 return -1;
1922 }
1923
6fc6879b
JM
1924 return 0;
1925}
1926
1927
1928int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1929 int verify_peer)
1930{
bf206cad
JM
1931 static int counter = 0;
1932
6fc6879b
JM
1933 if (conn == NULL)
1934 return -1;
1935
1936 if (verify_peer) {
00468b46 1937 conn->ca_cert_verify = 1;
6fc6879b
JM
1938 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1939 SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1940 SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1941 } else {
00468b46 1942 conn->ca_cert_verify = 0;
6fc6879b
JM
1943 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1944 }
1945
1946 SSL_set_accept_state(conn->ssl);
1947
bf206cad
JM
1948 /*
1949 * Set session id context in order to avoid fatal errors when client
1950 * tries to resume a session. However, set the context to a unique
1951 * value in order to effectively disable session resumption for now
1952 * since not all areas of the server code are ready for it (e.g.,
1953 * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1954 * handshake).
1955 */
1956 counter++;
1957 SSL_set_session_id_context(conn->ssl,
1958 (const unsigned char *) &counter,
1959 sizeof(counter));
1960
6fc6879b
JM
1961 return 0;
1962}
1963
1964
1965static int tls_connection_client_cert(struct tls_connection *conn,
1966 const char *client_cert,
1967 const u8 *client_cert_blob,
1968 size_t client_cert_blob_len)
1969{
1970 if (client_cert == NULL && client_cert_blob == NULL)
1971 return 0;
1972
1973 if (client_cert_blob &&
1974 SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1975 client_cert_blob_len) == 1) {
1976 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1977 "OK");
1978 return 0;
1979 } else if (client_cert_blob) {
1980 tls_show_errors(MSG_DEBUG, __func__,
1981 "SSL_use_certificate_ASN1 failed");
1982 }
1983
1984 if (client_cert == NULL)
1985 return -1;
1986
2a0cd067
DS
1987#ifdef ANDROID
1988 if (os_strncmp("keystore://", client_cert, 11) == 0) {
1989 BIO *bio = BIO_from_keystore(&client_cert[11]);
1990 X509 *x509 = NULL;
1991 int ret = -1;
1992 if (bio) {
1993 x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
1994 BIO_free(bio);
1995 }
1996 if (x509) {
1997 if (SSL_use_certificate(conn->ssl, x509) == 1)
1998 ret = 0;
1999 X509_free(x509);
2000 }
2001 return ret;
2002 }
2003#endif /* ANDROID */
2004
6fc6879b
JM
2005#ifndef OPENSSL_NO_STDIO
2006 if (SSL_use_certificate_file(conn->ssl, client_cert,
2007 SSL_FILETYPE_ASN1) == 1) {
2008 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2009 " --> OK");
2010 return 0;
6fc6879b
JM
2011 }
2012
2013 if (SSL_use_certificate_file(conn->ssl, client_cert,
2014 SSL_FILETYPE_PEM) == 1) {
effab86f 2015 ERR_clear_error();
6fc6879b
JM
2016 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2017 " --> OK");
2018 return 0;
6fc6879b 2019 }
effab86f
JM
2020
2021 tls_show_errors(MSG_DEBUG, __func__,
2022 "SSL_use_certificate_file failed");
6fc6879b
JM
2023#else /* OPENSSL_NO_STDIO */
2024 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2025#endif /* OPENSSL_NO_STDIO */
2026
2027 return -1;
2028}
2029
2030
2031static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
2032{
2033#ifndef OPENSSL_NO_STDIO
2034 if (client_cert == NULL)
2035 return 0;
2036
2037 if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2038 SSL_FILETYPE_ASN1) != 1 &&
65897747 2039 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
6fc6879b
JM
2040 SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2041 SSL_FILETYPE_PEM) != 1) {
2042 tls_show_errors(MSG_INFO, __func__,
2043 "Failed to load client certificate");
2044 return -1;
2045 }
2046 return 0;
2047#else /* OPENSSL_NO_STDIO */
2048 if (client_cert == NULL)
2049 return 0;
2050 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2051 return -1;
2052#endif /* OPENSSL_NO_STDIO */
2053}
2054
2055
2056static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2057{
2058 if (password == NULL) {
2059 return 0;
2060 }
2061 os_strlcpy(buf, (char *) password, size);
2062 return os_strlen(buf);
2063}
2064
2065
2066#ifdef PKCS12_FUNCS
2067static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
2068 const char *passwd)
2069{
2070 EVP_PKEY *pkey;
2071 X509 *cert;
2072 STACK_OF(X509) *certs;
2073 int res = 0;
2074 char buf[256];
2075
2076 pkey = NULL;
2077 cert = NULL;
2078 certs = NULL;
2079 if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2080 tls_show_errors(MSG_DEBUG, __func__,
2081 "Failed to parse PKCS12 file");
2082 PKCS12_free(p12);
2083 return -1;
2084 }
2085 wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2086
2087 if (cert) {
2088 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2089 sizeof(buf));
2090 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2091 "subject='%s'", buf);
2092 if (ssl) {
2093 if (SSL_use_certificate(ssl, cert) != 1)
2094 res = -1;
2095 } else {
2096 if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
2097 res = -1;
2098 }
2099 X509_free(cert);
2100 }
2101
2102 if (pkey) {
2103 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2104 if (ssl) {
2105 if (SSL_use_PrivateKey(ssl, pkey) != 1)
2106 res = -1;
2107 } else {
2108 if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
2109 res = -1;
2110 }
2111 EVP_PKEY_free(pkey);
2112 }
2113
2114 if (certs) {
de2a7b79
JM
2115#if OPENSSL_VERSION_NUMBER >= 0x10002000L
2116 SSL_clear_chain_certs(ssl);
2117 while ((cert = sk_X509_pop(certs)) != NULL) {
2118 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2119 sizeof(buf));
2120 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2121 " from PKCS12: subject='%s'", buf);
2122 if (SSL_add1_chain_cert(ssl, cert) != 1) {
2123 res = -1;
2124 break;
2125 }
2126 }
2127 sk_X509_free(certs);
226cdea6 2128#ifndef OPENSSL_IS_BORINGSSL
de2a7b79
JM
2129 res = SSL_build_cert_chain(ssl,
2130 SSL_BUILD_CHAIN_FLAG_CHECK |
2131 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2132 if (!res) {
2133 tls_show_errors(MSG_DEBUG, __func__,
2134 "Failed to build certificate chain");
2135 } else if (res == 2) {
2136 wpa_printf(MSG_DEBUG,
2137 "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2138 }
226cdea6 2139#endif /* OPENSSL_IS_BORINGSSL */
de2a7b79
JM
2140 /*
2141 * Try to continue regardless of result since it is possible for
2142 * the extra certificates not to be required.
2143 */
2144 res = 0;
2145#else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
0d2c0e67
JM
2146#if OPENSSL_VERSION_NUMBER >= 0x10001000L
2147 SSL_CTX_clear_extra_chain_certs(ssl_ctx);
2148#endif /* OPENSSL_VERSION_NUMBER >= 0x10001000L */
6fc6879b
JM
2149 while ((cert = sk_X509_pop(certs)) != NULL) {
2150 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2151 sizeof(buf));
2152 wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2153 " from PKCS12: subject='%s'", buf);
2154 /*
2155 * There is no SSL equivalent for the chain cert - so
2156 * always add it to the context...
2157 */
2158 if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
2159 res = -1;
2160 break;
2161 }
2162 }
2163 sk_X509_free(certs);
de2a7b79 2164#endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
6fc6879b
JM
2165 }
2166
2167 PKCS12_free(p12);
2168
2169 if (res < 0)
2170 tls_get_errors(ssl_ctx);
2171
2172 return res;
2173}
2174#endif /* PKCS12_FUNCS */
2175
2176
2177static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
2178 const char *passwd)
2179{
2180#ifdef PKCS12_FUNCS
2181 FILE *f;
2182 PKCS12 *p12;
2183
2184 f = fopen(private_key, "rb");
2185 if (f == NULL)
2186 return -1;
2187
2188 p12 = d2i_PKCS12_fp(f, NULL);
2189 fclose(f);
2190
2191 if (p12 == NULL) {
2192 tls_show_errors(MSG_INFO, __func__,
2193 "Failed to use PKCS#12 file");
2194 return -1;
2195 }
2196
2197 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2198
2199#else /* PKCS12_FUNCS */
2200 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2201 "p12/pfx files");
2202 return -1;
2203#endif /* PKCS12_FUNCS */
2204}
2205
2206
2207static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
2208 const u8 *blob, size_t len, const char *passwd)
2209{
2210#ifdef PKCS12_FUNCS
2211 PKCS12 *p12;
2212
fee31f76 2213 p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
6fc6879b
JM
2214 if (p12 == NULL) {
2215 tls_show_errors(MSG_INFO, __func__,
2216 "Failed to use PKCS#12 blob");
2217 return -1;
2218 }
2219
2220 return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
2221
2222#else /* PKCS12_FUNCS */
2223 wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2224 "p12/pfx blobs");
2225 return -1;
2226#endif /* PKCS12_FUNCS */
2227}
2228
2229
e572cb63 2230#ifndef OPENSSL_NO_ENGINE
e59c91af
DS
2231static int tls_engine_get_cert(struct tls_connection *conn,
2232 const char *cert_id,
2233 X509 **cert)
2234{
e59c91af
DS
2235 /* this runs after the private key is loaded so no PIN is required */
2236 struct {
2237 const char *cert_id;
2238 X509 *cert;
2239 } params;
2240 params.cert_id = cert_id;
2241 params.cert = NULL;
2242
2243 if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2244 0, &params, NULL, 1)) {
fd4fb281
MG
2245 unsigned long err = ERR_get_error();
2246
e59c91af
DS
2247 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2248 " '%s' [%s]", cert_id,
fd4fb281
MG
2249 ERR_error_string(err, NULL));
2250 if (tls_is_pin_error(err))
2251 return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
e59c91af
DS
2252 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2253 }
2254 if (!params.cert) {
2255 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2256 " '%s'", cert_id);
2257 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2258 }
2259 *cert = params.cert;
2260 return 0;
e59c91af 2261}
e572cb63 2262#endif /* OPENSSL_NO_ENGINE */
e59c91af
DS
2263
2264
2265static int tls_connection_engine_client_cert(struct tls_connection *conn,
2266 const char *cert_id)
2267{
2268#ifndef OPENSSL_NO_ENGINE
2269 X509 *cert;
2270
2271 if (tls_engine_get_cert(conn, cert_id, &cert))
2272 return -1;
2273
2274 if (!SSL_use_certificate(conn->ssl, cert)) {
2275 tls_show_errors(MSG_ERROR, __func__,
2276 "SSL_use_certificate failed");
2277 X509_free(cert);
2278 return -1;
2279 }
2280 X509_free(cert);
2281 wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2282 "OK");
2283 return 0;
2284
2285#else /* OPENSSL_NO_ENGINE */
2286 return -1;
2287#endif /* OPENSSL_NO_ENGINE */
2288}
2289
2290
2291static int tls_connection_engine_ca_cert(void *_ssl_ctx,
2292 struct tls_connection *conn,
2293 const char *ca_cert_id)
2294{
2295#ifndef OPENSSL_NO_ENGINE
2296 X509 *cert;
2297 SSL_CTX *ssl_ctx = _ssl_ctx;
68ae4773 2298 X509_STORE *store;
e59c91af
DS
2299
2300 if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2301 return -1;
2302
2303 /* start off the same as tls_connection_ca_cert */
68ae4773
JM
2304 store = X509_STORE_new();
2305 if (store == NULL) {
e59c91af
DS
2306 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2307 "certificate store", __func__);
2308 X509_free(cert);
2309 return -1;
2310 }
68ae4773
JM
2311 SSL_CTX_set_cert_store(ssl_ctx, store);
2312 if (!X509_STORE_add_cert(store, cert)) {
e59c91af
DS
2313 unsigned long err = ERR_peek_error();
2314 tls_show_errors(MSG_WARNING, __func__,
2315 "Failed to add CA certificate from engine "
2316 "to certificate store");
2317 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2318 ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2319 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2320 " already in hash table error",
2321 __func__);
2322 } else {
2323 X509_free(cert);
2324 return -1;
2325 }
2326 }
2327 X509_free(cert);
2328 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2329 "to certificate store", __func__);
2330 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
d8858cad
CW
2331 conn->ca_cert_verify = 1;
2332
e59c91af
DS
2333 return 0;
2334
2335#else /* OPENSSL_NO_ENGINE */
2336 return -1;
2337#endif /* OPENSSL_NO_ENGINE */
2338}
2339
2340
6fc6879b
JM
2341static int tls_connection_engine_private_key(struct tls_connection *conn)
2342{
2343#ifndef OPENSSL_NO_ENGINE
2344 if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2345 tls_show_errors(MSG_ERROR, __func__,
2346 "ENGINE: cannot use private key for TLS");
2347 return -1;
2348 }
2349 if (!SSL_check_private_key(conn->ssl)) {
2350 tls_show_errors(MSG_INFO, __func__,
2351 "Private key failed verification");
2352 return -1;
2353 }
2354 return 0;
2355#else /* OPENSSL_NO_ENGINE */
2356 wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2357 "engine support was not compiled in");
2358 return -1;
2359#endif /* OPENSSL_NO_ENGINE */
2360}
2361
2362
2363static int tls_connection_private_key(void *_ssl_ctx,
2364 struct tls_connection *conn,
2365 const char *private_key,
2366 const char *private_key_passwd,
2367 const u8 *private_key_blob,
2368 size_t private_key_blob_len)
2369{
2370 SSL_CTX *ssl_ctx = _ssl_ctx;
2371 char *passwd;
2372 int ok;
2373
2374 if (private_key == NULL && private_key_blob == NULL)
2375 return 0;
2376
2377 if (private_key_passwd) {
2378 passwd = os_strdup(private_key_passwd);
2379 if (passwd == NULL)
2380 return -1;
2381 } else
2382 passwd = NULL;
2383
2384 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2385 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2386
2387 ok = 0;
2388 while (private_key_blob) {
2389 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2390 (u8 *) private_key_blob,
2391 private_key_blob_len) == 1) {
2392 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2393 "ASN1(EVP_PKEY_RSA) --> OK");
2394 ok = 1;
2395 break;
6fc6879b
JM
2396 }
2397
2398 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2399 (u8 *) private_key_blob,
2400 private_key_blob_len) == 1) {
2401 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2402 "ASN1(EVP_PKEY_DSA) --> OK");
2403 ok = 1;
2404 break;
6fc6879b
JM
2405 }
2406
2407 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2408 (u8 *) private_key_blob,
2409 private_key_blob_len) == 1) {
2410 wpa_printf(MSG_DEBUG, "OpenSSL: "
2411 "SSL_use_RSAPrivateKey_ASN1 --> OK");
2412 ok = 1;
2413 break;
6fc6879b
JM
2414 }
2415
2416 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
2417 private_key_blob_len, passwd) == 0) {
2418 wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2419 "OK");
2420 ok = 1;
2421 break;
2422 }
2423
2424 break;
2425 }
2426
2427 while (!ok && private_key) {
2428#ifndef OPENSSL_NO_STDIO
2429 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2430 SSL_FILETYPE_ASN1) == 1) {
2431 wpa_printf(MSG_DEBUG, "OpenSSL: "
2432 "SSL_use_PrivateKey_File (DER) --> OK");
2433 ok = 1;
2434 break;
6fc6879b
JM
2435 }
2436
2437 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2438 SSL_FILETYPE_PEM) == 1) {
2439 wpa_printf(MSG_DEBUG, "OpenSSL: "
2440 "SSL_use_PrivateKey_File (PEM) --> OK");
2441 ok = 1;
2442 break;
6fc6879b
JM
2443 }
2444#else /* OPENSSL_NO_STDIO */
2445 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2446 __func__);
2447#endif /* OPENSSL_NO_STDIO */
2448
2449 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
2450 == 0) {
2451 wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2452 "--> OK");
2453 ok = 1;
2454 break;
2455 }
2456
2457 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2458 wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2459 "access certificate store --> OK");
2460 ok = 1;
2461 break;
2462 }
2463
2464 break;
2465 }
2466
2467 if (!ok) {
effab86f
JM
2468 tls_show_errors(MSG_INFO, __func__,
2469 "Failed to load private key");
6fc6879b 2470 os_free(passwd);
6fc6879b
JM
2471 return -1;
2472 }
2473 ERR_clear_error();
2474 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2475 os_free(passwd);
55651a4b 2476
6fc6879b
JM
2477 if (!SSL_check_private_key(conn->ssl)) {
2478 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2479 "verification");
2480 return -1;
2481 }
2482
2483 wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2484 return 0;
2485}
2486
2487
2488static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
2489 const char *private_key_passwd)
2490{
2491 char *passwd;
2492
2493 if (private_key == NULL)
2494 return 0;
2495
2496 if (private_key_passwd) {
2497 passwd = os_strdup(private_key_passwd);
2498 if (passwd == NULL)
2499 return -1;
2500 } else
2501 passwd = NULL;
2502
2503 SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2504 SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2505 if (
2506#ifndef OPENSSL_NO_STDIO
2507 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2508 SSL_FILETYPE_ASN1) != 1 &&
2509 SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2510 SSL_FILETYPE_PEM) != 1 &&
2511#endif /* OPENSSL_NO_STDIO */
2512 tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
2513 tls_show_errors(MSG_INFO, __func__,
2514 "Failed to load private key");
2515 os_free(passwd);
2516 ERR_clear_error();
2517 return -1;
2518 }
2519 os_free(passwd);
2520 ERR_clear_error();
2521 SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
55651a4b 2522
6fc6879b
JM
2523 if (!SSL_CTX_check_private_key(ssl_ctx)) {
2524 tls_show_errors(MSG_INFO, __func__,
2525 "Private key failed verification");
2526 return -1;
2527 }
2528
2529 return 0;
2530}
2531
2532
2533static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2534{
2535#ifdef OPENSSL_NO_DH
2536 if (dh_file == NULL)
2537 return 0;
2538 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2539 "dh_file specified");
2540 return -1;
2541#else /* OPENSSL_NO_DH */
2542 DH *dh;
2543 BIO *bio;
2544
2545 /* TODO: add support for dh_blob */
2546 if (dh_file == NULL)
2547 return 0;
2548 if (conn == NULL)
2549 return -1;
2550
2551 bio = BIO_new_file(dh_file, "r");
2552 if (bio == NULL) {
2553 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2554 dh_file, ERR_error_string(ERR_get_error(), NULL));
2555 return -1;
2556 }
2557 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2558 BIO_free(bio);
2559#ifndef OPENSSL_NO_DSA
2560 while (dh == NULL) {
2561 DSA *dsa;
2562 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2563 " trying to parse as DSA params", dh_file,
2564 ERR_error_string(ERR_get_error(), NULL));
2565 bio = BIO_new_file(dh_file, "r");
2566 if (bio == NULL)
2567 break;
2568 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2569 BIO_free(bio);
2570 if (!dsa) {
2571 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2572 "'%s': %s", dh_file,
2573 ERR_error_string(ERR_get_error(), NULL));
2574 break;
2575 }
2576
2577 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2578 dh = DSA_dup_DH(dsa);
2579 DSA_free(dsa);
2580 if (dh == NULL) {
2581 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2582 "params into DH params");
2583 break;
2584 }
2585 break;
2586 }
2587#endif /* !OPENSSL_NO_DSA */
2588 if (dh == NULL) {
2589 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2590 "'%s'", dh_file);
2591 return -1;
2592 }
2593
2594 if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2595 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2596 "%s", dh_file,
2597 ERR_error_string(ERR_get_error(), NULL));
2598 DH_free(dh);
2599 return -1;
2600 }
2601 DH_free(dh);
2602 return 0;
2603#endif /* OPENSSL_NO_DH */
2604}
2605
2606
2607static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
2608{
2609#ifdef OPENSSL_NO_DH
2610 if (dh_file == NULL)
2611 return 0;
2612 wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2613 "dh_file specified");
2614 return -1;
2615#else /* OPENSSL_NO_DH */
2616 DH *dh;
2617 BIO *bio;
2618
2619 /* TODO: add support for dh_blob */
2620 if (dh_file == NULL)
2621 return 0;
2622 if (ssl_ctx == NULL)
2623 return -1;
2624
2625 bio = BIO_new_file(dh_file, "r");
2626 if (bio == NULL) {
2627 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2628 dh_file, ERR_error_string(ERR_get_error(), NULL));
2629 return -1;
2630 }
2631 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2632 BIO_free(bio);
2633#ifndef OPENSSL_NO_DSA
2634 while (dh == NULL) {
2635 DSA *dsa;
2636 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2637 " trying to parse as DSA params", dh_file,
2638 ERR_error_string(ERR_get_error(), NULL));
2639 bio = BIO_new_file(dh_file, "r");
2640 if (bio == NULL)
2641 break;
2642 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2643 BIO_free(bio);
2644 if (!dsa) {
2645 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2646 "'%s': %s", dh_file,
2647 ERR_error_string(ERR_get_error(), NULL));
2648 break;
2649 }
2650
2651 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2652 dh = DSA_dup_DH(dsa);
2653 DSA_free(dsa);
2654 if (dh == NULL) {
2655 wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2656 "params into DH params");
2657 break;
2658 }
2659 break;
2660 }
2661#endif /* !OPENSSL_NO_DSA */
2662 if (dh == NULL) {
2663 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2664 "'%s'", dh_file);
2665 return -1;
2666 }
2667
2668 if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2669 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2670 "%s", dh_file,
2671 ERR_error_string(ERR_get_error(), NULL));
2672 DH_free(dh);
2673 return -1;
2674 }
2675 DH_free(dh);
2676 return 0;
2677#endif /* OPENSSL_NO_DH */
2678}
2679
2680
1046db8b
JM
2681int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
2682 struct tls_random *keys)
6fc6879b
JM
2683{
2684 SSL *ssl;
2685
2686 if (conn == NULL || keys == NULL)
2687 return -1;
2688 ssl = conn->ssl;
005c5dcf 2689#if OPENSSL_VERSION_NUMBER < 0x10100000L
6fc6879b
JM
2690 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2691 return -1;
2692
2693 os_memset(keys, 0, sizeof(*keys));
6fc6879b
JM
2694 keys->client_random = ssl->s3->client_random;
2695 keys->client_random_len = SSL3_RANDOM_SIZE;
2696 keys->server_random = ssl->s3->server_random;
2697 keys->server_random_len = SSL3_RANDOM_SIZE;
005c5dcf
JM
2698#else
2699 if (ssl == NULL)
2700 return -1;
2701
2702 os_memset(keys, 0, sizeof(*keys));
2703 keys->client_random = conn->client_random;
2704 keys->client_random_len = SSL_get_client_random(
2705 ssl, conn->client_random, sizeof(conn->client_random));
2706 keys->server_random = conn->server_random;
2707 keys->server_random_len = SSL_get_server_random(
2708 ssl, conn->server_random, sizeof(conn->server_random));
2709#endif
6fc6879b
JM
2710
2711 return 0;
2712}
2713
2714
266cf4a0 2715#ifndef CONFIG_FIPS
af851914
JM
2716static int openssl_get_keyblock_size(SSL *ssl)
2717{
3de28506 2718#if OPENSSL_VERSION_NUMBER < 0x10100000L
af851914
JM
2719 const EVP_CIPHER *c;
2720 const EVP_MD *h;
2721 int md_size;
2722
2723 if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2724 ssl->read_hash == NULL)
2725 return -1;
2726
2727 c = ssl->enc_read_ctx->cipher;
2728#if OPENSSL_VERSION_NUMBER >= 0x00909000L
2729 h = EVP_MD_CTX_md(ssl->read_hash);
2730#else
92f190a0 2731 h = ssl->read_hash;
af851914
JM
2732#endif
2733 if (h)
2734 md_size = EVP_MD_size(h);
2735#if OPENSSL_VERSION_NUMBER >= 0x10000000L
2736 else if (ssl->s3)
2737 md_size = ssl->s3->tmp.new_mac_secret_size;
2738#endif
2739 else
2740 return -1;
2741
2742 wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2743 "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2744 EVP_CIPHER_iv_length(c));
2745 return 2 * (EVP_CIPHER_key_length(c) +
2746 md_size +
2747 EVP_CIPHER_iv_length(c));
3de28506
JM
2748#else
2749 const SSL_CIPHER *ssl_cipher;
2750 int cipher, digest;
2751 const EVP_CIPHER *c;
2752 const EVP_MD *h;
2753
2754 ssl_cipher = SSL_get_current_cipher(ssl);
2755 if (!ssl_cipher)
2756 return -1;
2757 cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
2758 digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
2759 wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
2760 cipher, digest);
2761 if (cipher < 0 || digest < 0)
2762 return -1;
2763 c = EVP_get_cipherbynid(cipher);
2764 h = EVP_get_digestbynid(digest);
2765 if (!c || !h)
2766 return -1;
2767
2768 wpa_printf(MSG_DEBUG,
2769 "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
2770 EVP_CIPHER_key_length(c), EVP_MD_size(h),
2771 EVP_CIPHER_iv_length(c));
2772 return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
2773 EVP_CIPHER_iv_length(c));
2774#endif
af851914 2775}
266cf4a0 2776#endif /* CONFIG_FIPS */
af851914
JM
2777
2778
fa0e7151
JM
2779static int openssl_tls_prf(void *tls_ctx, struct tls_connection *conn,
2780 const char *label, int server_random_first,
af851914 2781 int skip_keyblock, u8 *out, size_t out_len)
fa0e7151
JM
2782{
2783#ifdef CONFIG_FIPS
2784 wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2785 "mode");
2786 return -1;
2787#else /* CONFIG_FIPS */
3de28506 2788#if OPENSSL_VERSION_NUMBER < 0x10100000L
fa0e7151
JM
2789 SSL *ssl;
2790 u8 *rnd;
2791 int ret = -1;
af851914
JM
2792 int skip = 0;
2793 u8 *tmp_out = NULL;
2794 u8 *_out = out;
16bc3b89 2795 const char *ver;
fa0e7151
JM
2796
2797 /*
2798 * TLS library did not support key generation, so get the needed TLS
2799 * session parameters and use an internal implementation of TLS PRF to
2800 * derive the key.
2801 */
2802
2803 if (conn == NULL)
2804 return -1;
2805 ssl = conn->ssl;
2806 if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
cb71a834 2807 ssl->session->master_key_length <= 0)
fa0e7151 2808 return -1;
16bc3b89 2809 ver = SSL_get_version(ssl);
fa0e7151 2810
af851914
JM
2811 if (skip_keyblock) {
2812 skip = openssl_get_keyblock_size(ssl);
2813 if (skip < 0)
2814 return -1;
2815 tmp_out = os_malloc(skip + out_len);
2816 if (!tmp_out)
2817 return -1;
2818 _out = tmp_out;
2819 }
2820
fa0e7151 2821 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
144b6a06
BR
2822 if (!rnd) {
2823 os_free(tmp_out);
fa0e7151 2824 return -1;
144b6a06
BR
2825 }
2826
fa0e7151
JM
2827 if (server_random_first) {
2828 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2829 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2830 SSL3_RANDOM_SIZE);
2831 } else {
2832 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2833 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2834 SSL3_RANDOM_SIZE);
2835 }
2836
16bc3b89
JM
2837 if (os_strcmp(ver, "TLSv1.2") == 0) {
2838 tls_prf_sha256(ssl->session->master_key,
2839 ssl->session->master_key_length,
2840 label, rnd, 2 * SSL3_RANDOM_SIZE,
2841 _out, skip + out_len);
fa0e7151 2842 ret = 0;
16bc3b89
JM
2843 } else if (tls_prf_sha1_md5(ssl->session->master_key,
2844 ssl->session->master_key_length,
2845 label, rnd, 2 * SSL3_RANDOM_SIZE,
2846 _out, skip + out_len) == 0) {
2847 ret = 0;
2848 }
fa0e7151 2849 os_free(rnd);
af851914
JM
2850 if (ret == 0 && skip_keyblock)
2851 os_memcpy(out, _out + skip, out_len);
2852 bin_clear_free(tmp_out, skip);
fa0e7151
JM
2853
2854 return ret;
3de28506
JM
2855#else
2856 SSL *ssl;
2857 SSL_SESSION *sess;
2858 u8 *rnd;
2859 int ret = -1;
2860 int skip = 0;
2861 u8 *tmp_out = NULL;
2862 u8 *_out = out;
2863 unsigned char client_random[SSL3_RANDOM_SIZE];
2864 unsigned char server_random[SSL3_RANDOM_SIZE];
2865 unsigned char master_key[64];
2866 size_t master_key_len;
16bc3b89 2867 const char *ver;
3de28506
JM
2868
2869 /*
2870 * TLS library did not support key generation, so get the needed TLS
2871 * session parameters and use an internal implementation of TLS PRF to
2872 * derive the key.
2873 */
2874
2875 if (conn == NULL)
2876 return -1;
2877 ssl = conn->ssl;
2878 if (ssl == NULL)
2879 return -1;
16bc3b89 2880 ver = SSL_get_version(ssl);
3de28506 2881 sess = SSL_get_session(ssl);
16bc3b89 2882 if (!ver || !sess)
3de28506
JM
2883 return -1;
2884
2885 if (skip_keyblock) {
2886 skip = openssl_get_keyblock_size(ssl);
2887 if (skip < 0)
2888 return -1;
2889 tmp_out = os_malloc(skip + out_len);
2890 if (!tmp_out)
2891 return -1;
2892 _out = tmp_out;
2893 }
2894
2895 rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2896 if (!rnd) {
2897 os_free(tmp_out);
2898 return -1;
2899 }
2900
2901 SSL_get_client_random(ssl, client_random, sizeof(client_random));
2902 SSL_get_server_random(ssl, server_random, sizeof(server_random));
2903 master_key_len = SSL_SESSION_get_master_key(sess, master_key,
2904 sizeof(master_key));
2905
2906 if (server_random_first) {
2907 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
2908 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random,
2909 SSL3_RANDOM_SIZE);
2910 } else {
2911 os_memcpy(rnd, client_random, SSL3_RANDOM_SIZE);
2912 os_memcpy(rnd + SSL3_RANDOM_SIZE, server_random,
2913 SSL3_RANDOM_SIZE);
2914 }
2915
16bc3b89
JM
2916 if (os_strcmp(ver, "TLSv1.2") == 0) {
2917 tls_prf_sha256(master_key, master_key_len,
2918 label, rnd, 2 * SSL3_RANDOM_SIZE,
2919 _out, skip + out_len);
3de28506 2920 ret = 0;
16bc3b89
JM
2921 } else if (tls_prf_sha1_md5(master_key, master_key_len,
2922 label, rnd, 2 * SSL3_RANDOM_SIZE,
2923 _out, skip + out_len) == 0) {
2924 ret = 0;
2925 }
3de28506
JM
2926 os_memset(master_key, 0, sizeof(master_key));
2927 os_free(rnd);
2928 if (ret == 0 && skip_keyblock)
2929 os_memcpy(out, _out + skip, out_len);
2930 bin_clear_free(tmp_out, skip);
2931
2932 return ret;
2933#endif
fa0e7151
JM
2934#endif /* CONFIG_FIPS */
2935}
2936
2937
6fc6879b
JM
2938int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2939 const char *label, int server_random_first,
af851914 2940 int skip_keyblock, u8 *out, size_t out_len)
6fc6879b 2941{
68770ccd
JM
2942#if OPENSSL_VERSION_NUMBER >= 0x10001000L
2943 SSL *ssl;
2944 if (conn == NULL)
2945 return -1;
af851914 2946 if (server_random_first || skip_keyblock)
fa0e7151 2947 return openssl_tls_prf(tls_ctx, conn, label,
af851914
JM
2948 server_random_first, skip_keyblock,
2949 out, out_len);
68770ccd
JM
2950 ssl = conn->ssl;
2951 if (SSL_export_keying_material(ssl, out, out_len, label,
2952 os_strlen(label), NULL, 0, 0) == 1) {
2953 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
2954 return 0;
2955 }
2956#endif
fa0e7151 2957 return openssl_tls_prf(tls_ctx, conn, label, server_random_first,
af851914 2958 skip_keyblock, out, out_len);
6fc6879b
JM
2959}
2960
2961
81c85c06
JM
2962static struct wpabuf *
2963openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
2964 int server)
6fc6879b
JM
2965{
2966 int res;
81c85c06 2967 struct wpabuf *out_data;
6fc6879b
JM
2968
2969 /*
2970 * Give TLS handshake data from the server (if available) to OpenSSL
2971 * for processing.
2972 */
e9690eb7 2973 if (in_data && wpabuf_len(in_data) > 0 &&
81c85c06
JM
2974 BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
2975 < 0) {
6fc6879b
JM
2976 tls_show_errors(MSG_INFO, __func__,
2977 "Handshake failed - BIO_write");
2978 return NULL;
2979 }
2980
2981 /* Initiate TLS handshake or continue the existing handshake */
81c85c06
JM
2982 if (server)
2983 res = SSL_accept(conn->ssl);
2984 else
2985 res = SSL_connect(conn->ssl);
6fc6879b
JM
2986 if (res != 1) {
2987 int err = SSL_get_error(conn->ssl, res);
2988 if (err == SSL_ERROR_WANT_READ)
2989 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2990 "more data");
2991 else if (err == SSL_ERROR_WANT_WRITE)
2992 wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2993 "write");
2994 else {
2995 tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2996 conn->failed++;
2997 }
2998 }
2999
3000 /* Get the TLS handshake data to be sent to the server */
3001 res = BIO_ctrl_pending(conn->ssl_out);
3002 wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
81c85c06 3003 out_data = wpabuf_alloc(res);
6fc6879b
JM
3004 if (out_data == NULL) {
3005 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
3006 "handshake output (%d bytes)", res);
3007 if (BIO_reset(conn->ssl_out) < 0) {
3008 tls_show_errors(MSG_INFO, __func__,
3009 "BIO_reset failed");
3010 }
6fc6879b
JM
3011 return NULL;
3012 }
81c85c06
JM
3013 res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
3014 res);
6fc6879b
JM
3015 if (res < 0) {
3016 tls_show_errors(MSG_INFO, __func__,
3017 "Handshake failed - BIO_read");
3018 if (BIO_reset(conn->ssl_out) < 0) {
3019 tls_show_errors(MSG_INFO, __func__,
3020 "BIO_reset failed");
3021 }
81c85c06 3022 wpabuf_free(out_data);
6fc6879b
JM
3023 return NULL;
3024 }
81c85c06 3025 wpabuf_put(out_data, res);
6fc6879b
JM
3026
3027 return out_data;
3028}
3029
3030
81c85c06
JM
3031static struct wpabuf *
3032openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
6fc6879b 3033{
81c85c06 3034 struct wpabuf *appl_data;
6fc6879b 3035 int res;
6fc6879b 3036
81c85c06
JM
3037 appl_data = wpabuf_alloc(max_len + 100);
3038 if (appl_data == NULL)
6fc6879b 3039 return NULL;
6fc6879b 3040
81c85c06
JM
3041 res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
3042 wpabuf_size(appl_data));
3043 if (res < 0) {
bf206cad 3044 int err = SSL_get_error(conn->ssl, res);
81c85c06
JM
3045 if (err == SSL_ERROR_WANT_READ ||
3046 err == SSL_ERROR_WANT_WRITE) {
3047 wpa_printf(MSG_DEBUG, "SSL: No Application Data "
3048 "included");
3049 } else {
6fc6879b 3050 tls_show_errors(MSG_INFO, __func__,
81c85c06
JM
3051 "Failed to read possible "
3052 "Application Data");
6fc6879b 3053 }
81c85c06 3054 wpabuf_free(appl_data);
6fc6879b
JM
3055 return NULL;
3056 }
81c85c06
JM
3057
3058 wpabuf_put(appl_data, res);
3059 wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
3060 "message", appl_data);
3061
3062 return appl_data;
3063}
3064
3065
3066static struct wpabuf *
3067openssl_connection_handshake(struct tls_connection *conn,
3068 const struct wpabuf *in_data,
3069 struct wpabuf **appl_data, int server)
3070{
3071 struct wpabuf *out_data;
3072
3073 if (appl_data)
3074 *appl_data = NULL;
3075
3076 out_data = openssl_handshake(conn, in_data, server);
3077 if (out_data == NULL)
6fc6879b 3078 return NULL;
bb52293e
JM
3079 if (conn->invalid_hb_used) {
3080 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3081 wpabuf_free(out_data);
3082 return NULL;
3083 }
81c85c06 3084
a89beee5
JM
3085 if (SSL_is_init_finished(conn->ssl)) {
3086 wpa_printf(MSG_DEBUG,
3087 "OpenSSL: Handshake finished - resumed=%d",
3088 tls_connection_resumed(conn->ssl_ctx, conn));
3089 if (appl_data && in_data)
3090 *appl_data = openssl_get_appl_data(conn,
3091 wpabuf_len(in_data));
3092 }
81c85c06 3093
bb52293e
JM
3094 if (conn->invalid_hb_used) {
3095 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3096 if (appl_data) {
3097 wpabuf_free(*appl_data);
3098 *appl_data = NULL;
3099 }
3100 wpabuf_free(out_data);
3101 return NULL;
3102 }
3103
6fc6879b
JM
3104 return out_data;
3105}
3106
3107
81c85c06
JM
3108struct wpabuf *
3109tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
3110 const struct wpabuf *in_data,
3111 struct wpabuf **appl_data)
3112{
3113 return openssl_connection_handshake(conn, in_data, appl_data, 0);
3114}
3115
3116
3117struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
3118 struct tls_connection *conn,
3119 const struct wpabuf *in_data,
3120 struct wpabuf **appl_data)
3121{
3122 return openssl_connection_handshake(conn, in_data, appl_data, 1);
3123}
3124
3125
3126struct wpabuf * tls_connection_encrypt(void *tls_ctx,
3127 struct tls_connection *conn,
3128 const struct wpabuf *in_data)
6fc6879b
JM
3129{
3130 int res;
81c85c06 3131 struct wpabuf *buf;
6fc6879b
JM
3132
3133 if (conn == NULL)
81c85c06 3134 return NULL;
6fc6879b
JM
3135
3136 /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3137 if ((res = BIO_reset(conn->ssl_in)) < 0 ||
3138 (res = BIO_reset(conn->ssl_out)) < 0) {
3139 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
81c85c06 3140 return NULL;
6fc6879b 3141 }
81c85c06 3142 res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
6fc6879b
JM
3143 if (res < 0) {
3144 tls_show_errors(MSG_INFO, __func__,
3145 "Encryption failed - SSL_write");
81c85c06 3146 return NULL;
6fc6879b
JM
3147 }
3148
3149 /* Read encrypted data to be sent to the server */
81c85c06
JM
3150 buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
3151 if (buf == NULL)
3152 return NULL;
3153 res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
6fc6879b
JM
3154 if (res < 0) {
3155 tls_show_errors(MSG_INFO, __func__,
3156 "Encryption failed - BIO_read");
81c85c06
JM
3157 wpabuf_free(buf);
3158 return NULL;
6fc6879b 3159 }
81c85c06 3160 wpabuf_put(buf, res);
6fc6879b 3161
81c85c06 3162 return buf;
6fc6879b
JM
3163}
3164
3165
81c85c06
JM
3166struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3167 struct tls_connection *conn,
3168 const struct wpabuf *in_data)
6fc6879b
JM
3169{
3170 int res;
81c85c06 3171 struct wpabuf *buf;
6fc6879b
JM
3172
3173 /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
81c85c06
JM
3174 res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3175 wpabuf_len(in_data));
6fc6879b
JM
3176 if (res < 0) {
3177 tls_show_errors(MSG_INFO, __func__,
3178 "Decryption failed - BIO_write");
81c85c06 3179 return NULL;
6fc6879b
JM
3180 }
3181 if (BIO_reset(conn->ssl_out) < 0) {
3182 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
81c85c06 3183 return NULL;
6fc6879b
JM
3184 }
3185
3186 /* Read decrypted data for further processing */
81c85c06
JM
3187 /*
3188 * Even though we try to disable TLS compression, it is possible that
3189 * this cannot be done with all TLS libraries. Add extra buffer space
3190 * to handle the possibility of the decrypted data being longer than
3191 * input data.
3192 */
3193 buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3194 if (buf == NULL)
3195 return NULL;
3196 res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
6fc6879b
JM
3197 if (res < 0) {
3198 tls_show_errors(MSG_INFO, __func__,
3199 "Decryption failed - SSL_read");
a86a7316 3200 wpabuf_free(buf);
81c85c06 3201 return NULL;
6fc6879b 3202 }
81c85c06 3203 wpabuf_put(buf, res);
6fc6879b 3204
bb52293e
JM
3205 if (conn->invalid_hb_used) {
3206 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3207 wpabuf_free(buf);
3208 return NULL;
3209 }
3210
81c85c06 3211 return buf;
6fc6879b
JM
3212}
3213
3214
3215int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3216{
db3168d4
JM
3217#if OPENSSL_VERSION_NUMBER >= 0x10001000L
3218 return conn ? SSL_cache_hit(conn->ssl) : 0;
3219#else
6fc6879b 3220 return conn ? conn->ssl->hit : 0;
db3168d4 3221#endif
6fc6879b
JM
3222}
3223
3224
3225int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3226 u8 *ciphers)
3227{
3228 char buf[100], *pos, *end;
3229 u8 *c;
3230 int ret;
3231
3232 if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3233 return -1;
3234
3235 buf[0] = '\0';
3236 pos = buf;
3237 end = pos + sizeof(buf);
3238
3239 c = ciphers;
3240 while (*c != TLS_CIPHER_NONE) {
3241 const char *suite;
3242
3243 switch (*c) {
3244 case TLS_CIPHER_RC4_SHA:
3245 suite = "RC4-SHA";
3246 break;
3247 case TLS_CIPHER_AES128_SHA:
3248 suite = "AES128-SHA";
3249 break;
3250 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3251 suite = "DHE-RSA-AES128-SHA";
3252 break;
3253 case TLS_CIPHER_ANON_DH_AES128_SHA:
3254 suite = "ADH-AES128-SHA";
3255 break;
3256 default:
3257 wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3258 "cipher selection: %d", *c);
3259 return -1;
3260 }
3261 ret = os_snprintf(pos, end - pos, ":%s", suite);
d85e1fc8 3262 if (os_snprintf_error(end - pos, ret))
6fc6879b
JM
3263 break;
3264 pos += ret;
3265
3266 c++;
3267 }
3268
3269 wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3270
c34cd668
JM
3271#if OPENSSL_VERSION_NUMBER >= 0x10100000L
3272#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3273 if (os_strstr(buf, ":ADH-")) {
3274 /*
3275 * Need to drop to security level 0 to allow anonymous
3276 * cipher suites for EAP-FAST.
3277 */
3278 SSL_set_security_level(conn->ssl, 0);
3279 } else if (SSL_get_security_level(conn->ssl) == 0) {
3280 /* Force at least security level 1 */
3281 SSL_set_security_level(conn->ssl, 1);
3282 }
3283#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3284#endif
3285
6fc6879b
JM
3286 if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3287 tls_show_errors(MSG_INFO, __func__,
3288 "Cipher suite configuration failed");
3289 return -1;
3290 }
3291
3292 return 0;
3293}
3294
3295
fe1bf329
JM
3296int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
3297 char *buf, size_t buflen)
3298{
3299 const char *name;
3300 if (conn == NULL || conn->ssl == NULL)
3301 return -1;
3302
3303 name = SSL_get_version(conn->ssl);
3304 if (name == NULL)
3305 return -1;
3306
3307 os_strlcpy(buf, name, buflen);
3308 return 0;
3309}
3310
3311
6fc6879b
JM
3312int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3313 char *buf, size_t buflen)
3314{
3315 const char *name;
3316 if (conn == NULL || conn->ssl == NULL)
3317 return -1;
3318
3319 name = SSL_get_cipher(conn->ssl);
3320 if (name == NULL)
3321 return -1;
3322
3323 os_strlcpy(buf, name, buflen);
3324 return 0;
3325}
3326
3327
3328int tls_connection_enable_workaround(void *ssl_ctx,
3329 struct tls_connection *conn)
3330{
3331 SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3332
3333 return 0;
3334}
3335
3336
1e5839e0 3337#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
6fc6879b
JM
3338/* ClientHello TLS extensions require a patch to openssl, so this function is
3339 * commented out unless explicitly needed for EAP-FAST in order to be able to
3340 * build this file with unmodified openssl. */
3341int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3342 int ext_type, const u8 *data,
3343 size_t data_len)
3344{
0cf03892 3345 if (conn == NULL || conn->ssl == NULL || ext_type != 35)
6fc6879b
JM
3346 return -1;
3347
0cf03892
JM
3348 if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3349 data_len) != 1)
3350 return -1;
6fc6879b
JM
3351
3352 return 0;
3353}
1e5839e0 3354#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
6fc6879b
JM
3355
3356
3357int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3358{
3359 if (conn == NULL)
3360 return -1;
3361 return conn->failed;
3362}
3363
3364
3365int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3366{
3367 if (conn == NULL)
3368 return -1;
3369 return conn->read_alerts;
3370}
3371
3372
3373int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3374{
3375 if (conn == NULL)
3376 return -1;
3377 return conn->write_alerts;
3378}
3379
3380
080585c0
JM
3381#ifdef HAVE_OCSP
3382
3383static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3384{
3385#ifndef CONFIG_NO_STDOUT_DEBUG
080585c0
JM
3386 BIO *out;
3387 size_t rlen;
3388 char *txt;
3389 int res;
3390
3391 if (wpa_debug_level > MSG_DEBUG)
3392 return;
3393
3394 out = BIO_new(BIO_s_mem());
3395 if (!out)
3396 return;
3397
3398 OCSP_RESPONSE_print(out, rsp, 0);
3399 rlen = BIO_ctrl_pending(out);
3400 txt = os_malloc(rlen + 1);
3401 if (!txt) {
3402 BIO_free(out);
3403 return;
3404 }
3405
3406 res = BIO_read(out, txt, rlen);
3407 if (res > 0) {
3408 txt[res] = '\0';
3409 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3410 }
3411 os_free(txt);
3412 BIO_free(out);
3413#endif /* CONFIG_NO_STDOUT_DEBUG */
3414}
3415
3416
4eb3b76b
JM
3417static void debug_print_cert(X509 *cert, const char *title)
3418{
3419#ifndef CONFIG_NO_STDOUT_DEBUG
3420 BIO *out;
3421 size_t rlen;
3422 char *txt;
3423 int res;
3424
3425 if (wpa_debug_level > MSG_DEBUG)
3426 return;
3427
3428 out = BIO_new(BIO_s_mem());
3429 if (!out)
3430 return;
3431
3432 X509_print(out, cert);
3433 rlen = BIO_ctrl_pending(out);
3434 txt = os_malloc(rlen + 1);
3435 if (!txt) {
3436 BIO_free(out);
3437 return;
3438 }
3439
3440 res = BIO_read(out, txt, rlen);
3441 if (res > 0) {
3442 txt[res] = '\0';
3443 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3444 }
3445 os_free(txt);
3446
3447 BIO_free(out);
3448#endif /* CONFIG_NO_STDOUT_DEBUG */
3449}
3450
3451
080585c0
JM
3452static int ocsp_resp_cb(SSL *s, void *arg)
3453{
3454 struct tls_connection *conn = arg;
3455 const unsigned char *p;
3456 int len, status, reason;
3457 OCSP_RESPONSE *rsp;
3458 OCSP_BASICRESP *basic;
3459 OCSP_CERTID *id;
3460 ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
6bf61fb2
JM
3461 X509_STORE *store;
3462 STACK_OF(X509) *certs = NULL;
080585c0
JM
3463
3464 len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3465 if (!p) {
3466 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3467 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3468 }
3469
3470 wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3471
3472 rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3473 if (!rsp) {
3474 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3475 return 0;
3476 }
3477
3478 ocsp_debug_print_resp(rsp);
3479
3480 status = OCSP_response_status(rsp);
3481 if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3482 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3483 status, OCSP_response_status_str(status));
3484 return 0;
3485 }
3486
3487 basic = OCSP_response_get1_basic(rsp);
3488 if (!basic) {
3489 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3490 return 0;
3491 }
3492
68ae4773 3493 store = SSL_CTX_get_cert_store(conn->ssl_ctx);
6bf61fb2 3494 if (conn->peer_issuer) {
4eb3b76b 3495 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
6bf61fb2
JM
3496
3497 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3498 tls_show_errors(MSG_INFO, __func__,
58d405fc 3499 "OpenSSL: Could not add issuer to certificate store");
6bf61fb2
JM
3500 }
3501 certs = sk_X509_new_null();
3502 if (certs) {
3503 X509 *cert;
3504 cert = X509_dup(conn->peer_issuer);
3505 if (cert && !sk_X509_push(certs, cert)) {
3506 tls_show_errors(
3507 MSG_INFO, __func__,
58d405fc 3508 "OpenSSL: Could not add issuer to OCSP responder trust store");
6bf61fb2
JM
3509 X509_free(cert);
3510 sk_X509_free(certs);
3511 certs = NULL;
3512 }
710dfb4e 3513 if (certs && conn->peer_issuer_issuer) {
6bf61fb2
JM
3514 cert = X509_dup(conn->peer_issuer_issuer);
3515 if (cert && !sk_X509_push(certs, cert)) {
3516 tls_show_errors(
3517 MSG_INFO, __func__,
58d405fc 3518 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
6bf61fb2
JM
3519 X509_free(cert);
3520 }
3521 }
3522 }
3523 }
3524
3525 status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3526 sk_X509_pop_free(certs, X509_free);
080585c0
JM
3527 if (status <= 0) {
3528 tls_show_errors(MSG_INFO, __func__,
3529 "OpenSSL: OCSP response failed verification");
3530 OCSP_BASICRESP_free(basic);
3531 OCSP_RESPONSE_free(rsp);
3532 return 0;
3533 }
3534
3535 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3536
762c92a4
JM
3537 if (!conn->peer_cert) {
3538 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3539 OCSP_BASICRESP_free(basic);
3540 OCSP_RESPONSE_free(rsp);
3541 return 0;
3542 }
3543
3544 if (!conn->peer_issuer) {
3545 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
080585c0
JM
3546 OCSP_BASICRESP_free(basic);
3547 OCSP_RESPONSE_free(rsp);
3548 return 0;
3549 }
3550
3551 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3552 if (!id) {
3553 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3554 OCSP_BASICRESP_free(basic);
3555 OCSP_RESPONSE_free(rsp);
3556 return 0;
3557 }
3558
3559 if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3560 &this_update, &next_update)) {
3561 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3562 (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3563 " (OCSP not required)");
3564 OCSP_BASICRESP_free(basic);
3565 OCSP_RESPONSE_free(rsp);
3566 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3567 }
3568
3569 if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3570 tls_show_errors(MSG_INFO, __func__,
3571 "OpenSSL: OCSP status times invalid");
3572 OCSP_BASICRESP_free(basic);
3573 OCSP_RESPONSE_free(rsp);
3574 return 0;
3575 }
3576
3577 OCSP_BASICRESP_free(basic);
3578 OCSP_RESPONSE_free(rsp);
3579
3580 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3581 OCSP_cert_status_str(status));
3582
3583 if (status == V_OCSP_CERTSTATUS_GOOD)
3584 return 1;
3585 if (status == V_OCSP_CERTSTATUS_REVOKED)
3586 return 0;
3587 if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3588 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3589 return 0;
3590 }
be7963b3 3591 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
080585c0
JM
3592 return 1;
3593}
3594
3595
3596static int ocsp_status_cb(SSL *s, void *arg)
3597{
3598 char *tmp;
3599 char *resp;
3600 size_t len;
3601
3602 if (tls_global->ocsp_stapling_response == NULL) {
3603 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3604 return SSL_TLSEXT_ERR_OK;
3605 }
3606
3607 resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3608 if (resp == NULL) {
3609 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3610 /* TODO: Build OCSPResponse with responseStatus = internalError
3611 */
3612 return SSL_TLSEXT_ERR_OK;
3613 }
3614 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3615 tmp = OPENSSL_malloc(len);
3616 if (tmp == NULL) {
3617 os_free(resp);
3618 return SSL_TLSEXT_ERR_ALERT_FATAL;
3619 }
3620
3621 os_memcpy(tmp, resp, len);
3622 os_free(resp);
3623 SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3624
3625 return SSL_TLSEXT_ERR_OK;
3626}
3627
3628#endif /* HAVE_OCSP */
3629
3630
6fc6879b
JM
3631int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3632 const struct tls_connection_params *params)
3633{
3634 int ret;
3635 unsigned long err;
96955192 3636 int can_pkcs11 = 0;
01b0d1d5
DW
3637 const char *key_id = params->key_id;
3638 const char *cert_id = params->cert_id;
3639 const char *ca_cert_id = params->ca_cert_id;
96955192 3640 const char *engine_id = params->engine ? params->engine_id : NULL;
6fc6879b
JM
3641
3642 if (conn == NULL)
3643 return -1;
3644
01b0d1d5 3645 /*
96955192
DW
3646 * If the engine isn't explicitly configured, and any of the
3647 * cert/key fields are actually PKCS#11 URIs, then automatically
3648 * use the PKCS#11 ENGINE.
01b0d1d5 3649 */
96955192
DW
3650 if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3651 can_pkcs11 = 1;
3652
3653 if (!key_id && params->private_key && can_pkcs11 &&
3654 os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3655 can_pkcs11 = 2;
01b0d1d5 3656 key_id = params->private_key;
96955192 3657 }
01b0d1d5 3658
96955192
DW
3659 if (!cert_id && params->client_cert && can_pkcs11 &&
3660 os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3661 can_pkcs11 = 2;
01b0d1d5 3662 cert_id = params->client_cert;
96955192 3663 }
01b0d1d5 3664
96955192
DW
3665 if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3666 os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3667 can_pkcs11 = 2;
01b0d1d5 3668 ca_cert_id = params->ca_cert;
96955192
DW
3669 }
3670
3671 /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3672 if (can_pkcs11 == 2 && !engine_id)
3673 engine_id = "pkcs11";
01b0d1d5 3674
0f56057c 3675#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
06836013 3676#if OPENSSL_VERSION_NUMBER < 0x10100000L
6a31a31d
JM
3677 if (params->flags & TLS_CONN_EAP_FAST) {
3678 wpa_printf(MSG_DEBUG,
3679 "OpenSSL: Use TLSv1_method() for EAP-FAST");
3680 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3681 tls_show_errors(MSG_INFO, __func__,
3682 "Failed to set TLSv1_method() for EAP-FAST");
3683 return -1;
3684 }
3685 }
06836013 3686#endif
0f56057c 3687#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
d4913c58 3688
6fc6879b
JM
3689 while ((err = ERR_get_error())) {
3690 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3691 __func__, ERR_error_string(err, NULL));
3692 }
3693
96955192 3694 if (engine_id) {
e59c91af 3695 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
96955192 3696 ret = tls_engine_init(conn, engine_id, params->pin,
01b0d1d5 3697 key_id, cert_id, ca_cert_id);
e59c91af
DS
3698 if (ret)
3699 return ret;
3700 }
6fc6879b
JM
3701 if (tls_connection_set_subject_match(conn,
3702 params->subject_match,
01f809c7 3703 params->altsubject_match,
cebee30f
JM
3704 params->suffix_match,
3705 params->domain_match))
6fc6879b 3706 return -1;
e59c91af 3707
96955192 3708 if (engine_id && ca_cert_id) {
e59c91af 3709 if (tls_connection_engine_ca_cert(tls_ctx, conn,
01b0d1d5 3710 ca_cert_id))
e59c91af
DS
3711 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3712 } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
3713 params->ca_cert_blob,
3714 params->ca_cert_blob_len,
3715 params->ca_path))
6fc6879b 3716 return -1;
e59c91af 3717
96955192 3718 if (engine_id && cert_id) {
01b0d1d5 3719 if (tls_connection_engine_client_cert(conn, cert_id))
e59c91af
DS
3720 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3721 } else if (tls_connection_client_cert(conn, params->client_cert,
3722 params->client_cert_blob,
3723 params->client_cert_blob_len))
6fc6879b
JM
3724 return -1;
3725
96955192 3726 if (engine_id && key_id) {
e59c91af 3727 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
6fc6879b
JM
3728 if (tls_connection_engine_private_key(conn))
3729 return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3730 } else if (tls_connection_private_key(tls_ctx, conn,
3731 params->private_key,
3732 params->private_key_passwd,
3733 params->private_key_blob,
3734 params->private_key_blob_len)) {
3735 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3736 params->private_key);
3737 return -1;
3738 }
3739
3740 if (tls_connection_dh(conn, params->dh_file)) {
3741 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3742 params->dh_file);
3743 return -1;
3744 }
3745
b7328434
JM
3746 if (params->openssl_ciphers &&
3747 SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3748 wpa_printf(MSG_INFO,
3749 "OpenSSL: Failed to set cipher string '%s'",
3750 params->openssl_ciphers);
3751 return -1;
3752 }
3753
e866f39f
JM
3754#ifdef SSL_OP_NO_TICKET
3755 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3756 SSL_set_options(conn->ssl, SSL_OP_NO_TICKET);
d53d2596 3757#ifdef SSL_clear_options
e866f39f
JM
3758 else
3759 SSL_clear_options(conn->ssl, SSL_OP_NO_TICKET);
d53d2596 3760#endif /* SSL_clear_options */
e866f39f
JM
3761#endif /* SSL_OP_NO_TICKET */
3762
5650d379
JM
3763#ifdef SSL_OP_NO_TLSv1
3764 if (params->flags & TLS_CONN_DISABLE_TLSv1_0)
3765 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1);
3766 else
3767 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1);
3768#endif /* SSL_OP_NO_TLSv1 */
e9a6f183
DS
3769#ifdef SSL_OP_NO_TLSv1_1
3770 if (params->flags & TLS_CONN_DISABLE_TLSv1_1)
3771 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3772 else
3773 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_1);
3774#endif /* SSL_OP_NO_TLSv1_1 */
3775#ifdef SSL_OP_NO_TLSv1_2
3776 if (params->flags & TLS_CONN_DISABLE_TLSv1_2)
3777 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3778 else
3779 SSL_clear_options(conn->ssl, SSL_OP_NO_TLSv1_2);
3780#endif /* SSL_OP_NO_TLSv1_2 */
3781
080585c0
JM
3782#ifdef HAVE_OCSP
3783 if (params->flags & TLS_CONN_REQUEST_OCSP) {
81cbc046 3784 SSL_CTX *ssl_ctx = tls_ctx;
080585c0
JM
3785 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3786 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3787 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3788 }
3789#endif /* HAVE_OCSP */
3790
235279e7
JM
3791 conn->flags = params->flags;
3792
6fc6879b
JM
3793 tls_get_errors(tls_ctx);
3794
3795 return 0;
3796}
3797
3798
3799int tls_global_set_params(void *tls_ctx,
3800 const struct tls_connection_params *params)
3801{
3802 SSL_CTX *ssl_ctx = tls_ctx;
3803 unsigned long err;
3804
3805 while ((err = ERR_get_error())) {
3806 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3807 __func__, ERR_error_string(err, NULL));
3808 }
3809
f24b9797
JM
3810 if (tls_global_ca_cert(ssl_ctx, params->ca_cert) ||
3811 tls_global_client_cert(ssl_ctx, params->client_cert) ||
3812 tls_global_private_key(ssl_ctx, params->private_key,
3813 params->private_key_passwd) ||
3814 tls_global_dh(ssl_ctx, params->dh_file)) {
3815 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
6fc6879b
JM
3816 return -1;
3817 }
3818
b7328434
JM
3819 if (params->openssl_ciphers &&
3820 SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3821 wpa_printf(MSG_INFO,
3822 "OpenSSL: Failed to set cipher string '%s'",
3823 params->openssl_ciphers);
3824 return -1;
3825 }
3826
e866f39f
JM
3827#ifdef SSL_OP_NO_TICKET
3828 if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3829 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
d53d2596 3830#ifdef SSL_CTX_clear_options
e866f39f
JM
3831 else
3832 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
d53d2596 3833#endif /* SSL_clear_options */
e866f39f
JM
3834#endif /* SSL_OP_NO_TICKET */
3835
080585c0
JM
3836#ifdef HAVE_OCSP
3837 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3838 SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3839 os_free(tls_global->ocsp_stapling_response);
3840 if (params->ocsp_stapling_response)
3841 tls_global->ocsp_stapling_response =
3842 os_strdup(params->ocsp_stapling_response);
3843 else
3844 tls_global->ocsp_stapling_response = NULL;
3845#endif /* HAVE_OCSP */
3846
6fc6879b
JM
3847 return 0;
3848}
3849
3850
1e5839e0 3851#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
6fc6879b
JM
3852/* Pre-shared secred requires a patch to openssl, so this function is
3853 * commented out unless explicitly needed for EAP-FAST in order to be able to
3854 * build this file with unmodified openssl. */
3855
a8572960
AL
3856#ifdef OPENSSL_IS_BORINGSSL
3857static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3858 STACK_OF(SSL_CIPHER) *peer_ciphers,
3859 const SSL_CIPHER **cipher, void *arg)
3860#else /* OPENSSL_IS_BORINGSSL */
6fc6879b
JM
3861static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3862 STACK_OF(SSL_CIPHER) *peer_ciphers,
3863 SSL_CIPHER **cipher, void *arg)
a8572960 3864#endif /* OPENSSL_IS_BORINGSSL */
6fc6879b
JM
3865{
3866 struct tls_connection *conn = arg;
3867 int ret;
3868
4d2a1b4f 3869#if OPENSSL_VERSION_NUMBER < 0x10100000L
6fc6879b
JM
3870 if (conn == NULL || conn->session_ticket_cb == NULL)
3871 return 0;
3872
3873 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3874 conn->session_ticket,
3875 conn->session_ticket_len,
3876 s->s3->client_random,
3877 s->s3->server_random, secret);
4d2a1b4f
JM
3878#else
3879 unsigned char client_random[SSL3_RANDOM_SIZE];
3880 unsigned char server_random[SSL3_RANDOM_SIZE];
3881
3882 if (conn == NULL || conn->session_ticket_cb == NULL)
3883 return 0;
3884
3885 SSL_get_client_random(s, client_random, sizeof(client_random));
3886 SSL_get_server_random(s, server_random, sizeof(server_random));
3887
3888 ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3889 conn->session_ticket,
3890 conn->session_ticket_len,
3891 client_random,
3892 server_random, secret);
3893#endif
3894
6fc6879b
JM
3895 os_free(conn->session_ticket);
3896 conn->session_ticket = NULL;
3897
3898 if (ret <= 0)
3899 return 0;
3900
3901 *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3902 return 1;
3903}
3904
3905
0cf03892
JM
3906static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3907 int len, void *arg)
3908{
3909 struct tls_connection *conn = arg;
3910
3911 if (conn == NULL || conn->session_ticket_cb == NULL)
3912 return 0;
3913
3914 wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3915
3916 os_free(conn->session_ticket);
3917 conn->session_ticket = NULL;
3918
3919 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3920 "extension", data, len);
3921
3922 conn->session_ticket = os_malloc(len);
3923 if (conn->session_ticket == NULL)
3924 return 0;
3925
3926 os_memcpy(conn->session_ticket, data, len);
3927 conn->session_ticket_len = len;
3928
3929 return 1;
3930}
1e5839e0 3931#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
6fc6879b
JM
3932
3933
3934int tls_connection_set_session_ticket_cb(void *tls_ctx,
3935 struct tls_connection *conn,
3936 tls_session_ticket_cb cb,
3937 void *ctx)
3938{
1e5839e0 3939#if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
6fc6879b
JM
3940 conn->session_ticket_cb = cb;
3941 conn->session_ticket_cb_ctx = ctx;
3942
3943 if (cb) {
3944 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3945 conn) != 1)
3946 return -1;
0cf03892
JM
3947 SSL_set_session_ticket_ext_cb(conn->ssl,
3948 tls_session_ticket_ext_cb, conn);
6fc6879b
JM
3949 } else {
3950 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3951 return -1;
0cf03892 3952 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
6fc6879b
JM
3953 }
3954
3955 return 0;
1e5839e0 3956#else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
6fc6879b 3957 return -1;
1e5839e0 3958#endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
6fc6879b 3959}
a1651451
JM
3960
3961
3962int tls_get_library_version(char *buf, size_t buf_len)
3963{
3964 return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
3965 OPENSSL_VERSION_TEXT,
3966 SSLeay_version(SSLEAY_VERSION));
3967}