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