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