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