]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/wpa/src/crypto/tls_openssl.c
THIS BRANCH IS OBSOLETE, PLEASE READ:
[FreeBSD/FreeBSD.git] / contrib / wpa / 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(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || \
48         defined(EAP_SERVER_FAST) || defined(EAP_TEAP) || \
49         defined(EAP_SERVER_TEAP)
50 #define EAP_FAST_OR_TEAP
51 #endif
52
53
54 #if defined(OPENSSL_IS_BORINGSSL)
55 /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
56 typedef size_t stack_index_t;
57 #else
58 typedef int stack_index_t;
59 #endif
60
61 #ifdef SSL_set_tlsext_status_type
62 #ifndef OPENSSL_NO_TLSEXT
63 #define HAVE_OCSP
64 #include <openssl/ocsp.h>
65 #endif /* OPENSSL_NO_TLSEXT */
66 #endif /* SSL_set_tlsext_status_type */
67
68 #if (OPENSSL_VERSION_NUMBER < 0x10100000L || \
69      (defined(LIBRESSL_VERSION_NUMBER) && \
70       LIBRESSL_VERSION_NUMBER < 0x20700000L)) && \
71     !defined(BORINGSSL_API_VERSION)
72 /*
73  * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
74  * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
75  * older versions.
76  */
77
78 static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
79                                     size_t outlen)
80 {
81         if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
82                 return 0;
83         os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
84         return SSL3_RANDOM_SIZE;
85 }
86
87
88 static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
89                                     size_t outlen)
90 {
91         if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
92                 return 0;
93         os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
94         return SSL3_RANDOM_SIZE;
95 }
96
97
98 #ifdef OPENSSL_NEED_EAP_FAST_PRF
99 static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
100                                          unsigned char *out, size_t outlen)
101 {
102         if (!session || session->master_key_length < 0 ||
103             (size_t) session->master_key_length > outlen)
104                 return 0;
105         if ((size_t) session->master_key_length < outlen)
106                 outlen = session->master_key_length;
107         os_memcpy(out, session->master_key, outlen);
108         return outlen;
109 }
110 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
111
112 #endif
113
114 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
115         (defined(LIBRESSL_VERSION_NUMBER) && \
116          LIBRESSL_VERSION_NUMBER < 0x20700000L)
117 #ifdef CONFIG_SUITEB
118 static int RSA_bits(const RSA *r)
119 {
120         return BN_num_bits(r->n);
121 }
122 #endif /* CONFIG_SUITEB */
123
124
125 static const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
126 {
127         return ASN1_STRING_data((ASN1_STRING *) x);
128 }
129 #endif
130
131 #ifdef ANDROID
132 #include <openssl/pem.h>
133 #include <keystore/keystore_get.h>
134
135 static BIO * BIO_from_keystore(const char *key)
136 {
137         BIO *bio = NULL;
138         uint8_t *value = NULL;
139         int length = keystore_get(key, strlen(key), &value);
140         if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
141                 BIO_write(bio, value, length);
142         free(value);
143         return bio;
144 }
145
146
147 static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
148 {
149         BIO *bio = BIO_from_keystore(key_alias);
150         STACK_OF(X509_INFO) *stack = NULL;
151         stack_index_t i;
152
153         if (bio) {
154                 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
155                 BIO_free(bio);
156         }
157
158         if (!stack) {
159                 wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
160                            key_alias);
161                 return -1;
162         }
163
164         for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
165                 X509_INFO *info = sk_X509_INFO_value(stack, i);
166
167                 if (info->x509)
168                         X509_STORE_add_cert(ctx, info->x509);
169                 if (info->crl)
170                         X509_STORE_add_crl(ctx, info->crl);
171         }
172
173         sk_X509_INFO_pop_free(stack, X509_INFO_free);
174
175         return 0;
176 }
177
178
179 static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
180                                             const char *encoded_key_alias)
181 {
182         int rc = -1;
183         int len = os_strlen(encoded_key_alias);
184         unsigned char *decoded_alias;
185
186         if (len & 1) {
187                 wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
188                            encoded_key_alias);
189                 return rc;
190         }
191
192         decoded_alias = os_malloc(len / 2 + 1);
193         if (decoded_alias) {
194                 if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
195                         decoded_alias[len / 2] = '\0';
196                         rc = tls_add_ca_from_keystore(
197                                 ctx, (const char *) decoded_alias);
198                 }
199                 os_free(decoded_alias);
200         }
201
202         return rc;
203 }
204
205 #endif /* ANDROID */
206
207 static int tls_openssl_ref_count = 0;
208 static int tls_ex_idx_session = -1;
209
210 struct tls_context {
211         void (*event_cb)(void *ctx, enum tls_event ev,
212                          union tls_event_data *data);
213         void *cb_ctx;
214         int cert_in_cb;
215         char *ocsp_stapling_response;
216 };
217
218 static struct tls_context *tls_global = NULL;
219
220
221 struct tls_data {
222         SSL_CTX *ssl;
223         unsigned int tls_session_lifetime;
224         int check_crl;
225         int check_crl_strict;
226         char *ca_cert;
227         unsigned int crl_reload_interval;
228         struct os_reltime crl_last_reload;
229         char *check_cert_subject;
230 };
231
232 struct tls_connection {
233         struct tls_context *context;
234         struct tls_data *data;
235         SSL_CTX *ssl_ctx;
236         SSL *ssl;
237         BIO *ssl_in, *ssl_out;
238 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
239         ENGINE *engine;        /* functional reference to the engine */
240         EVP_PKEY *private_key; /* the private key if using engine */
241 #endif /* OPENSSL_NO_ENGINE */
242         char *subject_match, *altsubject_match, *suffix_match, *domain_match;
243         char *check_cert_subject;
244         int read_alerts, write_alerts, failed;
245
246         tls_session_ticket_cb session_ticket_cb;
247         void *session_ticket_cb_ctx;
248
249         /* SessionTicket received from OpenSSL hello_extension_cb (server) */
250         u8 *session_ticket;
251         size_t session_ticket_len;
252
253         unsigned int ca_cert_verify:1;
254         unsigned int cert_probe:1;
255         unsigned int server_cert_only:1;
256         unsigned int invalid_hb_used:1;
257         unsigned int success_data:1;
258         unsigned int client_hello_generated:1;
259         unsigned int server:1;
260
261         u8 srv_cert_hash[32];
262
263         unsigned int flags;
264
265         X509 *peer_cert;
266         X509 *peer_issuer;
267         X509 *peer_issuer_issuer;
268
269         unsigned char client_random[SSL3_RANDOM_SIZE];
270         unsigned char server_random[SSL3_RANDOM_SIZE];
271
272         u16 cipher_suite;
273         int server_dh_prime_len;
274 };
275
276
277 static struct tls_context * tls_context_new(const struct tls_config *conf)
278 {
279         struct tls_context *context = os_zalloc(sizeof(*context));
280         if (context == NULL)
281                 return NULL;
282         if (conf) {
283                 context->event_cb = conf->event_cb;
284                 context->cb_ctx = conf->cb_ctx;
285                 context->cert_in_cb = conf->cert_in_cb;
286         }
287         return context;
288 }
289
290
291 #ifdef CONFIG_NO_STDOUT_DEBUG
292
293 static void _tls_show_errors(void)
294 {
295         unsigned long err;
296
297         while ((err = ERR_get_error())) {
298                 /* Just ignore the errors, since stdout is disabled */
299         }
300 }
301 #define tls_show_errors(l, f, t) _tls_show_errors()
302
303 #else /* CONFIG_NO_STDOUT_DEBUG */
304
305 static void tls_show_errors(int level, const char *func, const char *txt)
306 {
307         unsigned long err;
308
309         wpa_printf(level, "OpenSSL: %s - %s %s",
310                    func, txt, ERR_error_string(ERR_get_error(), NULL));
311
312         while ((err = ERR_get_error())) {
313                 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
314                            ERR_error_string(err, NULL));
315         }
316 }
317
318 #endif /* CONFIG_NO_STDOUT_DEBUG */
319
320
321 static X509_STORE * tls_crl_cert_reload(const char *ca_cert, int check_crl)
322 {
323         int flags;
324         X509_STORE *store;
325
326         store = X509_STORE_new();
327         if (!store) {
328                 wpa_printf(MSG_DEBUG,
329                            "OpenSSL: %s - failed to allocate new certificate store",
330                            __func__);
331                 return NULL;
332         }
333
334         if (ca_cert && X509_STORE_load_locations(store, ca_cert, NULL) != 1) {
335                 tls_show_errors(MSG_WARNING, __func__,
336                                 "Failed to load root certificates");
337                 X509_STORE_free(store);
338                 return NULL;
339         }
340
341         flags = check_crl ? X509_V_FLAG_CRL_CHECK : 0;
342         if (check_crl == 2)
343                 flags |= X509_V_FLAG_CRL_CHECK_ALL;
344
345         X509_STORE_set_flags(store, flags);
346
347         return store;
348 }
349
350
351 #ifdef CONFIG_NATIVE_WINDOWS
352
353 /* Windows CryptoAPI and access to certificate stores */
354 #include <wincrypt.h>
355
356 #ifdef __MINGW32_VERSION
357 /*
358  * MinGW does not yet include all the needed definitions for CryptoAPI, so
359  * define here whatever extra is needed.
360  */
361 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
362 #define CERT_STORE_READONLY_FLAG 0x00008000
363 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
364
365 #endif /* __MINGW32_VERSION */
366
367
368 struct cryptoapi_rsa_data {
369         const CERT_CONTEXT *cert;
370         HCRYPTPROV crypt_prov;
371         DWORD key_spec;
372         BOOL free_crypt_prov;
373 };
374
375
376 static void cryptoapi_error(const char *msg)
377 {
378         wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
379                    msg, (unsigned int) GetLastError());
380 }
381
382
383 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
384                                  unsigned char *to, RSA *rsa, int padding)
385 {
386         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
387         return 0;
388 }
389
390
391 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
392                                  unsigned char *to, RSA *rsa, int padding)
393 {
394         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
395         return 0;
396 }
397
398
399 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
400                                   unsigned char *to, RSA *rsa, int padding)
401 {
402         struct cryptoapi_rsa_data *priv =
403                 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
404         HCRYPTHASH hash;
405         DWORD hash_size, len, i;
406         unsigned char *buf = NULL;
407         int ret = 0;
408
409         if (priv == NULL) {
410                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
411                        ERR_R_PASSED_NULL_PARAMETER);
412                 return 0;
413         }
414
415         if (padding != RSA_PKCS1_PADDING) {
416                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
417                        RSA_R_UNKNOWN_PADDING_TYPE);
418                 return 0;
419         }
420
421         if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
422                 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
423                            __func__);
424                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
425                        RSA_R_INVALID_MESSAGE_LENGTH);
426                 return 0;
427         }
428
429         if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
430         {
431                 cryptoapi_error("CryptCreateHash failed");
432                 return 0;
433         }
434
435         len = sizeof(hash_size);
436         if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
437                                0)) {
438                 cryptoapi_error("CryptGetHashParam failed");
439                 goto err;
440         }
441
442         if ((int) hash_size != flen) {
443                 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
444                            (unsigned) hash_size, flen);
445                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
446                        RSA_R_INVALID_MESSAGE_LENGTH);
447                 goto err;
448         }
449         if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
450                 cryptoapi_error("CryptSetHashParam failed");
451                 goto err;
452         }
453
454         len = RSA_size(rsa);
455         buf = os_malloc(len);
456         if (buf == NULL) {
457                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
458                 goto err;
459         }
460
461         if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
462                 cryptoapi_error("CryptSignHash failed");
463                 goto err;
464         }
465
466         for (i = 0; i < len; i++)
467                 to[i] = buf[len - i - 1];
468         ret = len;
469
470 err:
471         os_free(buf);
472         CryptDestroyHash(hash);
473
474         return ret;
475 }
476
477
478 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
479                                   unsigned char *to, RSA *rsa, int padding)
480 {
481         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
482         return 0;
483 }
484
485
486 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
487 {
488         if (priv == NULL)
489                 return;
490         if (priv->crypt_prov && priv->free_crypt_prov)
491                 CryptReleaseContext(priv->crypt_prov, 0);
492         if (priv->cert)
493                 CertFreeCertificateContext(priv->cert);
494         os_free(priv);
495 }
496
497
498 static int cryptoapi_finish(RSA *rsa)
499 {
500         cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
501         os_free((void *) rsa->meth);
502         rsa->meth = NULL;
503         return 1;
504 }
505
506
507 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
508 {
509         HCERTSTORE cs;
510         const CERT_CONTEXT *ret = NULL;
511
512         cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
513                            store | CERT_STORE_OPEN_EXISTING_FLAG |
514                            CERT_STORE_READONLY_FLAG, L"MY");
515         if (cs == NULL) {
516                 cryptoapi_error("Failed to open 'My system store'");
517                 return NULL;
518         }
519
520         if (strncmp(name, "cert://", 7) == 0) {
521                 unsigned short wbuf[255];
522                 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
523                 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
524                                                  PKCS_7_ASN_ENCODING,
525                                                  0, CERT_FIND_SUBJECT_STR,
526                                                  wbuf, NULL);
527         } else if (strncmp(name, "hash://", 7) == 0) {
528                 CRYPT_HASH_BLOB blob;
529                 int len;
530                 const char *hash = name + 7;
531                 unsigned char *buf;
532
533                 len = os_strlen(hash) / 2;
534                 buf = os_malloc(len);
535                 if (buf && hexstr2bin(hash, buf, len) == 0) {
536                         blob.cbData = len;
537                         blob.pbData = buf;
538                         ret = CertFindCertificateInStore(cs,
539                                                          X509_ASN_ENCODING |
540                                                          PKCS_7_ASN_ENCODING,
541                                                          0, CERT_FIND_HASH,
542                                                          &blob, NULL);
543                 }
544                 os_free(buf);
545         }
546
547         CertCloseStore(cs, 0);
548
549         return ret;
550 }
551
552
553 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
554 {
555         X509 *cert = NULL;
556         RSA *rsa = NULL, *pub_rsa;
557         struct cryptoapi_rsa_data *priv;
558         RSA_METHOD *rsa_meth;
559
560         if (name == NULL ||
561             (strncmp(name, "cert://", 7) != 0 &&
562              strncmp(name, "hash://", 7) != 0))
563                 return -1;
564
565         priv = os_zalloc(sizeof(*priv));
566         rsa_meth = os_zalloc(sizeof(*rsa_meth));
567         if (priv == NULL || rsa_meth == NULL) {
568                 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
569                            "for CryptoAPI RSA method");
570                 os_free(priv);
571                 os_free(rsa_meth);
572                 return -1;
573         }
574
575         priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
576         if (priv->cert == NULL) {
577                 priv->cert = cryptoapi_find_cert(
578                         name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
579         }
580         if (priv->cert == NULL) {
581                 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
582                            "'%s'", name);
583                 goto err;
584         }
585
586         cert = d2i_X509(NULL,
587                         (const unsigned char **) &priv->cert->pbCertEncoded,
588                         priv->cert->cbCertEncoded);
589         if (cert == NULL) {
590                 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
591                            "encoding");
592                 goto err;
593         }
594
595         if (!CryptAcquireCertificatePrivateKey(priv->cert,
596                                                CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
597                                                NULL, &priv->crypt_prov,
598                                                &priv->key_spec,
599                                                &priv->free_crypt_prov)) {
600                 cryptoapi_error("Failed to acquire a private key for the "
601                                 "certificate");
602                 goto err;
603         }
604
605         rsa_meth->name = "Microsoft CryptoAPI RSA Method";
606         rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
607         rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
608         rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
609         rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
610         rsa_meth->finish = cryptoapi_finish;
611         rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
612         rsa_meth->app_data = (char *) priv;
613
614         rsa = RSA_new();
615         if (rsa == NULL) {
616                 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
617                        ERR_R_MALLOC_FAILURE);
618                 goto err;
619         }
620
621         if (!SSL_use_certificate(ssl, cert)) {
622                 RSA_free(rsa);
623                 rsa = NULL;
624                 goto err;
625         }
626         pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
627         X509_free(cert);
628         cert = NULL;
629
630         rsa->n = BN_dup(pub_rsa->n);
631         rsa->e = BN_dup(pub_rsa->e);
632         if (!RSA_set_method(rsa, rsa_meth))
633                 goto err;
634
635         if (!SSL_use_RSAPrivateKey(ssl, rsa))
636                 goto err;
637         RSA_free(rsa);
638
639         return 0;
640
641 err:
642         if (cert)
643                 X509_free(cert);
644         if (rsa)
645                 RSA_free(rsa);
646         else {
647                 os_free(rsa_meth);
648                 cryptoapi_free_data(priv);
649         }
650         return -1;
651 }
652
653
654 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
655 {
656         HCERTSTORE cs;
657         PCCERT_CONTEXT ctx = NULL;
658         X509 *cert;
659         char buf[128];
660         const char *store;
661 #ifdef UNICODE
662         WCHAR *wstore;
663 #endif /* UNICODE */
664
665         if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
666                 return -1;
667
668         store = name + 13;
669 #ifdef UNICODE
670         wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
671         if (wstore == NULL)
672                 return -1;
673         wsprintf(wstore, L"%S", store);
674         cs = CertOpenSystemStore(0, wstore);
675         os_free(wstore);
676 #else /* UNICODE */
677         cs = CertOpenSystemStore(0, store);
678 #endif /* UNICODE */
679         if (cs == NULL) {
680                 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
681                            "'%s': error=%d", __func__, store,
682                            (int) GetLastError());
683                 return -1;
684         }
685
686         while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
687                 cert = d2i_X509(NULL,
688                                 (const unsigned char **) &ctx->pbCertEncoded,
689                                 ctx->cbCertEncoded);
690                 if (cert == NULL) {
691                         wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
692                                    "X509 DER encoding for CA cert");
693                         continue;
694                 }
695
696                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
697                                   sizeof(buf));
698                 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
699                            "system certificate store: subject='%s'", buf);
700
701                 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
702                                          cert)) {
703                         tls_show_errors(MSG_WARNING, __func__,
704                                         "Failed to add ca_cert to OpenSSL "
705                                         "certificate store");
706                 }
707
708                 X509_free(cert);
709         }
710
711         if (!CertCloseStore(cs, 0)) {
712                 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
713                            "'%s': error=%d", __func__, name + 13,
714                            (int) GetLastError());
715         }
716
717         return 0;
718 }
719
720
721 #else /* CONFIG_NATIVE_WINDOWS */
722
723 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
724 {
725         return -1;
726 }
727
728 #endif /* CONFIG_NATIVE_WINDOWS */
729
730
731 static void ssl_info_cb(const SSL *ssl, int where, int ret)
732 {
733         const char *str;
734         int w;
735
736         wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
737         w = where & ~SSL_ST_MASK;
738         if (w & SSL_ST_CONNECT)
739                 str = "SSL_connect";
740         else if (w & SSL_ST_ACCEPT)
741                 str = "SSL_accept";
742         else
743                 str = "undefined";
744
745         if (where & SSL_CB_LOOP) {
746                 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
747                            str, SSL_state_string_long(ssl));
748         } else if (where & SSL_CB_ALERT) {
749                 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
750                 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
751                            where & SSL_CB_READ ?
752                            "read (remote end reported an error)" :
753                            "write (local SSL3 detected an error)",
754                            SSL_alert_type_string_long(ret),
755                            SSL_alert_desc_string_long(ret));
756                 if ((ret >> 8) == SSL3_AL_FATAL) {
757                         if (where & SSL_CB_READ)
758                                 conn->read_alerts++;
759                         else
760                                 conn->write_alerts++;
761                 }
762                 if (conn->context->event_cb != NULL) {
763                         union tls_event_data ev;
764                         struct tls_context *context = conn->context;
765                         os_memset(&ev, 0, sizeof(ev));
766                         ev.alert.is_local = !(where & SSL_CB_READ);
767                         ev.alert.type = SSL_alert_type_string_long(ret);
768                         ev.alert.description = SSL_alert_desc_string_long(ret);
769                         context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
770                 }
771         } else if (where & SSL_CB_EXIT && ret <= 0) {
772                 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
773                            str, ret == 0 ? "failed" : "error",
774                            SSL_state_string_long(ssl));
775         }
776 }
777
778
779 #ifndef OPENSSL_NO_ENGINE
780 /**
781  * tls_engine_load_dynamic_generic - load any openssl engine
782  * @pre: an array of commands and values that load an engine initialized
783  *       in the engine specific function
784  * @post: an array of commands and values that initialize an already loaded
785  *        engine (or %NULL if not required)
786  * @id: the engine id of the engine to load (only required if post is not %NULL
787  *
788  * This function is a generic function that loads any openssl engine.
789  *
790  * Returns: 0 on success, -1 on failure
791  */
792 static int tls_engine_load_dynamic_generic(const char *pre[],
793                                            const char *post[], const char *id)
794 {
795         ENGINE *engine;
796         const char *dynamic_id = "dynamic";
797
798         engine = ENGINE_by_id(id);
799         if (engine) {
800                 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
801                            "available", id);
802                 /*
803                  * If it was auto-loaded by ENGINE_by_id() we might still
804                  * need to tell it which PKCS#11 module to use in legacy
805                  * (non-p11-kit) environments. Do so now; even if it was
806                  * properly initialised before, setting it again will be
807                  * harmless.
808                  */
809                 goto found;
810         }
811         ERR_clear_error();
812
813         engine = ENGINE_by_id(dynamic_id);
814         if (engine == NULL) {
815                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
816                            dynamic_id,
817                            ERR_error_string(ERR_get_error(), NULL));
818                 return -1;
819         }
820
821         /* Perform the pre commands. This will load the engine. */
822         while (pre && pre[0]) {
823                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
824                 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
825                         wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
826                                    "%s %s [%s]", pre[0], pre[1],
827                                    ERR_error_string(ERR_get_error(), NULL));
828                         ENGINE_free(engine);
829                         return -1;
830                 }
831                 pre += 2;
832         }
833
834         /*
835          * Free the reference to the "dynamic" engine. The loaded engine can
836          * now be looked up using ENGINE_by_id().
837          */
838         ENGINE_free(engine);
839
840         engine = ENGINE_by_id(id);
841         if (engine == NULL) {
842                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
843                            id, ERR_error_string(ERR_get_error(), NULL));
844                 return -1;
845         }
846  found:
847         while (post && post[0]) {
848                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
849                 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
850                         wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
851                                 " %s %s [%s]", post[0], post[1],
852                                    ERR_error_string(ERR_get_error(), NULL));
853                         ENGINE_remove(engine);
854                         ENGINE_free(engine);
855                         return -1;
856                 }
857                 post += 2;
858         }
859         ENGINE_free(engine);
860
861         return 0;
862 }
863
864
865 /**
866  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
867  * @pkcs11_so_path: pksc11_so_path from the configuration
868  * @pcks11_module_path: pkcs11_module_path from the configuration
869  */
870 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
871                                           const char *pkcs11_module_path)
872 {
873         char *engine_id = "pkcs11";
874         const char *pre_cmd[] = {
875                 "SO_PATH", NULL /* pkcs11_so_path */,
876                 "ID", NULL /* engine_id */,
877                 "LIST_ADD", "1",
878                 /* "NO_VCHECK", "1", */
879                 "LOAD", NULL,
880                 NULL, NULL
881         };
882         const char *post_cmd[] = {
883                 "MODULE_PATH", NULL /* pkcs11_module_path */,
884                 NULL, NULL
885         };
886
887         if (!pkcs11_so_path)
888                 return 0;
889
890         pre_cmd[1] = pkcs11_so_path;
891         pre_cmd[3] = engine_id;
892         if (pkcs11_module_path)
893                 post_cmd[1] = pkcs11_module_path;
894         else
895                 post_cmd[0] = NULL;
896
897         wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
898                    pkcs11_so_path);
899
900         return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
901 }
902
903
904 /**
905  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
906  * @opensc_so_path: opensc_so_path from the configuration
907  */
908 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
909 {
910         char *engine_id = "opensc";
911         const char *pre_cmd[] = {
912                 "SO_PATH", NULL /* opensc_so_path */,
913                 "ID", NULL /* engine_id */,
914                 "LIST_ADD", "1",
915                 "LOAD", NULL,
916                 NULL, NULL
917         };
918
919         if (!opensc_so_path)
920                 return 0;
921
922         pre_cmd[1] = opensc_so_path;
923         pre_cmd[3] = engine_id;
924
925         wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
926                    opensc_so_path);
927
928         return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
929 }
930 #endif /* OPENSSL_NO_ENGINE */
931
932
933 static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
934 {
935         struct wpabuf *buf;
936
937         if (tls_ex_idx_session < 0)
938                 return;
939         buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
940         if (!buf)
941                 return;
942         wpa_printf(MSG_DEBUG,
943                    "OpenSSL: Free application session data %p (sess %p)",
944                    buf, sess);
945         wpabuf_free(buf);
946
947         SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
948 }
949
950
951 void * tls_init(const struct tls_config *conf)
952 {
953         struct tls_data *data;
954         SSL_CTX *ssl;
955         struct tls_context *context;
956         const char *ciphers;
957
958         if (tls_openssl_ref_count == 0) {
959                 tls_global = context = tls_context_new(conf);
960                 if (context == NULL)
961                         return NULL;
962 #ifdef CONFIG_FIPS
963 #ifdef OPENSSL_FIPS
964                 if (conf && conf->fips_mode) {
965                         static int fips_enabled = 0;
966
967                         if (!fips_enabled && !FIPS_mode_set(1)) {
968                                 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
969                                            "mode");
970                                 ERR_load_crypto_strings();
971                                 ERR_print_errors_fp(stderr);
972                                 os_free(tls_global);
973                                 tls_global = NULL;
974                                 return NULL;
975                         } else {
976                                 wpa_printf(MSG_INFO, "Running in FIPS mode");
977                                 fips_enabled = 1;
978                         }
979                 }
980 #else /* OPENSSL_FIPS */
981                 if (conf && conf->fips_mode) {
982                         wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
983                                    "supported");
984                         os_free(tls_global);
985                         tls_global = NULL;
986                         return NULL;
987                 }
988 #endif /* OPENSSL_FIPS */
989 #endif /* CONFIG_FIPS */
990 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
991         (defined(LIBRESSL_VERSION_NUMBER) && \
992          LIBRESSL_VERSION_NUMBER < 0x20700000L)
993                 SSL_load_error_strings();
994                 SSL_library_init();
995 #ifndef OPENSSL_NO_SHA256
996                 EVP_add_digest(EVP_sha256());
997 #endif /* OPENSSL_NO_SHA256 */
998                 /* TODO: if /dev/urandom is available, PRNG is seeded
999                  * automatically. If this is not the case, random data should
1000                  * be added here. */
1001
1002 #ifdef PKCS12_FUNCS
1003 #ifndef OPENSSL_NO_RC2
1004                 /*
1005                  * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
1006                  * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
1007                  * versions, but it looks like OpenSSL 1.0.0 does not do that
1008                  * anymore.
1009                  */
1010                 EVP_add_cipher(EVP_rc2_40_cbc());
1011 #endif /* OPENSSL_NO_RC2 */
1012                 PKCS12_PBE_add();
1013 #endif  /* PKCS12_FUNCS */
1014 #endif /* < 1.1.0 */
1015         } else {
1016                 context = tls_context_new(conf);
1017                 if (context == NULL)
1018                         return NULL;
1019         }
1020         tls_openssl_ref_count++;
1021
1022         data = os_zalloc(sizeof(*data));
1023         if (data)
1024                 ssl = SSL_CTX_new(SSLv23_method());
1025         else
1026                 ssl = NULL;
1027         if (ssl == NULL) {
1028                 tls_openssl_ref_count--;
1029                 if (context != tls_global)
1030                         os_free(context);
1031                 if (tls_openssl_ref_count == 0) {
1032                         os_free(tls_global);
1033                         tls_global = NULL;
1034                 }
1035                 os_free(data);
1036                 return NULL;
1037         }
1038         data->ssl = ssl;
1039         if (conf) {
1040                 data->tls_session_lifetime = conf->tls_session_lifetime;
1041                 data->crl_reload_interval = conf->crl_reload_interval;
1042         }
1043
1044         SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
1045         SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
1046
1047 #ifdef SSL_MODE_NO_AUTO_CHAIN
1048         /* Number of deployed use cases assume the default OpenSSL behavior of
1049          * auto chaining the local certificate is in use. BoringSSL removed this
1050          * functionality by default, so we need to restore it here to avoid
1051          * breaking existing use cases. */
1052         SSL_CTX_clear_mode(ssl, SSL_MODE_NO_AUTO_CHAIN);
1053 #endif /* SSL_MODE_NO_AUTO_CHAIN */
1054
1055         SSL_CTX_set_info_callback(ssl, ssl_info_cb);
1056         SSL_CTX_set_app_data(ssl, context);
1057         if (data->tls_session_lifetime > 0) {
1058                 SSL_CTX_set_quiet_shutdown(ssl, 1);
1059                 /*
1060                  * Set default context here. In practice, this will be replaced
1061                  * by the per-EAP method context in tls_connection_set_verify().
1062                  */
1063                 SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
1064                 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
1065                 SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
1066                 SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
1067         } else {
1068                 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
1069         }
1070
1071         if (tls_ex_idx_session < 0) {
1072                 tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
1073                         0, NULL, NULL, NULL, NULL);
1074                 if (tls_ex_idx_session < 0) {
1075                         tls_deinit(data);
1076                         return NULL;
1077                 }
1078         }
1079
1080 #ifndef OPENSSL_NO_ENGINE
1081         wpa_printf(MSG_DEBUG, "ENGINE: Loading builtin engines");
1082         ENGINE_load_builtin_engines();
1083
1084         if (conf &&
1085             (conf->opensc_engine_path || conf->pkcs11_engine_path ||
1086              conf->pkcs11_module_path)) {
1087                 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
1088                     tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
1089                                                    conf->pkcs11_module_path)) {
1090                         tls_deinit(data);
1091                         return NULL;
1092                 }
1093         }
1094 #endif /* OPENSSL_NO_ENGINE */
1095
1096         if (conf && conf->openssl_ciphers)
1097                 ciphers = conf->openssl_ciphers;
1098         else
1099                 ciphers = TLS_DEFAULT_CIPHERS;
1100         if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
1101                 wpa_printf(MSG_ERROR,
1102                            "OpenSSL: Failed to set cipher string '%s'",
1103                            ciphers);
1104                 tls_deinit(data);
1105                 return NULL;
1106         }
1107
1108         return data;
1109 }
1110
1111
1112 void tls_deinit(void *ssl_ctx)
1113 {
1114         struct tls_data *data = ssl_ctx;
1115         SSL_CTX *ssl = data->ssl;
1116         struct tls_context *context = SSL_CTX_get_app_data(ssl);
1117         if (context != tls_global)
1118                 os_free(context);
1119         if (data->tls_session_lifetime > 0)
1120                 SSL_CTX_flush_sessions(ssl, 0);
1121         os_free(data->ca_cert);
1122         SSL_CTX_free(ssl);
1123
1124         tls_openssl_ref_count--;
1125         if (tls_openssl_ref_count == 0) {
1126 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
1127         (defined(LIBRESSL_VERSION_NUMBER) && \
1128          LIBRESSL_VERSION_NUMBER < 0x20700000L)
1129 #ifndef OPENSSL_NO_ENGINE
1130                 ENGINE_cleanup();
1131 #endif /* OPENSSL_NO_ENGINE */
1132                 CRYPTO_cleanup_all_ex_data();
1133                 ERR_remove_thread_state(NULL);
1134                 ERR_free_strings();
1135                 EVP_cleanup();
1136 #endif /* < 1.1.0 */
1137                 os_free(tls_global->ocsp_stapling_response);
1138                 tls_global->ocsp_stapling_response = NULL;
1139                 os_free(tls_global);
1140                 tls_global = NULL;
1141         }
1142
1143         os_free(data->check_cert_subject);
1144         os_free(data);
1145 }
1146
1147
1148 #ifndef OPENSSL_NO_ENGINE
1149
1150 /* Cryptoki return values */
1151 #define CKR_PIN_INCORRECT 0x000000a0
1152 #define CKR_PIN_INVALID 0x000000a1
1153 #define CKR_PIN_LEN_RANGE 0x000000a2
1154
1155 /* libp11 */
1156 #define ERR_LIB_PKCS11  ERR_LIB_USER
1157
1158 static int tls_is_pin_error(unsigned int err)
1159 {
1160         return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
1161                 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
1162                  ERR_GET_REASON(err) == CKR_PIN_INVALID ||
1163                  ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
1164 }
1165
1166 #endif /* OPENSSL_NO_ENGINE */
1167
1168
1169 #ifdef ANDROID
1170 /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
1171 EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
1172 #endif /* ANDROID */
1173
1174 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
1175                            const char *pin, const char *key_id,
1176                            const char *cert_id, const char *ca_cert_id)
1177 {
1178 #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
1179 #if !defined(OPENSSL_NO_ENGINE)
1180 #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
1181 #endif
1182         if (!key_id)
1183                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1184         conn->engine = NULL;
1185         conn->private_key = EVP_PKEY_from_keystore(key_id);
1186         if (!conn->private_key) {
1187                 wpa_printf(MSG_ERROR,
1188                            "ENGINE: cannot load private key with id '%s' [%s]",
1189                            key_id,
1190                            ERR_error_string(ERR_get_error(), NULL));
1191                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1192         }
1193 #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
1194
1195 #ifndef OPENSSL_NO_ENGINE
1196         int ret = -1;
1197         if (engine_id == NULL) {
1198                 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
1199                 return -1;
1200         }
1201
1202         ERR_clear_error();
1203 #ifdef ANDROID
1204         ENGINE_load_dynamic();
1205 #endif
1206         conn->engine = ENGINE_by_id(engine_id);
1207         if (!conn->engine) {
1208                 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
1209                            engine_id, ERR_error_string(ERR_get_error(), NULL));
1210                 goto err;
1211         }
1212         if (ENGINE_init(conn->engine) != 1) {
1213                 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
1214                            "(engine: %s) [%s]", engine_id,
1215                            ERR_error_string(ERR_get_error(), NULL));
1216                 goto err;
1217         }
1218         wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
1219
1220 #ifndef ANDROID
1221         if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
1222                 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
1223                            ERR_error_string(ERR_get_error(), NULL));
1224                 goto err;
1225         }
1226 #endif
1227         if (key_id) {
1228                 /*
1229                  * Ensure that the ENGINE does not attempt to use the OpenSSL
1230                  * UI system to obtain a PIN, if we didn't provide one.
1231                  */
1232                 struct {
1233                         const void *password;
1234                         const char *prompt_info;
1235                 } key_cb = { "", NULL };
1236
1237                 /* load private key first in-case PIN is required for cert */
1238                 conn->private_key = ENGINE_load_private_key(conn->engine,
1239                                                             key_id, NULL,
1240                                                             &key_cb);
1241                 if (!conn->private_key) {
1242                         unsigned long err = ERR_get_error();
1243
1244                         wpa_printf(MSG_ERROR,
1245                                    "ENGINE: cannot load private key with id '%s' [%s]",
1246                                    key_id,
1247                                    ERR_error_string(err, NULL));
1248                         if (tls_is_pin_error(err))
1249                                 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
1250                         else
1251                                 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1252                         goto err;
1253                 }
1254         }
1255
1256         /* handle a certificate and/or CA certificate */
1257         if (cert_id || ca_cert_id) {
1258                 const char *cmd_name = "LOAD_CERT_CTRL";
1259
1260                 /* test if the engine supports a LOAD_CERT_CTRL */
1261                 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
1262                                  0, (void *)cmd_name, NULL)) {
1263                         wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
1264                                    " loading certificates");
1265                         ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1266                         goto err;
1267                 }
1268         }
1269
1270         return 0;
1271
1272 err:
1273         if (conn->engine) {
1274                 ENGINE_free(conn->engine);
1275                 conn->engine = NULL;
1276         }
1277
1278         if (conn->private_key) {
1279                 EVP_PKEY_free(conn->private_key);
1280                 conn->private_key = NULL;
1281         }
1282
1283         return ret;
1284 #else /* OPENSSL_NO_ENGINE */
1285         return 0;
1286 #endif /* OPENSSL_NO_ENGINE */
1287 }
1288
1289
1290 static void tls_engine_deinit(struct tls_connection *conn)
1291 {
1292 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
1293         wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
1294         if (conn->private_key) {
1295                 EVP_PKEY_free(conn->private_key);
1296                 conn->private_key = NULL;
1297         }
1298         if (conn->engine) {
1299 #if !defined(OPENSSL_IS_BORINGSSL)
1300                 ENGINE_finish(conn->engine);
1301 #endif /* !OPENSSL_IS_BORINGSSL */
1302                 conn->engine = NULL;
1303         }
1304 #endif /* ANDROID || !OPENSSL_NO_ENGINE */
1305 }
1306
1307
1308 int tls_get_errors(void *ssl_ctx)
1309 {
1310         int count = 0;
1311         unsigned long err;
1312
1313         while ((err = ERR_get_error())) {
1314                 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
1315                            ERR_error_string(err, NULL));
1316                 count++;
1317         }
1318
1319         return count;
1320 }
1321
1322
1323 static const char * openssl_content_type(int content_type)
1324 {
1325         switch (content_type) {
1326         case 20:
1327                 return "change cipher spec";
1328         case 21:
1329                 return "alert";
1330         case 22:
1331                 return "handshake";
1332         case 23:
1333                 return "application data";
1334         case 24:
1335                 return "heartbeat";
1336         case 256:
1337                 return "TLS header info"; /* pseudo content type */
1338         case 257:
1339                 return "inner content type"; /* pseudo content type */
1340         default:
1341                 return "?";
1342         }
1343 }
1344
1345
1346 static const char * openssl_handshake_type(int content_type, const u8 *buf,
1347                                            size_t len)
1348 {
1349         if (content_type == 257 && buf && len == 1)
1350                 return openssl_content_type(buf[0]);
1351         if (content_type != 22 || !buf || len == 0)
1352                 return "";
1353         switch (buf[0]) {
1354         case 0:
1355                 return "hello request";
1356         case 1:
1357                 return "client hello";
1358         case 2:
1359                 return "server hello";
1360         case 3:
1361                 return "hello verify request";
1362         case 4:
1363                 return "new session ticket";
1364         case 5:
1365                 return "end of early data";
1366         case 6:
1367                 return "hello retry request";
1368         case 8:
1369                 return "encrypted extensions";
1370         case 11:
1371                 return "certificate";
1372         case 12:
1373                 return "server key exchange";
1374         case 13:
1375                 return "certificate request";
1376         case 14:
1377                 return "server hello done";
1378         case 15:
1379                 return "certificate verify";
1380         case 16:
1381                 return "client key exchange";
1382         case 20:
1383                 return "finished";
1384         case 21:
1385                 return "certificate url";
1386         case 22:
1387                 return "certificate status";
1388         case 23:
1389                 return "supplemental data";
1390         case 24:
1391                 return "key update";
1392         case 254:
1393                 return "message hash";
1394         default:
1395                 return "?";
1396         }
1397 }
1398
1399
1400 #ifdef CONFIG_SUITEB
1401
1402 static void check_server_hello(struct tls_connection *conn,
1403                                const u8 *pos, const u8 *end)
1404 {
1405         size_t payload_len, id_len;
1406
1407         /*
1408          * Parse ServerHello to get the selected cipher suite since OpenSSL does
1409          * not make it cleanly available during handshake and we need to know
1410          * whether DHE was selected.
1411          */
1412
1413         if (end - pos < 3)
1414                 return;
1415         payload_len = WPA_GET_BE24(pos);
1416         pos += 3;
1417
1418         if ((size_t) (end - pos) < payload_len)
1419                 return;
1420         end = pos + payload_len;
1421
1422         /* Skip Version and Random */
1423         if (end - pos < 2 + SSL3_RANDOM_SIZE)
1424                 return;
1425         pos += 2 + SSL3_RANDOM_SIZE;
1426
1427         /* Skip Session ID */
1428         if (end - pos < 1)
1429                 return;
1430         id_len = *pos++;
1431         if ((size_t) (end - pos) < id_len)
1432                 return;
1433         pos += id_len;
1434
1435         if (end - pos < 2)
1436                 return;
1437         conn->cipher_suite = WPA_GET_BE16(pos);
1438         wpa_printf(MSG_DEBUG, "OpenSSL: Server selected cipher suite 0x%x",
1439                    conn->cipher_suite);
1440 }
1441
1442
1443 static void check_server_key_exchange(SSL *ssl, struct tls_connection *conn,
1444                                       const u8 *pos, const u8 *end)
1445 {
1446         size_t payload_len;
1447         u16 dh_len;
1448         BIGNUM *p;
1449         int bits;
1450
1451         if (!(conn->flags & TLS_CONN_SUITEB))
1452                 return;
1453
1454         /* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
1455         if (conn->cipher_suite != 0x9f)
1456                 return;
1457
1458         if (end - pos < 3)
1459                 return;
1460         payload_len = WPA_GET_BE24(pos);
1461         pos += 3;
1462
1463         if ((size_t) (end - pos) < payload_len)
1464                 return;
1465         end = pos + payload_len;
1466
1467         if (end - pos < 2)
1468                 return;
1469         dh_len = WPA_GET_BE16(pos);
1470         pos += 2;
1471
1472         if ((size_t) (end - pos) < dh_len)
1473                 return;
1474         p = BN_bin2bn(pos, dh_len, NULL);
1475         if (!p)
1476                 return;
1477
1478         bits = BN_num_bits(p);
1479         BN_free(p);
1480
1481         conn->server_dh_prime_len = bits;
1482         wpa_printf(MSG_DEBUG, "OpenSSL: Server DH prime length: %d bits",
1483                    conn->server_dh_prime_len);
1484 }
1485
1486 #endif /* CONFIG_SUITEB */
1487
1488
1489 static void tls_msg_cb(int write_p, int version, int content_type,
1490                        const void *buf, size_t len, SSL *ssl, void *arg)
1491 {
1492         struct tls_connection *conn = arg;
1493         const u8 *pos = buf;
1494
1495         if (write_p == 2) {
1496                 wpa_printf(MSG_DEBUG,
1497                            "OpenSSL: session ver=0x%x content_type=%d",
1498                            version, content_type);
1499                 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
1500                 return;
1501         }
1502
1503         wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
1504                    write_p ? "TX" : "RX", version, content_type,
1505                    openssl_content_type(content_type),
1506                    openssl_handshake_type(content_type, buf, len));
1507         wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
1508         if (content_type == 24 && len >= 3 && pos[0] == 1) {
1509                 size_t payload_len = WPA_GET_BE16(pos + 1);
1510                 if (payload_len + 3 > len) {
1511                         wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
1512                         conn->invalid_hb_used = 1;
1513                 }
1514         }
1515
1516 #ifdef CONFIG_SUITEB
1517         /*
1518          * Need to parse these handshake messages to be able to check DH prime
1519          * length since OpenSSL does not expose the new cipher suite and DH
1520          * parameters during handshake (e.g., for cert_cb() callback).
1521          */
1522         if (content_type == 22 && pos && len > 0 && pos[0] == 2)
1523                 check_server_hello(conn, pos + 1, pos + len);
1524         if (content_type == 22 && pos && len > 0 && pos[0] == 12)
1525                 check_server_key_exchange(ssl, conn, pos + 1, pos + len);
1526 #endif /* CONFIG_SUITEB */
1527 }
1528
1529
1530 struct tls_connection * tls_connection_init(void *ssl_ctx)
1531 {
1532         struct tls_data *data = ssl_ctx;
1533         SSL_CTX *ssl = data->ssl;
1534         struct tls_connection *conn;
1535         long options;
1536         X509_STORE *new_cert_store;
1537         struct os_reltime now;
1538         struct tls_context *context = SSL_CTX_get_app_data(ssl);
1539
1540         /* Replace X509 store if it is time to update CRL. */
1541         if (data->crl_reload_interval > 0 && os_get_reltime(&now) == 0 &&
1542             os_reltime_expired(&now, &data->crl_last_reload,
1543                                data->crl_reload_interval)) {
1544                 wpa_printf(MSG_INFO,
1545                            "OpenSSL: Flushing X509 store with ca_cert file");
1546                 new_cert_store = tls_crl_cert_reload(data->ca_cert,
1547                                                      data->check_crl);
1548                 if (!new_cert_store) {
1549                         wpa_printf(MSG_ERROR,
1550                                    "OpenSSL: Error replacing X509 store with ca_cert file");
1551                 } else {
1552                         /* Replace old store */
1553                         SSL_CTX_set_cert_store(ssl, new_cert_store);
1554                         data->crl_last_reload = now;
1555                 }
1556         }
1557
1558         conn = os_zalloc(sizeof(*conn));
1559         if (conn == NULL)
1560                 return NULL;
1561         conn->data = data;
1562         conn->ssl_ctx = ssl;
1563         conn->ssl = SSL_new(ssl);
1564         if (conn->ssl == NULL) {
1565                 tls_show_errors(MSG_INFO, __func__,
1566                                 "Failed to initialize new SSL connection");
1567                 os_free(conn);
1568                 return NULL;
1569         }
1570
1571         conn->context = context;
1572         SSL_set_app_data(conn->ssl, conn);
1573         SSL_set_msg_callback(conn->ssl, tls_msg_cb);
1574         SSL_set_msg_callback_arg(conn->ssl, conn);
1575         options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
1576                 SSL_OP_SINGLE_DH_USE;
1577 #ifdef SSL_OP_NO_COMPRESSION
1578         options |= SSL_OP_NO_COMPRESSION;
1579 #endif /* SSL_OP_NO_COMPRESSION */
1580         SSL_set_options(conn->ssl, options);
1581 #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
1582         /* Hopefully there is no need for middlebox compatibility mechanisms
1583          * when going through EAP authentication. */
1584         SSL_clear_options(conn->ssl, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
1585 #endif
1586
1587         conn->ssl_in = BIO_new(BIO_s_mem());
1588         if (!conn->ssl_in) {
1589                 tls_show_errors(MSG_INFO, __func__,
1590                                 "Failed to create a new BIO for ssl_in");
1591                 SSL_free(conn->ssl);
1592                 os_free(conn);
1593                 return NULL;
1594         }
1595
1596         conn->ssl_out = BIO_new(BIO_s_mem());
1597         if (!conn->ssl_out) {
1598                 tls_show_errors(MSG_INFO, __func__,
1599                                 "Failed to create a new BIO for ssl_out");
1600                 SSL_free(conn->ssl);
1601                 BIO_free(conn->ssl_in);
1602                 os_free(conn);
1603                 return NULL;
1604         }
1605
1606         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
1607
1608         return conn;
1609 }
1610
1611
1612 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
1613 {
1614         if (conn == NULL)
1615                 return;
1616         if (conn->success_data) {
1617                 /*
1618                  * Make sure ssl_clear_bad_session() does not remove this
1619                  * session.
1620                  */
1621                 SSL_set_quiet_shutdown(conn->ssl, 1);
1622                 SSL_shutdown(conn->ssl);
1623         }
1624         SSL_free(conn->ssl);
1625         tls_engine_deinit(conn);
1626         os_free(conn->subject_match);
1627         os_free(conn->altsubject_match);
1628         os_free(conn->suffix_match);
1629         os_free(conn->domain_match);
1630         os_free(conn->check_cert_subject);
1631         os_free(conn->session_ticket);
1632         os_free(conn);
1633 }
1634
1635
1636 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
1637 {
1638         return conn ? SSL_is_init_finished(conn->ssl) : 0;
1639 }
1640
1641
1642 char * tls_connection_peer_serial_num(void *tls_ctx,
1643                                       struct tls_connection *conn)
1644 {
1645         ASN1_INTEGER *ser;
1646         char *serial_num;
1647         size_t len;
1648
1649         if (!conn->peer_cert)
1650                 return NULL;
1651
1652         ser = X509_get_serialNumber(conn->peer_cert);
1653         if (!ser)
1654                 return NULL;
1655
1656         len = ASN1_STRING_length(ser) * 2 + 1;
1657         serial_num = os_malloc(len);
1658         if (!serial_num)
1659                 return NULL;
1660         wpa_snprintf_hex_uppercase(serial_num, len,
1661                                    ASN1_STRING_get0_data(ser),
1662                                    ASN1_STRING_length(ser));
1663         return serial_num;
1664 }
1665
1666
1667 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
1668 {
1669         if (conn == NULL)
1670                 return -1;
1671
1672         /* Shutdown previous TLS connection without notifying the peer
1673          * because the connection was already terminated in practice
1674          * and "close notify" shutdown alert would confuse AS. */
1675         SSL_set_quiet_shutdown(conn->ssl, 1);
1676         SSL_shutdown(conn->ssl);
1677         return SSL_clear(conn->ssl) == 1 ? 0 : -1;
1678 }
1679
1680
1681 static int tls_match_altsubject_component(X509 *cert, int type,
1682                                           const char *value, size_t len)
1683 {
1684         GENERAL_NAME *gen;
1685         void *ext;
1686         int found = 0;
1687         stack_index_t i;
1688
1689         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
1690
1691         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
1692                 gen = sk_GENERAL_NAME_value(ext, i);
1693                 if (gen->type != type)
1694                         continue;
1695                 if (os_strlen((char *) gen->d.ia5->data) == len &&
1696                     os_memcmp(value, gen->d.ia5->data, len) == 0)
1697                         found++;
1698         }
1699
1700         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
1701
1702         return found;
1703 }
1704
1705
1706 static int tls_match_altsubject(X509 *cert, const char *match)
1707 {
1708         int type;
1709         const char *pos, *end;
1710         size_t len;
1711
1712         pos = match;
1713         do {
1714                 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1715                         type = GEN_EMAIL;
1716                         pos += 6;
1717                 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1718                         type = GEN_DNS;
1719                         pos += 4;
1720                 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1721                         type = GEN_URI;
1722                         pos += 4;
1723                 } else {
1724                         wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1725                                    "match '%s'", pos);
1726                         return 0;
1727                 }
1728                 end = os_strchr(pos, ';');
1729                 while (end) {
1730                         if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1731                             os_strncmp(end + 1, "DNS:", 4) == 0 ||
1732                             os_strncmp(end + 1, "URI:", 4) == 0)
1733                                 break;
1734                         end = os_strchr(end + 1, ';');
1735                 }
1736                 if (end)
1737                         len = end - pos;
1738                 else
1739                         len = os_strlen(pos);
1740                 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1741                         return 1;
1742                 pos = end + 1;
1743         } while (end);
1744
1745         return 0;
1746 }
1747
1748
1749 #ifndef CONFIG_NATIVE_WINDOWS
1750 static int domain_suffix_match(const u8 *val, size_t len, const char *match,
1751                                size_t match_len, int full)
1752 {
1753         size_t i;
1754
1755         /* Check for embedded nuls that could mess up suffix matching */
1756         for (i = 0; i < len; i++) {
1757                 if (val[i] == '\0') {
1758                         wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
1759                         return 0;
1760                 }
1761         }
1762
1763         if (match_len > len || (full && match_len != len))
1764                 return 0;
1765
1766         if (os_strncasecmp((const char *) val + len - match_len, match,
1767                            match_len) != 0)
1768                 return 0; /* no match */
1769
1770         if (match_len == len)
1771                 return 1; /* exact match */
1772
1773         if (val[len - match_len - 1] == '.')
1774                 return 1; /* full label match completes suffix match */
1775
1776         wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
1777         return 0;
1778 }
1779 #endif /* CONFIG_NATIVE_WINDOWS */
1780
1781
1782 struct tls_dn_field_order_cnt {
1783         u8 cn;
1784         u8 c;
1785         u8 l;
1786         u8 st;
1787         u8 o;
1788         u8 ou;
1789         u8 email;
1790 };
1791
1792
1793 static int get_dn_field_index(const struct tls_dn_field_order_cnt *dn_cnt,
1794                               int nid)
1795 {
1796         switch (nid) {
1797         case NID_commonName:
1798                 return dn_cnt->cn;
1799         case NID_countryName:
1800                 return dn_cnt->c;
1801         case NID_localityName:
1802                 return dn_cnt->l;
1803         case NID_stateOrProvinceName:
1804                 return dn_cnt->st;
1805         case NID_organizationName:
1806                 return dn_cnt->o;
1807         case NID_organizationalUnitName:
1808                 return dn_cnt->ou;
1809         case NID_pkcs9_emailAddress:
1810                 return dn_cnt->email;
1811         default:
1812                 wpa_printf(MSG_ERROR,
1813                            "TLS: Unknown NID '%d' in check_cert_subject",
1814                            nid);
1815                 return -1;
1816         }
1817 }
1818
1819
1820 /**
1821  * match_dn_field - Match configuration DN field against Certificate DN field
1822  * @cert: Certificate
1823  * @nid: NID of DN field
1824  * @field: Field name
1825  * @value DN field value which is passed from configuration
1826  *      e.g., if configuration have C=US and this argument will point to US.
1827  * @dn_cnt: DN matching context
1828  * Returns: 1 on success and 0 on failure
1829  */
1830 static int match_dn_field(const X509 *cert, int nid, const char *field,
1831                           const char *value,
1832                           const struct tls_dn_field_order_cnt *dn_cnt)
1833 {
1834         int i, ret = 0, len, config_dn_field_index, match_index = 0;
1835         X509_NAME *name;
1836
1837         len = os_strlen(value);
1838         name = X509_get_subject_name((X509 *) cert);
1839
1840         /* Assign incremented cnt for every field of DN to check DN field in
1841          * right order */
1842         config_dn_field_index = get_dn_field_index(dn_cnt, nid);
1843         if (config_dn_field_index < 0)
1844                 return 0;
1845
1846         /* Fetch value based on NID */
1847         for (i = -1; (i = X509_NAME_get_index_by_NID(name, nid, i)) > -1;) {
1848                 X509_NAME_ENTRY *e;
1849                 ASN1_STRING *cn;
1850
1851                 e = X509_NAME_get_entry(name, i);
1852                 if (!e)
1853                         continue;
1854
1855                 cn = X509_NAME_ENTRY_get_data(e);
1856                 if (!cn)
1857                         continue;
1858
1859                 match_index++;
1860
1861                 /* check for more than one DN field with same name */
1862                 if (match_index != config_dn_field_index)
1863                         continue;
1864
1865                 /* Check wildcard at the right end side */
1866                 /* E.g., if OU=develop* mentioned in configuration, allow 'OU'
1867                  * of the subject in the client certificate to start with
1868                  * 'develop' */
1869                 if (len > 0 && value[len - 1] == '*') {
1870                         /* Compare actual certificate DN field value with
1871                          * configuration DN field value up to the specified
1872                          * length. */
1873                         ret = ASN1_STRING_length(cn) >= len - 1 &&
1874                                 os_memcmp(ASN1_STRING_get0_data(cn), value,
1875                                           len - 1) == 0;
1876                 } else {
1877                         /* Compare actual certificate DN field value with
1878                          * configuration DN field value */
1879                         ret = ASN1_STRING_length(cn) == len &&
1880                                 os_memcmp(ASN1_STRING_get0_data(cn), value,
1881                                           len) == 0;
1882                 }
1883                 if (!ret) {
1884                         wpa_printf(MSG_ERROR,
1885                                    "OpenSSL: Failed to match %s '%s' with certificate DN field value '%s'",
1886                                    field, value, ASN1_STRING_get0_data(cn));
1887                 }
1888                 break;
1889         }
1890
1891         return ret;
1892 }
1893
1894
1895 /**
1896  * get_value_from_field - Get value from DN field
1897  * @cert: Certificate
1898  * @field_str: DN field string which is passed from configuration file (e.g.,
1899  *       C=US)
1900  * @dn_cnt: DN matching context
1901  * Returns: 1 on success and 0 on failure
1902  */
1903 static int get_value_from_field(const X509 *cert, char *field_str,
1904                                 struct tls_dn_field_order_cnt *dn_cnt)
1905 {
1906         int nid;
1907         char *context = NULL, *name, *value;
1908
1909         if (os_strcmp(field_str, "*") == 0)
1910                 return 1; /* wildcard matches everything */
1911
1912         name = str_token(field_str, "=", &context);
1913         if (!name)
1914                 return 0;
1915
1916         /* Compare all configured DN fields and assign nid based on that to
1917          * fetch correct value from certificate subject */
1918         if (os_strcmp(name, "CN") == 0) {
1919                 nid = NID_commonName;
1920                 dn_cnt->cn++;
1921         } else if(os_strcmp(name, "C") == 0) {
1922                 nid = NID_countryName;
1923                 dn_cnt->c++;
1924         } else if (os_strcmp(name, "L") == 0) {
1925                 nid = NID_localityName;
1926                 dn_cnt->l++;
1927         } else if (os_strcmp(name, "ST") == 0) {
1928                 nid = NID_stateOrProvinceName;
1929                 dn_cnt->st++;
1930         } else if (os_strcmp(name, "O") == 0) {
1931                 nid = NID_organizationName;
1932                 dn_cnt->o++;
1933         } else if (os_strcmp(name, "OU") == 0) {
1934                 nid = NID_organizationalUnitName;
1935                 dn_cnt->ou++;
1936         } else if (os_strcmp(name, "emailAddress") == 0) {
1937                 nid = NID_pkcs9_emailAddress;
1938                 dn_cnt->email++;
1939         } else {
1940                 wpa_printf(MSG_ERROR,
1941                         "TLS: Unknown field '%s' in check_cert_subject", name);
1942                 return 0;
1943         }
1944
1945         value = str_token(field_str, "=", &context);
1946         if (!value) {
1947                 wpa_printf(MSG_ERROR,
1948                            "TLS: Distinguished Name field '%s' value is not defined in check_cert_subject",
1949                            name);
1950                 return 0;
1951         }
1952
1953         return match_dn_field(cert, nid, name, value, dn_cnt);
1954 }
1955
1956
1957 /**
1958  * tls_match_dn_field - Match subject DN field with check_cert_subject
1959  * @cert: Certificate
1960  * @match: check_cert_subject string
1961  * Returns: Return 1 on success and 0 on failure
1962 */
1963 static int tls_match_dn_field(X509 *cert, const char *match)
1964 {
1965         const char *token, *last = NULL;
1966         char field[256];
1967         struct tls_dn_field_order_cnt dn_cnt;
1968
1969         os_memset(&dn_cnt, 0, sizeof(dn_cnt));
1970
1971         /* Maximum length of each DN field is 255 characters */
1972
1973         /* Process each '/' delimited field */
1974         while ((token = cstr_token(match, "/", &last))) {
1975                 if (last - token >= (int) sizeof(field)) {
1976                         wpa_printf(MSG_ERROR,
1977                                    "OpenSSL: Too long DN matching field value in '%s'",
1978                                    match);
1979                         return 0;
1980                 }
1981                 os_memcpy(field, token, last - token);
1982                 field[last - token] = '\0';
1983
1984                 if (!get_value_from_field(cert, field, &dn_cnt)) {
1985                         wpa_printf(MSG_DEBUG, "OpenSSL: No match for DN '%s'",
1986                                    field);
1987                         return 0;
1988                 }
1989         }
1990
1991         return 1;
1992 }
1993
1994
1995 #ifndef CONFIG_NATIVE_WINDOWS
1996 static int tls_match_suffix_helper(X509 *cert, const char *match,
1997                                    size_t match_len, int full)
1998 {
1999         GENERAL_NAME *gen;
2000         void *ext;
2001         int i;
2002         stack_index_t j;
2003         int dns_name = 0;
2004         X509_NAME *name;
2005
2006         wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
2007                    full ? "": "suffix ", match);
2008
2009         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
2010
2011         for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
2012                 gen = sk_GENERAL_NAME_value(ext, j);
2013                 if (gen->type != GEN_DNS)
2014                         continue;
2015                 dns_name++;
2016                 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
2017                                   gen->d.dNSName->data,
2018                                   gen->d.dNSName->length);
2019                 if (domain_suffix_match(gen->d.dNSName->data,
2020                                         gen->d.dNSName->length,
2021                                         match, match_len, full) == 1) {
2022                         wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
2023                                    full ? "Match" : "Suffix match");
2024                         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2025                         return 1;
2026                 }
2027         }
2028         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2029
2030         if (dns_name) {
2031                 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
2032                 return 0;
2033         }
2034
2035         name = X509_get_subject_name(cert);
2036         i = -1;
2037         for (;;) {
2038                 X509_NAME_ENTRY *e;
2039                 ASN1_STRING *cn;
2040
2041                 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
2042                 if (i == -1)
2043                         break;
2044                 e = X509_NAME_get_entry(name, i);
2045                 if (e == NULL)
2046                         continue;
2047                 cn = X509_NAME_ENTRY_get_data(e);
2048                 if (cn == NULL)
2049                         continue;
2050                 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
2051                                   cn->data, cn->length);
2052                 if (domain_suffix_match(cn->data, cn->length,
2053                                         match, match_len, full) == 1) {
2054                         wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
2055                                    full ? "Match" : "Suffix match");
2056                         return 1;
2057                 }
2058         }
2059
2060         wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
2061                    full ? "": "suffix ");
2062         return 0;
2063 }
2064 #endif /* CONFIG_NATIVE_WINDOWS */
2065
2066
2067 static int tls_match_suffix(X509 *cert, const char *match, int full)
2068 {
2069 #ifdef CONFIG_NATIVE_WINDOWS
2070         /* wincrypt.h has conflicting X509_NAME definition */
2071         return -1;
2072 #else /* CONFIG_NATIVE_WINDOWS */
2073         const char *token, *last = NULL;
2074
2075         /* Process each match alternative separately until a match is found */
2076         while ((token = cstr_token(match, ";", &last))) {
2077                 if (tls_match_suffix_helper(cert, token, last - token, full))
2078                         return 1;
2079         }
2080
2081         return 0;
2082 #endif /* CONFIG_NATIVE_WINDOWS */
2083 }
2084
2085
2086 static enum tls_fail_reason openssl_tls_fail_reason(int err)
2087 {
2088         switch (err) {
2089         case X509_V_ERR_CERT_REVOKED:
2090                 return TLS_FAIL_REVOKED;
2091         case X509_V_ERR_CERT_NOT_YET_VALID:
2092         case X509_V_ERR_CRL_NOT_YET_VALID:
2093                 return TLS_FAIL_NOT_YET_VALID;
2094         case X509_V_ERR_CERT_HAS_EXPIRED:
2095         case X509_V_ERR_CRL_HAS_EXPIRED:
2096                 return TLS_FAIL_EXPIRED;
2097         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
2098         case X509_V_ERR_UNABLE_TO_GET_CRL:
2099         case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
2100         case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
2101         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
2102         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
2103         case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
2104         case X509_V_ERR_CERT_CHAIN_TOO_LONG:
2105         case X509_V_ERR_PATH_LENGTH_EXCEEDED:
2106         case X509_V_ERR_INVALID_CA:
2107                 return TLS_FAIL_UNTRUSTED;
2108         case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
2109         case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
2110         case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
2111         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
2112         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
2113         case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
2114         case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
2115         case X509_V_ERR_CERT_UNTRUSTED:
2116         case X509_V_ERR_CERT_REJECTED:
2117                 return TLS_FAIL_BAD_CERTIFICATE;
2118         default:
2119                 return TLS_FAIL_UNSPECIFIED;
2120         }
2121 }
2122
2123
2124 static struct wpabuf * get_x509_cert(X509 *cert)
2125 {
2126         struct wpabuf *buf;
2127         u8 *tmp;
2128
2129         int cert_len = i2d_X509(cert, NULL);
2130         if (cert_len <= 0)
2131                 return NULL;
2132
2133         buf = wpabuf_alloc(cert_len);
2134         if (buf == NULL)
2135                 return NULL;
2136
2137         tmp = wpabuf_put(buf, cert_len);
2138         i2d_X509(cert, &tmp);
2139         return buf;
2140 }
2141
2142
2143 static void openssl_tls_fail_event(struct tls_connection *conn,
2144                                    X509 *err_cert, int err, int depth,
2145                                    const char *subject, const char *err_str,
2146                                    enum tls_fail_reason reason)
2147 {
2148         union tls_event_data ev;
2149         struct wpabuf *cert = NULL;
2150         struct tls_context *context = conn->context;
2151
2152         if (context->event_cb == NULL)
2153                 return;
2154
2155         cert = get_x509_cert(err_cert);
2156         os_memset(&ev, 0, sizeof(ev));
2157         ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
2158                 reason : openssl_tls_fail_reason(err);
2159         ev.cert_fail.depth = depth;
2160         ev.cert_fail.subject = subject;
2161         ev.cert_fail.reason_txt = err_str;
2162         ev.cert_fail.cert = cert;
2163         context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
2164         wpabuf_free(cert);
2165 }
2166
2167
2168 static int openssl_cert_tod(X509 *cert)
2169 {
2170         CERTIFICATEPOLICIES *ext;
2171         stack_index_t i;
2172         char buf[100];
2173         int res;
2174         int tod = 0;
2175
2176         ext = X509_get_ext_d2i(cert, NID_certificate_policies, NULL, NULL);
2177         if (!ext)
2178                 return 0;
2179
2180         for (i = 0; i < sk_POLICYINFO_num(ext); i++) {
2181                 POLICYINFO *policy;
2182
2183                 policy = sk_POLICYINFO_value(ext, i);
2184                 res = OBJ_obj2txt(buf, sizeof(buf), policy->policyid, 0);
2185                 if (res < 0 || (size_t) res >= sizeof(buf))
2186                         continue;
2187                 wpa_printf(MSG_DEBUG, "OpenSSL: Certificate Policy %s", buf);
2188                 if (os_strcmp(buf, "1.3.6.1.4.1.40808.1.3.1") == 0)
2189                         tod = 1;
2190         }
2191
2192         return tod;
2193 }
2194
2195
2196 static void openssl_tls_cert_event(struct tls_connection *conn,
2197                                    X509 *err_cert, int depth,
2198                                    const char *subject)
2199 {
2200         struct wpabuf *cert = NULL;
2201         union tls_event_data ev;
2202         struct tls_context *context = conn->context;
2203         char *altsubject[TLS_MAX_ALT_SUBJECT];
2204         int alt, num_altsubject = 0;
2205         GENERAL_NAME *gen;
2206         void *ext;
2207         stack_index_t i;
2208         ASN1_INTEGER *ser;
2209         char serial_num[128];
2210 #ifdef CONFIG_SHA256
2211         u8 hash[32];
2212 #endif /* CONFIG_SHA256 */
2213
2214         if (context->event_cb == NULL)
2215                 return;
2216
2217         os_memset(&ev, 0, sizeof(ev));
2218         if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
2219             context->cert_in_cb) {
2220                 cert = get_x509_cert(err_cert);
2221                 ev.peer_cert.cert = cert;
2222         }
2223 #ifdef CONFIG_SHA256
2224         if (cert) {
2225                 const u8 *addr[1];
2226                 size_t len[1];
2227                 addr[0] = wpabuf_head(cert);
2228                 len[0] = wpabuf_len(cert);
2229                 if (sha256_vector(1, addr, len, hash) == 0) {
2230                         ev.peer_cert.hash = hash;
2231                         ev.peer_cert.hash_len = sizeof(hash);
2232                 }
2233         }
2234 #endif /* CONFIG_SHA256 */
2235         ev.peer_cert.depth = depth;
2236         ev.peer_cert.subject = subject;
2237
2238         ser = X509_get_serialNumber(err_cert);
2239         if (ser) {
2240                 wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
2241                                            ASN1_STRING_get0_data(ser),
2242                                            ASN1_STRING_length(ser));
2243                 ev.peer_cert.serial_num = serial_num;
2244         }
2245
2246         ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
2247         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
2248                 char *pos;
2249
2250                 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
2251                         break;
2252                 gen = sk_GENERAL_NAME_value(ext, i);
2253                 if (gen->type != GEN_EMAIL &&
2254                     gen->type != GEN_DNS &&
2255                     gen->type != GEN_URI)
2256                         continue;
2257
2258                 pos = os_malloc(10 + gen->d.ia5->length + 1);
2259                 if (pos == NULL)
2260                         break;
2261                 altsubject[num_altsubject++] = pos;
2262
2263                 switch (gen->type) {
2264                 case GEN_EMAIL:
2265                         os_memcpy(pos, "EMAIL:", 6);
2266                         pos += 6;
2267                         break;
2268                 case GEN_DNS:
2269                         os_memcpy(pos, "DNS:", 4);
2270                         pos += 4;
2271                         break;
2272                 case GEN_URI:
2273                         os_memcpy(pos, "URI:", 4);
2274                         pos += 4;
2275                         break;
2276                 }
2277
2278                 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
2279                 pos += gen->d.ia5->length;
2280                 *pos = '\0';
2281         }
2282         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
2283
2284         for (alt = 0; alt < num_altsubject; alt++)
2285                 ev.peer_cert.altsubject[alt] = altsubject[alt];
2286         ev.peer_cert.num_altsubject = num_altsubject;
2287
2288         ev.peer_cert.tod = openssl_cert_tod(err_cert);
2289
2290         context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
2291         wpabuf_free(cert);
2292         for (alt = 0; alt < num_altsubject; alt++)
2293                 os_free(altsubject[alt]);
2294 }
2295
2296
2297 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
2298 {
2299         char buf[256];
2300         X509 *err_cert;
2301         int err, depth;
2302         SSL *ssl;
2303         struct tls_connection *conn;
2304         struct tls_context *context;
2305         char *match, *altmatch, *suffix_match, *domain_match;
2306         const char *check_cert_subject;
2307         const char *err_str;
2308
2309         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
2310         if (!err_cert)
2311                 return 0;
2312
2313         err = X509_STORE_CTX_get_error(x509_ctx);
2314         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
2315         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
2316                                          SSL_get_ex_data_X509_STORE_CTX_idx());
2317         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
2318
2319         conn = SSL_get_app_data(ssl);
2320         if (conn == NULL)
2321                 return 0;
2322
2323         if (depth == 0)
2324                 conn->peer_cert = err_cert;
2325         else if (depth == 1)
2326                 conn->peer_issuer = err_cert;
2327         else if (depth == 2)
2328                 conn->peer_issuer_issuer = err_cert;
2329
2330         context = conn->context;
2331         match = conn->subject_match;
2332         altmatch = conn->altsubject_match;
2333         suffix_match = conn->suffix_match;
2334         domain_match = conn->domain_match;
2335
2336         if (!preverify_ok && !conn->ca_cert_verify)
2337                 preverify_ok = 1;
2338         if (!preverify_ok && depth > 0 && conn->server_cert_only)
2339                 preverify_ok = 1;
2340         if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
2341             (err == X509_V_ERR_CERT_HAS_EXPIRED ||
2342              err == X509_V_ERR_CERT_NOT_YET_VALID)) {
2343                 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
2344                            "time mismatch");
2345                 preverify_ok = 1;
2346         }
2347         if (!preverify_ok && !conn->data->check_crl_strict &&
2348             (err == X509_V_ERR_CRL_HAS_EXPIRED ||
2349              err == X509_V_ERR_CRL_NOT_YET_VALID)) {
2350                 wpa_printf(MSG_DEBUG,
2351                            "OpenSSL: Ignore certificate validity CRL time mismatch");
2352                 preverify_ok = 1;
2353         }
2354
2355         err_str = X509_verify_cert_error_string(err);
2356
2357 #ifdef CONFIG_SHA256
2358         /*
2359          * Do not require preverify_ok so we can explicity allow otherwise
2360          * invalid pinned server certificates.
2361          */
2362         if (depth == 0 && conn->server_cert_only) {
2363                 struct wpabuf *cert;
2364                 cert = get_x509_cert(err_cert);
2365                 if (!cert) {
2366                         wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
2367                                    "server certificate data");
2368                         preverify_ok = 0;
2369                 } else {
2370                         u8 hash[32];
2371                         const u8 *addr[1];
2372                         size_t len[1];
2373                         addr[0] = wpabuf_head(cert);
2374                         len[0] = wpabuf_len(cert);
2375                         if (sha256_vector(1, addr, len, hash) < 0 ||
2376                             os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
2377                                 err_str = "Server certificate mismatch";
2378                                 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
2379                                 preverify_ok = 0;
2380                         } else if (!preverify_ok) {
2381                                 /*
2382                                  * Certificate matches pinned certificate, allow
2383                                  * regardless of other problems.
2384                                  */
2385                                 wpa_printf(MSG_DEBUG,
2386                                            "OpenSSL: Ignore validation issues for a pinned server certificate");
2387                                 preverify_ok = 1;
2388                         }
2389                         wpabuf_free(cert);
2390                 }
2391         }
2392 #endif /* CONFIG_SHA256 */
2393
2394         openssl_tls_cert_event(conn, err_cert, depth, buf);
2395
2396         if (!preverify_ok) {
2397                 if (depth > 0) {
2398                         /* Send cert event for the peer certificate so that
2399                          * the upper layers get information about it even if
2400                          * validation of a CA certificate fails. */
2401                         STACK_OF(X509) *chain;
2402
2403                         chain = X509_STORE_CTX_get1_chain(x509_ctx);
2404                         if (chain && sk_X509_num(chain) > 0) {
2405                                 char buf2[256];
2406                                 X509 *cert;
2407
2408                                 cert = sk_X509_value(chain, 0);
2409                                 X509_NAME_oneline(X509_get_subject_name(cert),
2410                                                   buf2, sizeof(buf2));
2411
2412                                 openssl_tls_cert_event(conn, cert, 0, buf2);
2413                         }
2414                         if (chain)
2415                                 sk_X509_pop_free(chain, X509_free);
2416                 }
2417
2418                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
2419                            " error %d (%s) depth %d for '%s'", err, err_str,
2420                            depth, buf);
2421                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2422                                        err_str, TLS_FAIL_UNSPECIFIED);
2423                 return preverify_ok;
2424         }
2425
2426         wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
2427                    "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
2428                    preverify_ok, err, err_str,
2429                    conn->ca_cert_verify, depth, buf);
2430         check_cert_subject = conn->check_cert_subject;
2431         if (!check_cert_subject)
2432                 check_cert_subject = conn->data->check_cert_subject;
2433         if (check_cert_subject) {
2434                 if (depth == 0 &&
2435                     !tls_match_dn_field(err_cert, check_cert_subject)) {
2436                         preverify_ok = 0;
2437                         openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2438                                                "Distinguished Name",
2439                                                TLS_FAIL_DN_MISMATCH);
2440                 }
2441         }
2442         if (depth == 0 && match && os_strstr(buf, match) == NULL) {
2443                 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
2444                            "match with '%s'", buf, match);
2445                 preverify_ok = 0;
2446                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2447                                        "Subject mismatch",
2448                                        TLS_FAIL_SUBJECT_MISMATCH);
2449         } else if (depth == 0 && altmatch &&
2450                    !tls_match_altsubject(err_cert, altmatch)) {
2451                 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
2452                            "'%s' not found", altmatch);
2453                 preverify_ok = 0;
2454                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2455                                        "AltSubject mismatch",
2456                                        TLS_FAIL_ALTSUBJECT_MISMATCH);
2457         } else if (depth == 0 && suffix_match &&
2458                    !tls_match_suffix(err_cert, suffix_match, 0)) {
2459                 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
2460                            suffix_match);
2461                 preverify_ok = 0;
2462                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2463                                        "Domain suffix mismatch",
2464                                        TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
2465         } else if (depth == 0 && domain_match &&
2466                    !tls_match_suffix(err_cert, domain_match, 1)) {
2467                 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
2468                            domain_match);
2469                 preverify_ok = 0;
2470                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2471                                        "Domain mismatch",
2472                                        TLS_FAIL_DOMAIN_MISMATCH);
2473         }
2474
2475         if (conn->cert_probe && preverify_ok && depth == 0) {
2476                 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
2477                            "on probe-only run");
2478                 preverify_ok = 0;
2479                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2480                                        "Server certificate chain probe",
2481                                        TLS_FAIL_SERVER_CHAIN_PROBE);
2482         }
2483
2484 #ifdef CONFIG_SUITEB
2485         if (conn->flags & TLS_CONN_SUITEB) {
2486                 EVP_PKEY *pk;
2487                 RSA *rsa;
2488                 int len = -1;
2489
2490                 pk = X509_get_pubkey(err_cert);
2491                 if (pk) {
2492                         rsa = EVP_PKEY_get1_RSA(pk);
2493                         if (rsa) {
2494                                 len = RSA_bits(rsa);
2495                                 RSA_free(rsa);
2496                         }
2497                         EVP_PKEY_free(pk);
2498                 }
2499
2500                 if (len >= 0) {
2501                         wpa_printf(MSG_DEBUG,
2502                                    "OpenSSL: RSA modulus size: %d bits", len);
2503                         if (len < 3072) {
2504                                 preverify_ok = 0;
2505                                 openssl_tls_fail_event(
2506                                         conn, err_cert, err,
2507                                         depth, buf,
2508                                         "Insufficient RSA modulus size",
2509                                         TLS_FAIL_INSUFFICIENT_KEY_LEN);
2510                         }
2511                 }
2512         }
2513 #endif /* CONFIG_SUITEB */
2514
2515 #ifdef OPENSSL_IS_BORINGSSL
2516         if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
2517             preverify_ok) {
2518                 enum ocsp_result res;
2519
2520                 res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
2521                                       conn->peer_issuer,
2522                                       conn->peer_issuer_issuer);
2523                 if (res == OCSP_REVOKED) {
2524                         preverify_ok = 0;
2525                         openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2526                                                "certificate revoked",
2527                                                TLS_FAIL_REVOKED);
2528                         if (err == X509_V_OK)
2529                                 X509_STORE_CTX_set_error(
2530                                         x509_ctx, X509_V_ERR_CERT_REVOKED);
2531                 } else if (res != OCSP_GOOD &&
2532                            (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
2533                         preverify_ok = 0;
2534                         openssl_tls_fail_event(conn, err_cert, err, depth, buf,
2535                                                "bad certificate status response",
2536                                                TLS_FAIL_UNSPECIFIED);
2537                 }
2538         }
2539 #endif /* OPENSSL_IS_BORINGSSL */
2540
2541         if (depth == 0 && preverify_ok && context->event_cb != NULL)
2542                 context->event_cb(context->cb_ctx,
2543                                   TLS_CERT_CHAIN_SUCCESS, NULL);
2544
2545         return preverify_ok;
2546 }
2547
2548
2549 #ifndef OPENSSL_NO_STDIO
2550 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
2551 {
2552         SSL_CTX *ssl_ctx = data->ssl;
2553         X509_LOOKUP *lookup;
2554         int ret = 0;
2555
2556         lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
2557                                        X509_LOOKUP_file());
2558         if (lookup == NULL) {
2559                 tls_show_errors(MSG_WARNING, __func__,
2560                                 "Failed add lookup for X509 store");
2561                 return -1;
2562         }
2563
2564         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
2565                 unsigned long err = ERR_peek_error();
2566                 tls_show_errors(MSG_WARNING, __func__,
2567                                 "Failed load CA in DER format");
2568                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2569                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2570                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2571                                    "cert already in hash table error",
2572                                    __func__);
2573                 } else
2574                         ret = -1;
2575         }
2576
2577         return ret;
2578 }
2579 #endif /* OPENSSL_NO_STDIO */
2580
2581
2582 static int tls_connection_ca_cert(struct tls_data *data,
2583                                   struct tls_connection *conn,
2584                                   const char *ca_cert, const u8 *ca_cert_blob,
2585                                   size_t ca_cert_blob_len, const char *ca_path)
2586 {
2587         SSL_CTX *ssl_ctx = data->ssl;
2588         X509_STORE *store;
2589
2590         /*
2591          * Remove previously configured trusted CA certificates before adding
2592          * new ones.
2593          */
2594         store = X509_STORE_new();
2595         if (store == NULL) {
2596                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2597                            "certificate store", __func__);
2598                 return -1;
2599         }
2600         SSL_CTX_set_cert_store(ssl_ctx, store);
2601
2602         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2603         conn->ca_cert_verify = 1;
2604
2605         if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
2606                 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
2607                            "chain");
2608                 conn->cert_probe = 1;
2609                 conn->ca_cert_verify = 0;
2610                 return 0;
2611         }
2612
2613         if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
2614 #ifdef CONFIG_SHA256
2615                 const char *pos = ca_cert + 7;
2616                 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
2617                         wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
2618                                    "hash value '%s'", ca_cert);
2619                         return -1;
2620                 }
2621                 pos += 14;
2622                 if (os_strlen(pos) != 32 * 2) {
2623                         wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
2624                                    "hash length in ca_cert '%s'", ca_cert);
2625                         return -1;
2626                 }
2627                 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
2628                         wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
2629                                    "value in ca_cert '%s'", ca_cert);
2630                         return -1;
2631                 }
2632                 conn->server_cert_only = 1;
2633                 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
2634                            "certificate match");
2635                 return 0;
2636 #else /* CONFIG_SHA256 */
2637                 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
2638                            "cannot validate server certificate hash");
2639                 return -1;
2640 #endif /* CONFIG_SHA256 */
2641         }
2642
2643         if (ca_cert_blob) {
2644                 X509 *cert = d2i_X509(NULL,
2645                                       (const unsigned char **) &ca_cert_blob,
2646                                       ca_cert_blob_len);
2647                 if (cert == NULL) {
2648                         BIO *bio = BIO_new_mem_buf(ca_cert_blob,
2649                                                    ca_cert_blob_len);
2650
2651                         if (bio) {
2652                                 cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2653                                 BIO_free(bio);
2654                         }
2655
2656                         if (!cert) {
2657                                 tls_show_errors(MSG_WARNING, __func__,
2658                                                 "Failed to parse ca_cert_blob");
2659                                 return -1;
2660                         }
2661
2662                         while (ERR_get_error()) {
2663                                 /* Ignore errors from DER conversion. */
2664                         }
2665                 }
2666
2667                 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
2668                                          cert)) {
2669                         unsigned long err = ERR_peek_error();
2670                         tls_show_errors(MSG_WARNING, __func__,
2671                                         "Failed to add ca_cert_blob to "
2672                                         "certificate store");
2673                         if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2674                             ERR_GET_REASON(err) ==
2675                             X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2676                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
2677                                            "cert already in hash table error",
2678                                            __func__);
2679                         } else {
2680                                 X509_free(cert);
2681                                 return -1;
2682                         }
2683                 }
2684                 X509_free(cert);
2685                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
2686                            "to certificate store", __func__);
2687                 return 0;
2688         }
2689
2690 #ifdef ANDROID
2691         /* Single alias */
2692         if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
2693                 if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
2694                                              &ca_cert[11]) < 0)
2695                         return -1;
2696                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2697                 return 0;
2698         }
2699
2700         /* Multiple aliases separated by space */
2701         if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
2702                 char *aliases = os_strdup(&ca_cert[12]);
2703                 const char *delim = " ";
2704                 int rc = 0;
2705                 char *savedptr;
2706                 char *alias;
2707
2708                 if (!aliases)
2709                         return -1;
2710                 alias = strtok_r(aliases, delim, &savedptr);
2711                 for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
2712                         if (tls_add_ca_from_keystore_encoded(
2713                                     SSL_CTX_get_cert_store(ssl_ctx), alias)) {
2714                                 wpa_printf(MSG_WARNING,
2715                                            "OpenSSL: %s - Failed to add ca_cert %s from keystore",
2716                                            __func__, alias);
2717                                 rc = -1;
2718                                 break;
2719                         }
2720                 }
2721                 os_free(aliases);
2722                 if (rc)
2723                         return rc;
2724
2725                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2726                 return 0;
2727         }
2728 #endif /* ANDROID */
2729
2730 #ifdef CONFIG_NATIVE_WINDOWS
2731         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
2732             0) {
2733                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
2734                            "system certificate store");
2735                 return 0;
2736         }
2737 #endif /* CONFIG_NATIVE_WINDOWS */
2738
2739         if (ca_cert || ca_path) {
2740 #ifndef OPENSSL_NO_STDIO
2741                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
2742                     1) {
2743                         tls_show_errors(MSG_WARNING, __func__,
2744                                         "Failed to load root certificates");
2745                         if (ca_cert &&
2746                             tls_load_ca_der(data, ca_cert) == 0) {
2747                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
2748                                            "DER format CA certificate",
2749                                            __func__);
2750                         } else
2751                                 return -1;
2752                 } else {
2753                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2754                                    "certificate(s) loaded");
2755                         tls_get_errors(data);
2756                 }
2757 #else /* OPENSSL_NO_STDIO */
2758                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2759                            __func__);
2760                 return -1;
2761 #endif /* OPENSSL_NO_STDIO */
2762         } else {
2763                 /* No ca_cert configured - do not try to verify server
2764                  * certificate */
2765                 conn->ca_cert_verify = 0;
2766         }
2767
2768         return 0;
2769 }
2770
2771
2772 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
2773 {
2774         SSL_CTX *ssl_ctx = data->ssl;
2775
2776         if (ca_cert) {
2777                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
2778                 {
2779                         tls_show_errors(MSG_WARNING, __func__,
2780                                         "Failed to load root certificates");
2781                         return -1;
2782                 }
2783
2784                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
2785                            "certificate(s) loaded");
2786
2787 #ifndef OPENSSL_NO_STDIO
2788                 /* Add the same CAs to the client certificate requests */
2789                 SSL_CTX_set_client_CA_list(ssl_ctx,
2790                                            SSL_load_client_CA_file(ca_cert));
2791 #endif /* OPENSSL_NO_STDIO */
2792
2793                 os_free(data->ca_cert);
2794                 data->ca_cert = os_strdup(ca_cert);
2795         }
2796
2797         return 0;
2798 }
2799
2800
2801 int tls_global_set_verify(void *ssl_ctx, int check_crl, int strict)
2802 {
2803         int flags;
2804
2805         if (check_crl) {
2806                 struct tls_data *data = ssl_ctx;
2807                 X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
2808                 if (cs == NULL) {
2809                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
2810                                         "certificate store when enabling "
2811                                         "check_crl");
2812                         return -1;
2813                 }
2814                 flags = X509_V_FLAG_CRL_CHECK;
2815                 if (check_crl == 2)
2816                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
2817                 X509_STORE_set_flags(cs, flags);
2818
2819                 data->check_crl = check_crl;
2820                 data->check_crl_strict = strict;
2821                 os_get_reltime(&data->crl_last_reload);
2822         }
2823         return 0;
2824 }
2825
2826
2827 static int tls_connection_set_subject_match(struct tls_connection *conn,
2828                                             const char *subject_match,
2829                                             const char *altsubject_match,
2830                                             const char *suffix_match,
2831                                             const char *domain_match,
2832                                             const char *check_cert_subject)
2833 {
2834         os_free(conn->subject_match);
2835         conn->subject_match = NULL;
2836         if (subject_match) {
2837                 conn->subject_match = os_strdup(subject_match);
2838                 if (conn->subject_match == NULL)
2839                         return -1;
2840         }
2841
2842         os_free(conn->altsubject_match);
2843         conn->altsubject_match = NULL;
2844         if (altsubject_match) {
2845                 conn->altsubject_match = os_strdup(altsubject_match);
2846                 if (conn->altsubject_match == NULL)
2847                         return -1;
2848         }
2849
2850         os_free(conn->suffix_match);
2851         conn->suffix_match = NULL;
2852         if (suffix_match) {
2853                 conn->suffix_match = os_strdup(suffix_match);
2854                 if (conn->suffix_match == NULL)
2855                         return -1;
2856         }
2857
2858         os_free(conn->domain_match);
2859         conn->domain_match = NULL;
2860         if (domain_match) {
2861                 conn->domain_match = os_strdup(domain_match);
2862                 if (conn->domain_match == NULL)
2863                         return -1;
2864         }
2865
2866         os_free(conn->check_cert_subject);
2867         conn->check_cert_subject = NULL;
2868         if (check_cert_subject) {
2869                 conn->check_cert_subject = os_strdup(check_cert_subject);
2870                 if (!conn->check_cert_subject)
2871                         return -1;
2872         }
2873
2874         return 0;
2875 }
2876
2877
2878 #ifdef CONFIG_SUITEB
2879 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2880 static int suiteb_cert_cb(SSL *ssl, void *arg)
2881 {
2882         struct tls_connection *conn = arg;
2883
2884         /*
2885          * This cert_cb() is not really the best location for doing a
2886          * constraint check for the ServerKeyExchange message, but this seems to
2887          * be the only place where the current OpenSSL sequence can be
2888          * terminated cleanly with an TLS alert going out to the server.
2889          */
2890
2891         if (!(conn->flags & TLS_CONN_SUITEB))
2892                 return 1;
2893
2894         /* DHE is enabled only with DHE-RSA-AES256-GCM-SHA384 */
2895         if (conn->cipher_suite != 0x9f)
2896                 return 1;
2897
2898         if (conn->server_dh_prime_len >= 3072)
2899                 return 1;
2900
2901         wpa_printf(MSG_DEBUG,
2902                    "OpenSSL: Server DH prime length (%d bits) not sufficient for Suite B RSA - reject handshake",
2903                    conn->server_dh_prime_len);
2904         return 0;
2905 }
2906 #endif /* OPENSSL_VERSION_NUMBER */
2907 #endif /* CONFIG_SUITEB */
2908
2909
2910 static int tls_set_conn_flags(struct tls_connection *conn, unsigned int flags,
2911                               const char *openssl_ciphers)
2912 {
2913         SSL *ssl = conn->ssl;
2914
2915 #ifdef SSL_OP_NO_TICKET
2916         if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
2917                 SSL_set_options(ssl, SSL_OP_NO_TICKET);
2918         else
2919                 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
2920 #endif /* SSL_OP_NO_TICKET */
2921
2922 #ifdef SSL_OP_NO_TLSv1
2923         if (flags & TLS_CONN_DISABLE_TLSv1_0)
2924                 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2925         else
2926                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
2927 #endif /* SSL_OP_NO_TLSv1 */
2928 #ifdef SSL_OP_NO_TLSv1_1
2929         if (flags & TLS_CONN_DISABLE_TLSv1_1)
2930                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2931         else
2932                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
2933 #endif /* SSL_OP_NO_TLSv1_1 */
2934 #ifdef SSL_OP_NO_TLSv1_2
2935         if (flags & TLS_CONN_DISABLE_TLSv1_2)
2936                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
2937         else
2938                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
2939 #endif /* SSL_OP_NO_TLSv1_2 */
2940 #ifdef SSL_OP_NO_TLSv1_3
2941         if (flags & TLS_CONN_DISABLE_TLSv1_3)
2942                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_3);
2943         else
2944                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_3);
2945 #endif /* SSL_OP_NO_TLSv1_3 */
2946 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
2947         if (flags & (TLS_CONN_ENABLE_TLSv1_0 |
2948                      TLS_CONN_ENABLE_TLSv1_1 |
2949                      TLS_CONN_ENABLE_TLSv1_2)) {
2950                 int version = 0;
2951
2952                 /* Explicit request to enable TLS versions even if needing to
2953                  * override systemwide policies. */
2954                 if (flags & TLS_CONN_ENABLE_TLSv1_0) {
2955                         version = TLS1_VERSION;
2956                 } else if (flags & TLS_CONN_ENABLE_TLSv1_1) {
2957                         if (!(flags & TLS_CONN_DISABLE_TLSv1_0))
2958                                 version = TLS1_1_VERSION;
2959                 } else if (flags & TLS_CONN_ENABLE_TLSv1_2) {
2960                         if (!(flags & (TLS_CONN_DISABLE_TLSv1_0 |
2961                                        TLS_CONN_DISABLE_TLSv1_1)))
2962                                 version = TLS1_2_VERSION;
2963                 }
2964                 if (!version) {
2965                         wpa_printf(MSG_DEBUG,
2966                                    "OpenSSL: Invalid TLS version configuration");
2967                         return -1;
2968                 }
2969
2970                 if (SSL_set_min_proto_version(ssl, version) != 1) {
2971                         wpa_printf(MSG_DEBUG,
2972                                    "OpenSSL: Failed to set minimum TLS version");
2973                         return -1;
2974                 }
2975         }
2976 #endif /* >= 1.1.0 */
2977
2978 #ifdef CONFIG_SUITEB
2979 #ifdef OPENSSL_IS_BORINGSSL
2980         /* Start with defaults from BoringSSL */
2981         SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, NULL, 0);
2982 #endif /* OPENSSL_IS_BORINGSSL */
2983 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2984         if (flags & TLS_CONN_SUITEB_NO_ECDH) {
2985                 const char *ciphers = "DHE-RSA-AES256-GCM-SHA384";
2986
2987                 if (openssl_ciphers) {
2988                         wpa_printf(MSG_DEBUG,
2989                                    "OpenSSL: Override ciphers for Suite B (no ECDH): %s",
2990                                    openssl_ciphers);
2991                         ciphers = openssl_ciphers;
2992                 }
2993                 if (SSL_set_cipher_list(ssl, ciphers) != 1) {
2994                         wpa_printf(MSG_INFO,
2995                                    "OpenSSL: Failed to set Suite B ciphers");
2996                         return -1;
2997                 }
2998         } else if (flags & TLS_CONN_SUITEB) {
2999                 EC_KEY *ecdh;
3000                 const char *ciphers =
3001                         "ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384";
3002                 int nid[1] = { NID_secp384r1 };
3003
3004                 if (openssl_ciphers) {
3005                         wpa_printf(MSG_DEBUG,
3006                                    "OpenSSL: Override ciphers for Suite B: %s",
3007                                    openssl_ciphers);
3008                         ciphers = openssl_ciphers;
3009                 }
3010                 if (SSL_set_cipher_list(ssl, ciphers) != 1) {
3011                         wpa_printf(MSG_INFO,
3012                                    "OpenSSL: Failed to set Suite B ciphers");
3013                         return -1;
3014                 }
3015
3016                 if (SSL_set1_curves(ssl, nid, 1) != 1) {
3017                         wpa_printf(MSG_INFO,
3018                                    "OpenSSL: Failed to set Suite B curves");
3019                         return -1;
3020                 }
3021
3022                 ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
3023                 if (!ecdh || SSL_set_tmp_ecdh(ssl, ecdh) != 1) {
3024                         EC_KEY_free(ecdh);
3025                         wpa_printf(MSG_INFO,
3026                                    "OpenSSL: Failed to set ECDH parameter");
3027                         return -1;
3028                 }
3029                 EC_KEY_free(ecdh);
3030         }
3031         if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
3032 #ifdef OPENSSL_IS_BORINGSSL
3033                 uint16_t sigalgs[1] = { SSL_SIGN_RSA_PKCS1_SHA384 };
3034
3035                 if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
3036                                                        1) != 1) {
3037                         wpa_printf(MSG_INFO,
3038                                    "OpenSSL: Failed to set Suite B sigalgs");
3039                         return -1;
3040                 }
3041 #else /* OPENSSL_IS_BORINGSSL */
3042                 /* ECDSA+SHA384 if need to add EC support here */
3043                 if (SSL_set1_sigalgs_list(ssl, "RSA+SHA384") != 1) {
3044                         wpa_printf(MSG_INFO,
3045                                    "OpenSSL: Failed to set Suite B sigalgs");
3046                         return -1;
3047                 }
3048 #endif /* OPENSSL_IS_BORINGSSL */
3049
3050                 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
3051                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
3052                 SSL_set_cert_cb(ssl, suiteb_cert_cb, conn);
3053         }
3054 #else /* OPENSSL_VERSION_NUMBER < 0x10002000L */
3055         if (flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) {
3056                 wpa_printf(MSG_ERROR,
3057                            "OpenSSL: Suite B RSA case not supported with this OpenSSL version");
3058                 return -1;
3059         }
3060 #endif /* OPENSSL_VERSION_NUMBER */
3061
3062 #ifdef OPENSSL_IS_BORINGSSL
3063         if (openssl_ciphers && os_strcmp(openssl_ciphers, "SUITEB192") == 0) {
3064                 uint16_t sigalgs[1] = { SSL_SIGN_ECDSA_SECP384R1_SHA384 };
3065                 int nid[1] = { NID_secp384r1 };
3066
3067                 if (SSL_set1_curves(ssl, nid, 1) != 1) {
3068                         wpa_printf(MSG_INFO,
3069                                    "OpenSSL: Failed to set Suite B curves");
3070                         return -1;
3071                 }
3072
3073                 if (SSL_CTX_set_verify_algorithm_prefs(conn->ssl_ctx, sigalgs,
3074                                                        1) != 1) {
3075                         wpa_printf(MSG_INFO,
3076                                    "OpenSSL: Failed to set Suite B sigalgs");
3077                         return -1;
3078                 }
3079         }
3080 #else /* OPENSSL_IS_BORINGSSL */
3081         if (!(flags & (TLS_CONN_SUITEB | TLS_CONN_SUITEB_NO_ECDH)) &&
3082             openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3083                 wpa_printf(MSG_INFO,
3084                            "OpenSSL: Failed to set openssl_ciphers '%s'",
3085                            openssl_ciphers);
3086                 return -1;
3087         }
3088 #endif /* OPENSSL_IS_BORINGSSL */
3089 #else /* CONFIG_SUITEB */
3090         if (openssl_ciphers && SSL_set_cipher_list(ssl, openssl_ciphers) != 1) {
3091                 wpa_printf(MSG_INFO,
3092                            "OpenSSL: Failed to set openssl_ciphers '%s'",
3093                            openssl_ciphers);
3094                 return -1;
3095         }
3096 #endif /* CONFIG_SUITEB */
3097
3098         if (flags & TLS_CONN_TEAP_ANON_DH) {
3099 #ifndef TEAP_DH_ANON_CS
3100 #define TEAP_DH_ANON_CS \
3101         "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:" \
3102         "ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:" \
3103         "ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:" \
3104         "DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:" \
3105         "DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:" \
3106         "DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:" \
3107         "ADH-AES256-GCM-SHA384:ADH-AES128-GCM-SHA256:" \
3108         "ADH-AES256-SHA256:ADH-AES128-SHA256:ADH-AES256-SHA:ADH-AES128-SHA"
3109 #endif
3110                 static const char *cs = TEAP_DH_ANON_CS;
3111
3112 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3113         !defined(LIBRESSL_VERSION_NUMBER) && \
3114         !defined(OPENSSL_IS_BORINGSSL)
3115                 /*
3116                  * Need to drop to security level 0 to allow anonymous
3117                  * cipher suites for EAP-TEAP.
3118                  */
3119                 SSL_set_security_level(conn->ssl, 0);
3120 #endif
3121
3122                 wpa_printf(MSG_DEBUG,
3123                            "OpenSSL: Enable cipher suites for anonymous EAP-TEAP provisioning: %s",
3124                            cs);
3125                 if (SSL_set_cipher_list(conn->ssl, cs) != 1) {
3126                         tls_show_errors(MSG_INFO, __func__,
3127                                         "Cipher suite configuration failed");
3128                         return -1;
3129                 }
3130         }
3131
3132         return 0;
3133 }
3134
3135
3136 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
3137                               int verify_peer, unsigned int flags,
3138                               const u8 *session_ctx, size_t session_ctx_len)
3139 {
3140         static int counter = 0;
3141         struct tls_data *data = ssl_ctx;
3142
3143         if (conn == NULL)
3144                 return -1;
3145
3146         if (verify_peer) {
3147                 conn->ca_cert_verify = 1;
3148                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
3149                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
3150                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
3151         } else {
3152                 conn->ca_cert_verify = 0;
3153                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
3154         }
3155
3156         if (tls_set_conn_flags(conn, flags, NULL) < 0)
3157                 return -1;
3158         conn->flags = flags;
3159
3160         SSL_set_accept_state(conn->ssl);
3161
3162         if (data->tls_session_lifetime == 0) {
3163                 /*
3164                  * Set session id context to a unique value to make sure
3165                  * session resumption cannot be used either through session
3166                  * caching or TLS ticket extension.
3167                  */
3168                 counter++;
3169                 SSL_set_session_id_context(conn->ssl,
3170                                            (const unsigned char *) &counter,
3171                                            sizeof(counter));
3172         } else if (session_ctx) {
3173                 SSL_set_session_id_context(conn->ssl, session_ctx,
3174                                            session_ctx_len);
3175         }
3176
3177         return 0;
3178 }
3179
3180
3181 static int tls_connection_client_cert(struct tls_connection *conn,
3182                                       const char *client_cert,
3183                                       const u8 *client_cert_blob,
3184                                       size_t client_cert_blob_len)
3185 {
3186         if (client_cert == NULL && client_cert_blob == NULL)
3187                 return 0;
3188
3189 #ifdef PKCS12_FUNCS
3190 #if OPENSSL_VERSION_NUMBER < 0x10002000L || defined(LIBRESSL_VERSION_NUMBER)
3191         /*
3192          * Clear previously set extra chain certificates, if any, from PKCS#12
3193          * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
3194          * chain properly.
3195          */
3196         SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
3197 #endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
3198 #endif /* PKCS12_FUNCS */
3199
3200         if (client_cert_blob &&
3201             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
3202                                      client_cert_blob_len) == 1) {
3203                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
3204                            "OK");
3205                 return 0;
3206         } else if (client_cert_blob) {
3207                 tls_show_errors(MSG_DEBUG, __func__,
3208                                 "SSL_use_certificate_ASN1 failed");
3209         }
3210
3211         if (client_cert == NULL)
3212                 return -1;
3213
3214 #ifdef ANDROID
3215         if (os_strncmp("keystore://", client_cert, 11) == 0) {
3216                 BIO *bio = BIO_from_keystore(&client_cert[11]);
3217                 X509 *x509 = NULL;
3218                 int ret = -1;
3219                 if (bio) {
3220                         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3221                 }
3222                 if (x509) {
3223                         if (SSL_use_certificate(conn->ssl, x509) == 1)
3224                                 ret = 0;
3225                         X509_free(x509);
3226                 }
3227
3228                 /* Read additional certificates into the chain. */
3229                 while (bio) {
3230                         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
3231                         if (x509) {
3232                                 /* Takes ownership of x509 */
3233                                 SSL_add0_chain_cert(conn->ssl, x509);
3234                         } else {
3235                                 BIO_free(bio);
3236                                 bio = NULL;
3237                         }
3238                 }
3239                 return ret;
3240         }
3241 #endif /* ANDROID */
3242
3243 #ifndef OPENSSL_NO_STDIO
3244         if (SSL_use_certificate_file(conn->ssl, client_cert,
3245                                      SSL_FILETYPE_ASN1) == 1) {
3246                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
3247                            " --> OK");
3248                 return 0;
3249         }
3250
3251 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
3252         !defined(LIBRESSL_VERSION_NUMBER) && !defined(OPENSSL_IS_BORINGSSL)
3253         if (SSL_use_certificate_chain_file(conn->ssl, client_cert) == 1) {
3254                 ERR_clear_error();
3255                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_chain_file"
3256                            " --> OK");
3257                 return 0;
3258         }
3259 #else
3260         if (SSL_use_certificate_file(conn->ssl, client_cert,
3261                                      SSL_FILETYPE_PEM) == 1) {
3262                 ERR_clear_error();
3263                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
3264                            " --> OK");
3265                 return 0;
3266         }
3267 #endif
3268
3269         tls_show_errors(MSG_DEBUG, __func__,
3270                         "SSL_use_certificate_file failed");
3271 #else /* OPENSSL_NO_STDIO */
3272         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3273 #endif /* OPENSSL_NO_STDIO */
3274
3275         return -1;
3276 }
3277
3278
3279 static int tls_global_client_cert(struct tls_data *data,
3280                                   const char *client_cert)
3281 {
3282 #ifndef OPENSSL_NO_STDIO
3283         SSL_CTX *ssl_ctx = data->ssl;
3284
3285         if (client_cert == NULL)
3286                 return 0;
3287
3288         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3289                                          SSL_FILETYPE_ASN1) != 1 &&
3290             SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
3291             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
3292                                          SSL_FILETYPE_PEM) != 1) {
3293                 tls_show_errors(MSG_INFO, __func__,
3294                                 "Failed to load client certificate");
3295                 return -1;
3296         }
3297         return 0;
3298 #else /* OPENSSL_NO_STDIO */
3299         if (client_cert == NULL)
3300                 return 0;
3301         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3302         return -1;
3303 #endif /* OPENSSL_NO_STDIO */
3304 }
3305
3306
3307 #ifdef PKCS12_FUNCS
3308 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
3309                             const char *passwd)
3310 {
3311         EVP_PKEY *pkey;
3312         X509 *cert;
3313         STACK_OF(X509) *certs;
3314         int res = 0;
3315         char buf[256];
3316
3317         pkey = NULL;
3318         cert = NULL;
3319         certs = NULL;
3320         if (!passwd)
3321                 passwd = "";
3322         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
3323                 tls_show_errors(MSG_DEBUG, __func__,
3324                                 "Failed to parse PKCS12 file");
3325                 PKCS12_free(p12);
3326                 return -1;
3327         }
3328         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
3329
3330         if (cert) {
3331                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
3332                                   sizeof(buf));
3333                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
3334                            "subject='%s'", buf);
3335                 if (ssl) {
3336                         if (SSL_use_certificate(ssl, cert) != 1)
3337                                 res = -1;
3338                 } else {
3339                         if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
3340                                 res = -1;
3341                 }
3342                 X509_free(cert);
3343         }
3344
3345         if (pkey) {
3346                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
3347                 if (ssl) {
3348                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
3349                                 res = -1;
3350                 } else {
3351                         if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
3352                                 res = -1;
3353                 }
3354                 EVP_PKEY_free(pkey);
3355         }
3356
3357         if (certs) {
3358 #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
3359                 if (ssl)
3360                         SSL_clear_chain_certs(ssl);
3361                 else
3362                         SSL_CTX_clear_chain_certs(data->ssl);
3363                 while ((cert = sk_X509_pop(certs)) != NULL) {
3364                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
3365                                           sizeof(buf));
3366                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3367                                    " from PKCS12: subject='%s'", buf);
3368                         if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
3369                             (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
3370                                                              cert) != 1)) {
3371                                 tls_show_errors(MSG_DEBUG, __func__,
3372                                                 "Failed to add additional certificate");
3373                                 res = -1;
3374                                 X509_free(cert);
3375                                 break;
3376                         }
3377                         X509_free(cert);
3378                 }
3379                 if (!res) {
3380                         /* Try to continue anyway */
3381                 }
3382                 sk_X509_pop_free(certs, X509_free);
3383 #ifndef OPENSSL_IS_BORINGSSL
3384                 if (ssl)
3385                         res = SSL_build_cert_chain(
3386                                 ssl,
3387                                 SSL_BUILD_CHAIN_FLAG_CHECK |
3388                                 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
3389                 else
3390                         res = SSL_CTX_build_cert_chain(
3391                                 data->ssl,
3392                                 SSL_BUILD_CHAIN_FLAG_CHECK |
3393                                 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
3394                 if (!res) {
3395                         tls_show_errors(MSG_DEBUG, __func__,
3396                                         "Failed to build certificate chain");
3397                 } else if (res == 2) {
3398                         wpa_printf(MSG_DEBUG,
3399                                    "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
3400                 }
3401 #endif /* OPENSSL_IS_BORINGSSL */
3402                 /*
3403                  * Try to continue regardless of result since it is possible for
3404                  * the extra certificates not to be required.
3405                  */
3406                 res = 0;
3407 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
3408                 SSL_CTX_clear_extra_chain_certs(data->ssl);
3409                 while ((cert = sk_X509_pop(certs)) != NULL) {
3410                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
3411                                           sizeof(buf));
3412                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
3413                                    " from PKCS12: subject='%s'", buf);
3414                         /*
3415                          * There is no SSL equivalent for the chain cert - so
3416                          * always add it to the context...
3417                          */
3418                         if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
3419                         {
3420                                 X509_free(cert);
3421                                 res = -1;
3422                                 break;
3423                         }
3424                 }
3425                 sk_X509_pop_free(certs, X509_free);
3426 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
3427         }
3428
3429         PKCS12_free(p12);
3430
3431         if (res < 0)
3432                 tls_get_errors(data);
3433
3434         return res;
3435 }
3436 #endif  /* PKCS12_FUNCS */
3437
3438
3439 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
3440                            const char *private_key, const char *passwd)
3441 {
3442 #ifdef PKCS12_FUNCS
3443         FILE *f;
3444         PKCS12 *p12;
3445
3446         f = fopen(private_key, "rb");
3447         if (f == NULL)
3448                 return -1;
3449
3450         p12 = d2i_PKCS12_fp(f, NULL);
3451         fclose(f);
3452
3453         if (p12 == NULL) {
3454                 tls_show_errors(MSG_INFO, __func__,
3455                                 "Failed to use PKCS#12 file");
3456                 return -1;
3457         }
3458
3459         return tls_parse_pkcs12(data, ssl, p12, passwd);
3460
3461 #else /* PKCS12_FUNCS */
3462         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
3463                    "p12/pfx files");
3464         return -1;
3465 #endif  /* PKCS12_FUNCS */
3466 }
3467
3468
3469 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
3470                                 const u8 *blob, size_t len, const char *passwd)
3471 {
3472 #ifdef PKCS12_FUNCS
3473         PKCS12 *p12;
3474
3475         p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
3476         if (p12 == NULL) {
3477                 tls_show_errors(MSG_INFO, __func__,
3478                                 "Failed to use PKCS#12 blob");
3479                 return -1;
3480         }
3481
3482         return tls_parse_pkcs12(data, ssl, p12, passwd);
3483
3484 #else /* PKCS12_FUNCS */
3485         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
3486                    "p12/pfx blobs");
3487         return -1;
3488 #endif  /* PKCS12_FUNCS */
3489 }
3490
3491
3492 #ifndef OPENSSL_NO_ENGINE
3493 static int tls_engine_get_cert(struct tls_connection *conn,
3494                                const char *cert_id,
3495                                X509 **cert)
3496 {
3497         /* this runs after the private key is loaded so no PIN is required */
3498         struct {
3499                 const char *cert_id;
3500                 X509 *cert;
3501         } params;
3502         params.cert_id = cert_id;
3503         params.cert = NULL;
3504
3505         if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
3506                              0, &params, NULL, 1)) {
3507                 unsigned long err = ERR_get_error();
3508
3509                 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
3510                            " '%s' [%s]", cert_id,
3511                            ERR_error_string(err, NULL));
3512                 if (tls_is_pin_error(err))
3513                         return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
3514                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3515         }
3516         if (!params.cert) {
3517                 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
3518                            " '%s'", cert_id);
3519                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
3520         }
3521         *cert = params.cert;
3522         return 0;
3523 }
3524 #endif /* OPENSSL_NO_ENGINE */
3525
3526
3527 static int tls_connection_engine_client_cert(struct tls_connection *conn,
3528                                              const char *cert_id)
3529 {
3530 #ifndef OPENSSL_NO_ENGINE
3531         X509 *cert;
3532
3533         if (tls_engine_get_cert(conn, cert_id, &cert))
3534                 return -1;
3535
3536         if (!SSL_use_certificate(conn->ssl, cert)) {
3537                 tls_show_errors(MSG_ERROR, __func__,
3538                                 "SSL_use_certificate failed");
3539                 X509_free(cert);
3540                 return -1;
3541         }
3542         X509_free(cert);
3543         wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
3544                    "OK");
3545         return 0;
3546
3547 #else /* OPENSSL_NO_ENGINE */
3548         return -1;
3549 #endif /* OPENSSL_NO_ENGINE */
3550 }
3551
3552
3553 static int tls_connection_engine_ca_cert(struct tls_data *data,
3554                                          struct tls_connection *conn,
3555                                          const char *ca_cert_id)
3556 {
3557 #ifndef OPENSSL_NO_ENGINE
3558         X509 *cert;
3559         SSL_CTX *ssl_ctx = data->ssl;
3560         X509_STORE *store;
3561
3562         if (tls_engine_get_cert(conn, ca_cert_id, &cert))
3563                 return -1;
3564
3565         /* start off the same as tls_connection_ca_cert */
3566         store = X509_STORE_new();
3567         if (store == NULL) {
3568                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
3569                            "certificate store", __func__);
3570                 X509_free(cert);
3571                 return -1;
3572         }
3573         SSL_CTX_set_cert_store(ssl_ctx, store);
3574         if (!X509_STORE_add_cert(store, cert)) {
3575                 unsigned long err = ERR_peek_error();
3576                 tls_show_errors(MSG_WARNING, __func__,
3577                                 "Failed to add CA certificate from engine "
3578                                 "to certificate store");
3579                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
3580                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
3581                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
3582                                    " already in hash table error",
3583                                    __func__);
3584                 } else {
3585                         X509_free(cert);
3586                         return -1;
3587                 }
3588         }
3589         X509_free(cert);
3590         wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
3591                    "to certificate store", __func__);
3592         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
3593         conn->ca_cert_verify = 1;
3594
3595         return 0;
3596
3597 #else /* OPENSSL_NO_ENGINE */
3598         return -1;
3599 #endif /* OPENSSL_NO_ENGINE */
3600 }
3601
3602
3603 static int tls_connection_engine_private_key(struct tls_connection *conn)
3604 {
3605 #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
3606         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
3607                 tls_show_errors(MSG_ERROR, __func__,
3608                                 "ENGINE: cannot use private key for TLS");
3609                 return -1;
3610         }
3611         if (!SSL_check_private_key(conn->ssl)) {
3612                 tls_show_errors(MSG_INFO, __func__,
3613                                 "Private key failed verification");
3614                 return -1;
3615         }
3616         return 0;
3617 #else /* OPENSSL_NO_ENGINE */
3618         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
3619                    "engine support was not compiled in");
3620         return -1;
3621 #endif /* OPENSSL_NO_ENGINE */
3622 }
3623
3624
3625 #ifndef OPENSSL_NO_STDIO
3626 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
3627 {
3628         if (!password)
3629                 return 0;
3630         os_strlcpy(buf, (const char *) password, size);
3631         return os_strlen(buf);
3632 }
3633 #endif /* OPENSSL_NO_STDIO */
3634
3635
3636 static int tls_use_private_key_file(struct tls_data *data, SSL *ssl,
3637                                     const char *private_key,
3638                                     const char *private_key_passwd)
3639 {
3640 #ifndef OPENSSL_NO_STDIO
3641         BIO *bio;
3642         EVP_PKEY *pkey;
3643         int ret;
3644
3645         /* First try ASN.1 (DER). */
3646         bio = BIO_new_file(private_key, "r");
3647         if (!bio)
3648                 return -1;
3649         pkey = d2i_PrivateKey_bio(bio, NULL);
3650         BIO_free(bio);
3651
3652         if (pkey) {
3653                 wpa_printf(MSG_DEBUG, "OpenSSL: %s (DER) --> loaded", __func__);
3654         } else {
3655                 /* Try PEM with the provided password. */
3656                 bio = BIO_new_file(private_key, "r");
3657                 if (!bio)
3658                         return -1;
3659                 pkey = PEM_read_bio_PrivateKey(bio, NULL, tls_passwd_cb,
3660                                                (void *) private_key_passwd);
3661                 BIO_free(bio);
3662                 if (!pkey)
3663                         return -1;
3664                 wpa_printf(MSG_DEBUG, "OpenSSL: %s (PEM) --> loaded", __func__);
3665                 /* Clear errors from the previous failed load. */
3666                 ERR_clear_error();
3667         }
3668
3669         if (ssl)
3670                 ret = SSL_use_PrivateKey(ssl, pkey);
3671         else
3672                 ret = SSL_CTX_use_PrivateKey(data->ssl, pkey);
3673
3674         EVP_PKEY_free(pkey);
3675         return ret == 1 ? 0 : -1;
3676 #else /* OPENSSL_NO_STDIO */
3677         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
3678         return -1;
3679 #endif /* OPENSSL_NO_STDIO */
3680 }
3681
3682
3683 static int tls_connection_private_key(struct tls_data *data,
3684                                       struct tls_connection *conn,
3685                                       const char *private_key,
3686                                       const char *private_key_passwd,
3687                                       const u8 *private_key_blob,
3688                                       size_t private_key_blob_len)
3689 {
3690         int ok;
3691
3692         if (private_key == NULL && private_key_blob == NULL)
3693                 return 0;
3694
3695         ok = 0;
3696         while (private_key_blob) {
3697                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
3698                                             (u8 *) private_key_blob,
3699                                             private_key_blob_len) == 1) {
3700                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3701                                    "ASN1(EVP_PKEY_RSA) --> OK");
3702                         ok = 1;
3703                         break;
3704                 }
3705
3706                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
3707                                             (u8 *) private_key_blob,
3708                                             private_key_blob_len) == 1) {
3709                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
3710                                    "ASN1(EVP_PKEY_DSA) --> OK");
3711                         ok = 1;
3712                         break;
3713                 }
3714
3715                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
3716                                                (u8 *) private_key_blob,
3717                                                private_key_blob_len) == 1) {
3718                         wpa_printf(MSG_DEBUG, "OpenSSL: "
3719                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
3720                         ok = 1;
3721                         break;
3722                 }
3723
3724                 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
3725                                          private_key_blob_len,
3726                                          private_key_passwd) == 0) {
3727                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
3728                                    "OK");
3729                         ok = 1;
3730                         break;
3731                 }
3732
3733                 break;
3734         }
3735
3736         while (!ok && private_key) {
3737                 if (tls_use_private_key_file(data, conn->ssl, private_key,
3738                                              private_key_passwd) == 0) {
3739                         ok = 1;
3740                         break;
3741                 }
3742
3743                 if (tls_read_pkcs12(data, conn->ssl, private_key,
3744                                     private_key_passwd) == 0) {
3745                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
3746                                    "--> OK");
3747                         ok = 1;
3748                         break;
3749                 }
3750
3751                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
3752                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
3753                                    "access certificate store --> OK");
3754                         ok = 1;
3755                         break;
3756                 }
3757
3758                 break;
3759         }
3760
3761         if (!ok) {
3762                 tls_show_errors(MSG_INFO, __func__,
3763                                 "Failed to load private key");
3764                 return -1;
3765         }
3766         ERR_clear_error();
3767
3768         if (!SSL_check_private_key(conn->ssl)) {
3769                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
3770                                 "verification");
3771                 return -1;
3772         }
3773
3774         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
3775         return 0;
3776 }
3777
3778
3779 static int tls_global_private_key(struct tls_data *data,
3780                                   const char *private_key,
3781                                   const char *private_key_passwd)
3782 {
3783         SSL_CTX *ssl_ctx = data->ssl;
3784
3785         if (private_key == NULL)
3786                 return 0;
3787
3788         if (tls_use_private_key_file(data, NULL, private_key,
3789                                      private_key_passwd) &&
3790             tls_read_pkcs12(data, NULL, private_key, private_key_passwd)) {
3791                 tls_show_errors(MSG_INFO, __func__,
3792                                 "Failed to load private key");
3793                 ERR_clear_error();
3794                 return -1;
3795         }
3796         ERR_clear_error();
3797
3798         if (!SSL_CTX_check_private_key(ssl_ctx)) {
3799                 tls_show_errors(MSG_INFO, __func__,
3800                                 "Private key failed verification");
3801                 return -1;
3802         }
3803
3804         return 0;
3805 }
3806
3807
3808 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
3809 {
3810 #ifdef OPENSSL_NO_DH
3811         if (dh_file == NULL)
3812                 return 0;
3813         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3814                    "dh_file specified");
3815         return -1;
3816 #else /* OPENSSL_NO_DH */
3817         DH *dh;
3818         BIO *bio;
3819
3820         /* TODO: add support for dh_blob */
3821         if (dh_file == NULL)
3822                 return 0;
3823         if (conn == NULL)
3824                 return -1;
3825
3826         bio = BIO_new_file(dh_file, "r");
3827         if (bio == NULL) {
3828                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3829                            dh_file, ERR_error_string(ERR_get_error(), NULL));
3830                 return -1;
3831         }
3832         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3833         BIO_free(bio);
3834 #ifndef OPENSSL_NO_DSA
3835         while (dh == NULL) {
3836                 DSA *dsa;
3837                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3838                            " trying to parse as DSA params", dh_file,
3839                            ERR_error_string(ERR_get_error(), NULL));
3840                 bio = BIO_new_file(dh_file, "r");
3841                 if (bio == NULL)
3842                         break;
3843                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3844                 BIO_free(bio);
3845                 if (!dsa) {
3846                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3847                                    "'%s': %s", dh_file,
3848                                    ERR_error_string(ERR_get_error(), NULL));
3849                         break;
3850                 }
3851
3852                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3853                 dh = DSA_dup_DH(dsa);
3854                 DSA_free(dsa);
3855                 if (dh == NULL) {
3856                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3857                                    "params into DH params");
3858                         break;
3859                 }
3860                 break;
3861         }
3862 #endif /* !OPENSSL_NO_DSA */
3863         if (dh == NULL) {
3864                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3865                            "'%s'", dh_file);
3866                 return -1;
3867         }
3868
3869         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
3870                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3871                            "%s", dh_file,
3872                            ERR_error_string(ERR_get_error(), NULL));
3873                 DH_free(dh);
3874                 return -1;
3875         }
3876         DH_free(dh);
3877         return 0;
3878 #endif /* OPENSSL_NO_DH */
3879 }
3880
3881
3882 static int tls_global_dh(struct tls_data *data, const char *dh_file)
3883 {
3884 #ifdef OPENSSL_NO_DH
3885         if (dh_file == NULL)
3886                 return 0;
3887         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
3888                    "dh_file specified");
3889         return -1;
3890 #else /* OPENSSL_NO_DH */
3891         SSL_CTX *ssl_ctx = data->ssl;
3892         DH *dh;
3893         BIO *bio;
3894
3895         /* TODO: add support for dh_blob */
3896         if (dh_file == NULL)
3897                 return 0;
3898         if (ssl_ctx == NULL)
3899                 return -1;
3900
3901         bio = BIO_new_file(dh_file, "r");
3902         if (bio == NULL) {
3903                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
3904                            dh_file, ERR_error_string(ERR_get_error(), NULL));
3905                 return -1;
3906         }
3907         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
3908         BIO_free(bio);
3909 #ifndef OPENSSL_NO_DSA
3910         while (dh == NULL) {
3911                 DSA *dsa;
3912                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
3913                            " trying to parse as DSA params", dh_file,
3914                            ERR_error_string(ERR_get_error(), NULL));
3915                 bio = BIO_new_file(dh_file, "r");
3916                 if (bio == NULL)
3917                         break;
3918                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
3919                 BIO_free(bio);
3920                 if (!dsa) {
3921                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
3922                                    "'%s': %s", dh_file,
3923                                    ERR_error_string(ERR_get_error(), NULL));
3924                         break;
3925                 }
3926
3927                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
3928                 dh = DSA_dup_DH(dsa);
3929                 DSA_free(dsa);
3930                 if (dh == NULL) {
3931                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
3932                                    "params into DH params");
3933                         break;
3934                 }
3935                 break;
3936         }
3937 #endif /* !OPENSSL_NO_DSA */
3938         if (dh == NULL) {
3939                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
3940                            "'%s'", dh_file);
3941                 return -1;
3942         }
3943
3944         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
3945                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
3946                            "%s", dh_file,
3947                            ERR_error_string(ERR_get_error(), NULL));
3948                 DH_free(dh);
3949                 return -1;
3950         }
3951         DH_free(dh);
3952         return 0;
3953 #endif /* OPENSSL_NO_DH */
3954 }
3955
3956
3957 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
3958                               struct tls_random *keys)
3959 {
3960         SSL *ssl;
3961
3962         if (conn == NULL || keys == NULL)
3963                 return -1;
3964         ssl = conn->ssl;
3965         if (ssl == NULL)
3966                 return -1;
3967
3968         os_memset(keys, 0, sizeof(*keys));
3969         keys->client_random = conn->client_random;
3970         keys->client_random_len = SSL_get_client_random(
3971                 ssl, conn->client_random, sizeof(conn->client_random));
3972         keys->server_random = conn->server_random;
3973         keys->server_random_len = SSL_get_server_random(
3974                 ssl, conn->server_random, sizeof(conn->server_random));
3975
3976         return 0;
3977 }
3978
3979
3980 #ifdef OPENSSL_NEED_EAP_FAST_PRF
3981 static int openssl_get_keyblock_size(SSL *ssl)
3982 {
3983 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
3984         (defined(LIBRESSL_VERSION_NUMBER) && \
3985          LIBRESSL_VERSION_NUMBER < 0x20700000L)
3986         const EVP_CIPHER *c;
3987         const EVP_MD *h;
3988         int md_size;
3989
3990         if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
3991             ssl->read_hash == NULL)
3992                 return -1;
3993
3994         c = ssl->enc_read_ctx->cipher;
3995         h = EVP_MD_CTX_md(ssl->read_hash);
3996         if (h)
3997                 md_size = EVP_MD_size(h);
3998         else if (ssl->s3)
3999                 md_size = ssl->s3->tmp.new_mac_secret_size;
4000         else
4001                 return -1;
4002
4003         wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
4004                    "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
4005                    EVP_CIPHER_iv_length(c));
4006         return 2 * (EVP_CIPHER_key_length(c) +
4007                     md_size +
4008                     EVP_CIPHER_iv_length(c));
4009 #else
4010         const SSL_CIPHER *ssl_cipher;
4011         int cipher, digest;
4012         const EVP_CIPHER *c;
4013         const EVP_MD *h;
4014
4015         ssl_cipher = SSL_get_current_cipher(ssl);
4016         if (!ssl_cipher)
4017                 return -1;
4018         cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
4019         digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
4020         wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
4021                    cipher, digest);
4022         if (cipher < 0 || digest < 0)
4023                 return -1;
4024         c = EVP_get_cipherbynid(cipher);
4025         h = EVP_get_digestbynid(digest);
4026         if (!c || !h)
4027                 return -1;
4028
4029         wpa_printf(MSG_DEBUG,
4030                    "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
4031                    EVP_CIPHER_key_length(c), EVP_MD_size(h),
4032                    EVP_CIPHER_iv_length(c));
4033         return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
4034                     EVP_CIPHER_iv_length(c));
4035 #endif
4036 }
4037 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
4038
4039
4040 int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
4041                               const char *label, const u8 *context,
4042                               size_t context_len, u8 *out, size_t out_len)
4043 {
4044         if (!conn ||
4045             SSL_export_keying_material(conn->ssl, out, out_len, label,
4046                                        os_strlen(label), context, context_len,
4047                                        context != NULL) != 1)
4048                 return -1;
4049         return 0;
4050 }
4051
4052
4053 int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
4054                                     u8 *out, size_t out_len)
4055 {
4056 #ifdef OPENSSL_NEED_EAP_FAST_PRF
4057         SSL *ssl;
4058         SSL_SESSION *sess;
4059         u8 *rnd;
4060         int ret = -1;
4061         int skip = 0;
4062         u8 *tmp_out = NULL;
4063         u8 *_out = out;
4064         unsigned char client_random[SSL3_RANDOM_SIZE];
4065         unsigned char server_random[SSL3_RANDOM_SIZE];
4066         unsigned char master_key[64];
4067         size_t master_key_len;
4068         const char *ver;
4069
4070         /*
4071          * TLS library did not support EAP-FAST key generation, so get the
4072          * needed TLS session parameters and use an internal implementation of
4073          * TLS PRF to derive the key.
4074          */
4075
4076         if (conn == NULL)
4077                 return -1;
4078         ssl = conn->ssl;
4079         if (ssl == NULL)
4080                 return -1;
4081         ver = SSL_get_version(ssl);
4082         sess = SSL_get_session(ssl);
4083         if (!ver || !sess)
4084                 return -1;
4085
4086         skip = openssl_get_keyblock_size(ssl);
4087         if (skip < 0)
4088                 return -1;
4089         tmp_out = os_malloc(skip + out_len);
4090         if (!tmp_out)
4091                 return -1;
4092         _out = tmp_out;
4093
4094         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
4095         if (!rnd) {
4096                 os_free(tmp_out);
4097                 return -1;
4098         }
4099
4100         SSL_get_client_random(ssl, client_random, sizeof(client_random));
4101         SSL_get_server_random(ssl, server_random, sizeof(server_random));
4102         master_key_len = SSL_SESSION_get_master_key(sess, master_key,
4103                                                     sizeof(master_key));
4104
4105         os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
4106         os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
4107
4108         if (os_strcmp(ver, "TLSv1.2") == 0) {
4109                 tls_prf_sha256(master_key, master_key_len,
4110                                "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4111                                _out, skip + out_len);
4112                 ret = 0;
4113         } else if (tls_prf_sha1_md5(master_key, master_key_len,
4114                                     "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
4115                                     _out, skip + out_len) == 0) {
4116                 ret = 0;
4117         }
4118         forced_memzero(master_key, sizeof(master_key));
4119         os_free(rnd);
4120         if (ret == 0)
4121                 os_memcpy(out, _out + skip, out_len);
4122         bin_clear_free(tmp_out, skip);
4123
4124         return ret;
4125 #else /* OPENSSL_NEED_EAP_FAST_PRF */
4126         wpa_printf(MSG_ERROR,
4127                    "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
4128         return -1;
4129 #endif /* OPENSSL_NEED_EAP_FAST_PRF */
4130 }
4131
4132
4133 static struct wpabuf *
4134 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data)
4135 {
4136         int res;
4137         struct wpabuf *out_data;
4138
4139         /*
4140          * Give TLS handshake data from the server (if available) to OpenSSL
4141          * for processing.
4142          */
4143         if (in_data && wpabuf_len(in_data) > 0 &&
4144             BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
4145             < 0) {
4146                 tls_show_errors(MSG_INFO, __func__,
4147                                 "Handshake failed - BIO_write");
4148                 return NULL;
4149         }
4150
4151         /* Initiate TLS handshake or continue the existing handshake */
4152         if (conn->server)
4153                 res = SSL_accept(conn->ssl);
4154         else
4155                 res = SSL_connect(conn->ssl);
4156         if (res != 1) {
4157                 int err = SSL_get_error(conn->ssl, res);
4158                 if (err == SSL_ERROR_WANT_READ)
4159                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
4160                                    "more data");
4161                 else if (err == SSL_ERROR_WANT_WRITE)
4162                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
4163                                    "write");
4164                 else {
4165                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
4166                         conn->failed++;
4167                         if (!conn->server && !conn->client_hello_generated) {
4168                                 /* The server would not understand TLS Alert
4169                                  * before ClientHello, so simply terminate
4170                                  * handshake on this type of error case caused
4171                                  * by a likely internal error like no ciphers
4172                                  * available. */
4173                                 wpa_printf(MSG_DEBUG,
4174                                            "OpenSSL: Could not generate ClientHello");
4175                                 conn->write_alerts++;
4176                                 return NULL;
4177                         }
4178                 }
4179         }
4180
4181         if (!conn->server && !conn->failed)
4182                 conn->client_hello_generated = 1;
4183
4184 #ifdef CONFIG_SUITEB
4185         if ((conn->flags & TLS_CONN_SUITEB) && !conn->server &&
4186             os_strncmp(SSL_get_cipher(conn->ssl), "DHE-", 4) == 0 &&
4187             conn->server_dh_prime_len < 3072) {
4188                 struct tls_context *context = conn->context;
4189
4190                 /*
4191                  * This should not be reached since earlier cert_cb should have
4192                  * terminated the handshake. Keep this check here for extra
4193                  * protection if anything goes wrong with the more low-level
4194                  * checks based on having to parse the TLS handshake messages.
4195                  */
4196                 wpa_printf(MSG_DEBUG,
4197                            "OpenSSL: Server DH prime length: %d bits",
4198                            conn->server_dh_prime_len);
4199
4200                 if (context->event_cb) {
4201                         union tls_event_data ev;
4202
4203                         os_memset(&ev, 0, sizeof(ev));
4204                         ev.alert.is_local = 1;
4205                         ev.alert.type = "fatal";
4206                         ev.alert.description = "insufficient security";
4207                         context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
4208                 }
4209                 /*
4210                  * Could send a TLS Alert to the server, but for now, simply
4211                  * terminate handshake.
4212                  */
4213                 conn->failed++;
4214                 conn->write_alerts++;
4215                 return NULL;
4216         }
4217 #endif /* CONFIG_SUITEB */
4218
4219         /* Get the TLS handshake data to be sent to the server */
4220         res = BIO_ctrl_pending(conn->ssl_out);
4221         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
4222         out_data = wpabuf_alloc(res);
4223         if (out_data == NULL) {
4224                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
4225                            "handshake output (%d bytes)", res);
4226                 if (BIO_reset(conn->ssl_out) < 0) {
4227                         tls_show_errors(MSG_INFO, __func__,
4228                                         "BIO_reset failed");
4229                 }
4230                 return NULL;
4231         }
4232         res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
4233                                       res);
4234         if (res < 0) {
4235                 tls_show_errors(MSG_INFO, __func__,
4236                                 "Handshake failed - BIO_read");
4237                 if (BIO_reset(conn->ssl_out) < 0) {
4238                         tls_show_errors(MSG_INFO, __func__,
4239                                         "BIO_reset failed");
4240                 }
4241                 wpabuf_free(out_data);
4242                 return NULL;
4243         }
4244         wpabuf_put(out_data, res);
4245
4246         return out_data;
4247 }
4248
4249
4250 static struct wpabuf *
4251 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
4252 {
4253         struct wpabuf *appl_data;
4254         int res;
4255
4256         appl_data = wpabuf_alloc(max_len + 100);
4257         if (appl_data == NULL)
4258                 return NULL;
4259
4260         res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
4261                        wpabuf_size(appl_data));
4262         if (res < 0) {
4263                 int err = SSL_get_error(conn->ssl, res);
4264                 if (err == SSL_ERROR_WANT_READ ||
4265                     err == SSL_ERROR_WANT_WRITE) {
4266                         wpa_printf(MSG_DEBUG, "SSL: No Application Data "
4267                                    "included");
4268                 } else {
4269                         tls_show_errors(MSG_INFO, __func__,
4270                                         "Failed to read possible "
4271                                         "Application Data");
4272                 }
4273                 wpabuf_free(appl_data);
4274                 return NULL;
4275         }
4276
4277         wpabuf_put(appl_data, res);
4278         wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
4279                             "message", appl_data);
4280
4281         return appl_data;
4282 }
4283
4284
4285 static struct wpabuf *
4286 openssl_connection_handshake(struct tls_connection *conn,
4287                              const struct wpabuf *in_data,
4288                              struct wpabuf **appl_data)
4289 {
4290         struct wpabuf *out_data;
4291
4292         if (appl_data)
4293                 *appl_data = NULL;
4294
4295         out_data = openssl_handshake(conn, in_data);
4296         if (out_data == NULL)
4297                 return NULL;
4298         if (conn->invalid_hb_used) {
4299                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4300                 wpabuf_free(out_data);
4301                 return NULL;
4302         }
4303
4304         if (SSL_is_init_finished(conn->ssl)) {
4305                 wpa_printf(MSG_DEBUG,
4306                            "OpenSSL: Handshake finished - resumed=%d",
4307                            tls_connection_resumed(conn->ssl_ctx, conn));
4308                 if (conn->server) {
4309                         char *buf;
4310                         size_t buflen = 2000;
4311
4312                         buf = os_malloc(buflen);
4313                         if (buf) {
4314                                 if (SSL_get_shared_ciphers(conn->ssl, buf,
4315                                                            buflen)) {
4316                                         buf[buflen - 1] = '\0';
4317                                         wpa_printf(MSG_DEBUG,
4318                                                    "OpenSSL: Shared ciphers: %s",
4319                                                    buf);
4320                                 }
4321                                 os_free(buf);
4322                         }
4323                 }
4324                 if (appl_data && in_data)
4325                         *appl_data = openssl_get_appl_data(conn,
4326                                                            wpabuf_len(in_data));
4327         }
4328
4329         if (conn->invalid_hb_used) {
4330                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4331                 if (appl_data) {
4332                         wpabuf_free(*appl_data);
4333                         *appl_data = NULL;
4334                 }
4335                 wpabuf_free(out_data);
4336                 return NULL;
4337         }
4338
4339         return out_data;
4340 }
4341
4342
4343 struct wpabuf *
4344 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
4345                          const struct wpabuf *in_data,
4346                          struct wpabuf **appl_data)
4347 {
4348         return openssl_connection_handshake(conn, in_data, appl_data);
4349 }
4350
4351
4352 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
4353                                                 struct tls_connection *conn,
4354                                                 const struct wpabuf *in_data,
4355                                                 struct wpabuf **appl_data)
4356 {
4357         conn->server = 1;
4358         return openssl_connection_handshake(conn, in_data, appl_data);
4359 }
4360
4361
4362 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
4363                                        struct tls_connection *conn,
4364                                        const struct wpabuf *in_data)
4365 {
4366         int res;
4367         struct wpabuf *buf;
4368
4369         if (conn == NULL)
4370                 return NULL;
4371
4372         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
4373         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
4374             (res = BIO_reset(conn->ssl_out)) < 0) {
4375                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
4376                 return NULL;
4377         }
4378         res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
4379         if (res < 0) {
4380                 tls_show_errors(MSG_INFO, __func__,
4381                                 "Encryption failed - SSL_write");
4382                 return NULL;
4383         }
4384
4385         /* Read encrypted data to be sent to the server */
4386         buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
4387         if (buf == NULL)
4388                 return NULL;
4389         res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
4390         if (res < 0) {
4391                 tls_show_errors(MSG_INFO, __func__,
4392                                 "Encryption failed - BIO_read");
4393                 wpabuf_free(buf);
4394                 return NULL;
4395         }
4396         wpabuf_put(buf, res);
4397
4398         return buf;
4399 }
4400
4401
4402 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
4403                                        struct tls_connection *conn,
4404                                        const struct wpabuf *in_data)
4405 {
4406         int res;
4407         struct wpabuf *buf;
4408
4409         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
4410         res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
4411                         wpabuf_len(in_data));
4412         if (res < 0) {
4413                 tls_show_errors(MSG_INFO, __func__,
4414                                 "Decryption failed - BIO_write");
4415                 return NULL;
4416         }
4417         if (BIO_reset(conn->ssl_out) < 0) {
4418                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
4419                 return NULL;
4420         }
4421
4422         /* Read decrypted data for further processing */
4423         /*
4424          * Even though we try to disable TLS compression, it is possible that
4425          * this cannot be done with all TLS libraries. Add extra buffer space
4426          * to handle the possibility of the decrypted data being longer than
4427          * input data.
4428          */
4429         buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
4430         if (buf == NULL)
4431                 return NULL;
4432         res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
4433         if (res < 0) {
4434                 tls_show_errors(MSG_INFO, __func__,
4435                                 "Decryption failed - SSL_read");
4436                 wpabuf_free(buf);
4437                 return NULL;
4438         }
4439         wpabuf_put(buf, res);
4440
4441         if (conn->invalid_hb_used) {
4442                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
4443                 wpabuf_free(buf);
4444                 return NULL;
4445         }
4446
4447         return buf;
4448 }
4449
4450
4451 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
4452 {
4453         return conn ? SSL_session_reused(conn->ssl) : 0;
4454 }
4455
4456
4457 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
4458                                    u8 *ciphers)
4459 {
4460         char buf[500], *pos, *end;
4461         u8 *c;
4462         int ret;
4463
4464         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
4465                 return -1;
4466
4467         buf[0] = '\0';
4468         pos = buf;
4469         end = pos + sizeof(buf);
4470
4471         c = ciphers;
4472         while (*c != TLS_CIPHER_NONE) {
4473                 const char *suite;
4474
4475                 switch (*c) {
4476                 case TLS_CIPHER_RC4_SHA:
4477                         suite = "RC4-SHA";
4478                         break;
4479                 case TLS_CIPHER_AES128_SHA:
4480                         suite = "AES128-SHA";
4481                         break;
4482                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
4483                         suite = "DHE-RSA-AES128-SHA";
4484                         break;
4485                 case TLS_CIPHER_ANON_DH_AES128_SHA:
4486                         suite = "ADH-AES128-SHA";
4487                         break;
4488                 case TLS_CIPHER_RSA_DHE_AES256_SHA:
4489                         suite = "DHE-RSA-AES256-SHA";
4490                         break;
4491                 case TLS_CIPHER_AES256_SHA:
4492                         suite = "AES256-SHA";
4493                         break;
4494                 default:
4495                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
4496                                    "cipher selection: %d", *c);
4497                         return -1;
4498                 }
4499                 ret = os_snprintf(pos, end - pos, ":%s", suite);
4500                 if (os_snprintf_error(end - pos, ret))
4501                         break;
4502                 pos += ret;
4503
4504                 c++;
4505         }
4506         if (!buf[0]) {
4507                 wpa_printf(MSG_DEBUG, "OpenSSL: No ciphers listed");
4508                 return -1;
4509         }
4510
4511         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
4512
4513 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
4514 #ifdef EAP_FAST_OR_TEAP
4515         if (os_strstr(buf, ":ADH-")) {
4516                 /*
4517                  * Need to drop to security level 0 to allow anonymous
4518                  * cipher suites for EAP-FAST.
4519                  */
4520                 SSL_set_security_level(conn->ssl, 0);
4521         } else if (SSL_get_security_level(conn->ssl) == 0) {
4522                 /* Force at least security level 1 */
4523                 SSL_set_security_level(conn->ssl, 1);
4524         }
4525 #endif /* EAP_FAST_OR_TEAP */
4526 #endif
4527
4528         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
4529                 tls_show_errors(MSG_INFO, __func__,
4530                                 "Cipher suite configuration failed");
4531                 return -1;
4532         }
4533
4534         return 0;
4535 }
4536
4537
4538 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
4539                     char *buf, size_t buflen)
4540 {
4541         const char *name;
4542         if (conn == NULL || conn->ssl == NULL)
4543                 return -1;
4544
4545         name = SSL_get_version(conn->ssl);
4546         if (name == NULL)
4547                 return -1;
4548
4549         os_strlcpy(buf, name, buflen);
4550         return 0;
4551 }
4552
4553
4554 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
4555                    char *buf, size_t buflen)
4556 {
4557         const char *name;
4558         if (conn == NULL || conn->ssl == NULL)
4559                 return -1;
4560
4561         name = SSL_get_cipher(conn->ssl);
4562         if (name == NULL)
4563                 return -1;
4564
4565         os_strlcpy(buf, name, buflen);
4566         return 0;
4567 }
4568
4569
4570 int tls_connection_enable_workaround(void *ssl_ctx,
4571                                      struct tls_connection *conn)
4572 {
4573         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
4574
4575         return 0;
4576 }
4577
4578
4579 #ifdef EAP_FAST_OR_TEAP
4580 /* ClientHello TLS extensions require a patch to openssl, so this function is
4581  * commented out unless explicitly needed for EAP-FAST in order to be able to
4582  * build this file with unmodified openssl. */
4583 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
4584                                     int ext_type, const u8 *data,
4585                                     size_t data_len)
4586 {
4587         if (conn == NULL || conn->ssl == NULL || ext_type != 35)
4588                 return -1;
4589
4590         if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
4591                                        data_len) != 1)
4592                 return -1;
4593
4594         return 0;
4595 }
4596 #endif /* EAP_FAST_OR_TEAP */
4597
4598
4599 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
4600 {
4601         if (conn == NULL)
4602                 return -1;
4603         return conn->failed;
4604 }
4605
4606
4607 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
4608 {
4609         if (conn == NULL)
4610                 return -1;
4611         return conn->read_alerts;
4612 }
4613
4614
4615 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
4616 {
4617         if (conn == NULL)
4618                 return -1;
4619         return conn->write_alerts;
4620 }
4621
4622
4623 #ifdef HAVE_OCSP
4624
4625 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
4626 {
4627 #ifndef CONFIG_NO_STDOUT_DEBUG
4628         BIO *out;
4629         size_t rlen;
4630         char *txt;
4631         int res;
4632
4633         if (wpa_debug_level > MSG_DEBUG)
4634                 return;
4635
4636         out = BIO_new(BIO_s_mem());
4637         if (!out)
4638                 return;
4639
4640         OCSP_RESPONSE_print(out, rsp, 0);
4641         rlen = BIO_ctrl_pending(out);
4642         txt = os_malloc(rlen + 1);
4643         if (!txt) {
4644                 BIO_free(out);
4645                 return;
4646         }
4647
4648         res = BIO_read(out, txt, rlen);
4649         if (res > 0) {
4650                 txt[res] = '\0';
4651                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
4652         }
4653         os_free(txt);
4654         BIO_free(out);
4655 #endif /* CONFIG_NO_STDOUT_DEBUG */
4656 }
4657
4658
4659 static void debug_print_cert(X509 *cert, const char *title)
4660 {
4661 #ifndef CONFIG_NO_STDOUT_DEBUG
4662         BIO *out;
4663         size_t rlen;
4664         char *txt;
4665         int res;
4666
4667         if (wpa_debug_level > MSG_DEBUG)
4668                 return;
4669
4670         out = BIO_new(BIO_s_mem());
4671         if (!out)
4672                 return;
4673
4674         X509_print(out, cert);
4675         rlen = BIO_ctrl_pending(out);
4676         txt = os_malloc(rlen + 1);
4677         if (!txt) {
4678                 BIO_free(out);
4679                 return;
4680         }
4681
4682         res = BIO_read(out, txt, rlen);
4683         if (res > 0) {
4684                 txt[res] = '\0';
4685                 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
4686         }
4687         os_free(txt);
4688
4689         BIO_free(out);
4690 #endif /* CONFIG_NO_STDOUT_DEBUG */
4691 }
4692
4693
4694 static int ocsp_resp_cb(SSL *s, void *arg)
4695 {
4696         struct tls_connection *conn = arg;
4697         const unsigned char *p;
4698         int len, status, reason, res;
4699         OCSP_RESPONSE *rsp;
4700         OCSP_BASICRESP *basic;
4701         OCSP_CERTID *id;
4702         ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
4703         X509_STORE *store;
4704         STACK_OF(X509) *certs = NULL;
4705
4706         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
4707         if (!p) {
4708                 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
4709                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4710         }
4711
4712         wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
4713
4714         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
4715         if (!rsp) {
4716                 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
4717                 return 0;
4718         }
4719
4720         ocsp_debug_print_resp(rsp);
4721
4722         status = OCSP_response_status(rsp);
4723         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
4724                 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
4725                            status, OCSP_response_status_str(status));
4726                 return 0;
4727         }
4728
4729         basic = OCSP_response_get1_basic(rsp);
4730         if (!basic) {
4731                 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
4732                 return 0;
4733         }
4734
4735         store = SSL_CTX_get_cert_store(conn->ssl_ctx);
4736         if (conn->peer_issuer) {
4737                 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
4738
4739                 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
4740                         tls_show_errors(MSG_INFO, __func__,
4741                                         "OpenSSL: Could not add issuer to certificate store");
4742                 }
4743                 certs = sk_X509_new_null();
4744                 if (certs) {
4745                         X509 *cert;
4746                         cert = X509_dup(conn->peer_issuer);
4747                         if (cert && !sk_X509_push(certs, cert)) {
4748                                 tls_show_errors(
4749                                         MSG_INFO, __func__,
4750                                         "OpenSSL: Could not add issuer to OCSP responder trust store");
4751                                 X509_free(cert);
4752                                 sk_X509_free(certs);
4753                                 certs = NULL;
4754                         }
4755                         if (certs && conn->peer_issuer_issuer) {
4756                                 cert = X509_dup(conn->peer_issuer_issuer);
4757                                 if (cert && !sk_X509_push(certs, cert)) {
4758                                         tls_show_errors(
4759                                                 MSG_INFO, __func__,
4760                                                 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
4761                                         X509_free(cert);
4762                                 }
4763                         }
4764                 }
4765         }
4766
4767         status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
4768         sk_X509_pop_free(certs, X509_free);
4769         if (status <= 0) {
4770                 tls_show_errors(MSG_INFO, __func__,
4771                                 "OpenSSL: OCSP response failed verification");
4772                 OCSP_BASICRESP_free(basic);
4773                 OCSP_RESPONSE_free(rsp);
4774                 return 0;
4775         }
4776
4777         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
4778
4779         if (!conn->peer_cert) {
4780                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
4781                 OCSP_BASICRESP_free(basic);
4782                 OCSP_RESPONSE_free(rsp);
4783                 return 0;
4784         }
4785
4786         if (!conn->peer_issuer) {
4787                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
4788                 OCSP_BASICRESP_free(basic);
4789                 OCSP_RESPONSE_free(rsp);
4790                 return 0;
4791         }
4792
4793         id = OCSP_cert_to_id(EVP_sha256(), conn->peer_cert, conn->peer_issuer);
4794         if (!id) {
4795                 wpa_printf(MSG_DEBUG,
4796                            "OpenSSL: Could not create OCSP certificate identifier (SHA256)");
4797                 OCSP_BASICRESP_free(basic);
4798                 OCSP_RESPONSE_free(rsp);
4799                 return 0;
4800         }
4801
4802         res = OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
4803                                     &this_update, &next_update);
4804         if (!res) {
4805                 OCSP_CERTID_free(id);
4806                 id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
4807                 if (!id) {
4808                         wpa_printf(MSG_DEBUG,
4809                                    "OpenSSL: Could not create OCSP certificate identifier (SHA1)");
4810                         OCSP_BASICRESP_free(basic);
4811                         OCSP_RESPONSE_free(rsp);
4812                         return 0;
4813                 }
4814
4815                 res = OCSP_resp_find_status(basic, id, &status, &reason,
4816                                             &produced_at, &this_update,
4817                                             &next_update);
4818         }
4819
4820         if (!res) {
4821                 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
4822                            (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
4823                            " (OCSP not required)");
4824                 OCSP_CERTID_free(id);
4825                 OCSP_BASICRESP_free(basic);
4826                 OCSP_RESPONSE_free(rsp);
4827                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
4828         }
4829         OCSP_CERTID_free(id);
4830
4831         if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
4832                 tls_show_errors(MSG_INFO, __func__,
4833                                 "OpenSSL: OCSP status times invalid");
4834                 OCSP_BASICRESP_free(basic);
4835                 OCSP_RESPONSE_free(rsp);
4836                 return 0;
4837         }
4838
4839         OCSP_BASICRESP_free(basic);
4840         OCSP_RESPONSE_free(rsp);
4841
4842         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
4843                    OCSP_cert_status_str(status));
4844
4845         if (status == V_OCSP_CERTSTATUS_GOOD)
4846                 return 1;
4847         if (status == V_OCSP_CERTSTATUS_REVOKED)
4848                 return 0;
4849         if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
4850                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
4851                 return 0;
4852         }
4853         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
4854         return 1;
4855 }
4856
4857
4858 static int ocsp_status_cb(SSL *s, void *arg)
4859 {
4860         char *tmp;
4861         char *resp;
4862         size_t len;
4863
4864         if (tls_global->ocsp_stapling_response == NULL) {
4865                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
4866                 return SSL_TLSEXT_ERR_OK;
4867         }
4868
4869         resp = os_readfile(tls_global->ocsp_stapling_response, &len);
4870         if (resp == NULL) {
4871                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
4872                 /* TODO: Build OCSPResponse with responseStatus = internalError
4873                  */
4874                 return SSL_TLSEXT_ERR_OK;
4875         }
4876         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
4877         tmp = OPENSSL_malloc(len);
4878         if (tmp == NULL) {
4879                 os_free(resp);
4880                 return SSL_TLSEXT_ERR_ALERT_FATAL;
4881         }
4882
4883         os_memcpy(tmp, resp, len);
4884         os_free(resp);
4885         SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
4886
4887         return SSL_TLSEXT_ERR_OK;
4888 }
4889
4890 #endif /* HAVE_OCSP */
4891
4892
4893 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
4894                               const struct tls_connection_params *params)
4895 {
4896         struct tls_data *data = tls_ctx;
4897         int ret;
4898         unsigned long err;
4899         int can_pkcs11 = 0;
4900         const char *key_id = params->key_id;
4901         const char *cert_id = params->cert_id;
4902         const char *ca_cert_id = params->ca_cert_id;
4903         const char *engine_id = params->engine ? params->engine_id : NULL;
4904         const char *ciphers;
4905
4906         if (conn == NULL)
4907                 return -1;
4908
4909         if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
4910                 wpa_printf(MSG_INFO,
4911                            "OpenSSL: ocsp=3 not supported");
4912                 return -1;
4913         }
4914
4915         /*
4916          * If the engine isn't explicitly configured, and any of the
4917          * cert/key fields are actually PKCS#11 URIs, then automatically
4918          * use the PKCS#11 ENGINE.
4919          */
4920         if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
4921                 can_pkcs11 = 1;
4922
4923         if (!key_id && params->private_key && can_pkcs11 &&
4924             os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
4925                 can_pkcs11 = 2;
4926                 key_id = params->private_key;
4927         }
4928
4929         if (!cert_id && params->client_cert && can_pkcs11 &&
4930             os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
4931                 can_pkcs11 = 2;
4932                 cert_id = params->client_cert;
4933         }
4934
4935         if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
4936             os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
4937                 can_pkcs11 = 2;
4938                 ca_cert_id = params->ca_cert;
4939         }
4940
4941         /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
4942         if (can_pkcs11 == 2 && !engine_id)
4943                 engine_id = "pkcs11";
4944
4945 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4946 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
4947         if (params->flags & TLS_CONN_EAP_FAST) {
4948                 wpa_printf(MSG_DEBUG,
4949                            "OpenSSL: Use TLSv1_method() for EAP-FAST");
4950                 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
4951                         tls_show_errors(MSG_INFO, __func__,
4952                                         "Failed to set TLSv1_method() for EAP-FAST");
4953                         return -1;
4954                 }
4955         }
4956 #endif
4957 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
4958 #ifdef SSL_OP_NO_TLSv1_3
4959         if (params->flags & TLS_CONN_EAP_FAST) {
4960                 /* Need to disable TLS v1.3 at least for now since OpenSSL 1.1.1
4961                  * refuses to start the handshake with the modified ciphersuite
4962                  * list (no TLS v1.3 ciphersuites included) for EAP-FAST. */
4963                 wpa_printf(MSG_DEBUG, "OpenSSL: Disable TLSv1.3 for EAP-FAST");
4964                 SSL_set_options(conn->ssl, SSL_OP_NO_TLSv1_3);
4965         }
4966 #endif /* SSL_OP_NO_TLSv1_3 */
4967 #endif
4968 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4969
4970         while ((err = ERR_get_error())) {
4971                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
4972                            __func__, ERR_error_string(err, NULL));
4973         }
4974
4975         if (engine_id) {
4976                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
4977                 ret = tls_engine_init(conn, engine_id, params->pin,
4978                                       key_id, cert_id, ca_cert_id);
4979                 if (ret)
4980                         return ret;
4981         }
4982         if (tls_connection_set_subject_match(conn,
4983                                              params->subject_match,
4984                                              params->altsubject_match,
4985                                              params->suffix_match,
4986                                              params->domain_match,
4987                                              params->check_cert_subject))
4988                 return -1;
4989
4990         if (engine_id && ca_cert_id) {
4991                 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
4992                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
4993         } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
4994                                           params->ca_cert_blob,
4995                                           params->ca_cert_blob_len,
4996                                           params->ca_path))
4997                 return -1;
4998
4999         if (engine_id && cert_id) {
5000                 if (tls_connection_engine_client_cert(conn, cert_id))
5001                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
5002         } else if (tls_connection_client_cert(conn, params->client_cert,
5003                                               params->client_cert_blob,
5004                                               params->client_cert_blob_len))
5005                 return -1;
5006
5007         if (engine_id && key_id) {
5008                 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
5009                 if (tls_connection_engine_private_key(conn))
5010                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
5011         } else if (tls_connection_private_key(data, conn,
5012                                               params->private_key,
5013                                               params->private_key_passwd,
5014                                               params->private_key_blob,
5015                                               params->private_key_blob_len)) {
5016                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
5017                            params->private_key);
5018                 return -1;
5019         }
5020
5021         if (tls_connection_dh(conn, params->dh_file)) {
5022                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
5023                            params->dh_file);
5024                 return -1;
5025         }
5026
5027         ciphers = params->openssl_ciphers;
5028 #ifdef CONFIG_SUITEB
5029 #ifdef OPENSSL_IS_BORINGSSL
5030         if (ciphers && os_strcmp(ciphers, "SUITEB192") == 0) {
5031                 /* BoringSSL removed support for SUITEB192, so need to handle
5032                  * this with hardcoded ciphersuite and additional checks for
5033                  * other parameters. */
5034                 ciphers = "ECDHE-ECDSA-AES256-GCM-SHA384";
5035         }
5036 #endif /* OPENSSL_IS_BORINGSSL */
5037 #endif /* CONFIG_SUITEB */
5038         if (ciphers && SSL_set_cipher_list(conn->ssl, ciphers) != 1) {
5039                 wpa_printf(MSG_INFO,
5040                            "OpenSSL: Failed to set cipher string '%s'",
5041                            ciphers);
5042                 return -1;
5043         }
5044
5045         if (!params->openssl_ecdh_curves) {
5046 #ifndef OPENSSL_IS_BORINGSSL
5047 #ifndef OPENSSL_NO_EC
5048 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && \
5049         (OPENSSL_VERSION_NUMBER < 0x10100000L)
5050                 if (SSL_set_ecdh_auto(conn->ssl, 1) != 1) {
5051                         wpa_printf(MSG_INFO,
5052                                    "OpenSSL: Failed to set ECDH curves to auto");
5053                         return -1;
5054                 }
5055 #endif /* >= 1.0.2 && < 1.1.0 */
5056 #endif /* OPENSSL_NO_EC */
5057 #endif /* OPENSSL_IS_BORINGSSL */
5058         } else if (params->openssl_ecdh_curves[0]) {
5059 #if defined(OPENSSL_IS_BORINGSSL) || (OPENSSL_VERSION_NUMBER < 0x10002000L)
5060                 wpa_printf(MSG_INFO,
5061                         "OpenSSL: ECDH configuration nnot supported");
5062                 return -1;
5063 #else /* OPENSSL_IS_BORINGSSL || < 1.0.2 */
5064 #ifndef OPENSSL_NO_EC
5065                 if (SSL_set1_curves_list(conn->ssl,
5066                                          params->openssl_ecdh_curves) != 1) {
5067                         wpa_printf(MSG_INFO,
5068                                    "OpenSSL: Failed to set ECDH curves '%s'",
5069                                    params->openssl_ecdh_curves);
5070                         return -1;
5071                 }
5072 #else /* OPENSSL_NO_EC */
5073                 wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
5074                 return -1;
5075 #endif /* OPENSSL_NO_EC */
5076 #endif /* OPENSSL_IS_BORINGSSL */
5077         }
5078
5079         if (tls_set_conn_flags(conn, params->flags,
5080                                params->openssl_ciphers) < 0)
5081                 return -1;
5082
5083 #ifdef OPENSSL_IS_BORINGSSL
5084         if (params->flags & TLS_CONN_REQUEST_OCSP) {
5085                 SSL_enable_ocsp_stapling(conn->ssl);
5086         }
5087 #else /* OPENSSL_IS_BORINGSSL */
5088 #ifdef HAVE_OCSP
5089         if (params->flags & TLS_CONN_REQUEST_OCSP) {
5090                 SSL_CTX *ssl_ctx = data->ssl;
5091                 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
5092                 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
5093                 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
5094         }
5095 #else /* HAVE_OCSP */
5096         if (params->flags & TLS_CONN_REQUIRE_OCSP) {
5097                 wpa_printf(MSG_INFO,
5098                            "OpenSSL: No OCSP support included - reject configuration");
5099                 return -1;
5100         }
5101         if (params->flags & TLS_CONN_REQUEST_OCSP) {
5102                 wpa_printf(MSG_DEBUG,
5103                            "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
5104         }
5105 #endif /* HAVE_OCSP */
5106 #endif /* OPENSSL_IS_BORINGSSL */
5107
5108         conn->flags = params->flags;
5109
5110         tls_get_errors(data);
5111
5112         return 0;
5113 }
5114
5115
5116 static void openssl_debug_dump_cipher_list(SSL_CTX *ssl_ctx)
5117 {
5118         SSL *ssl;
5119         int i;
5120
5121         ssl = SSL_new(ssl_ctx);
5122         if (!ssl)
5123                 return;
5124
5125         wpa_printf(MSG_DEBUG,
5126                    "OpenSSL: Enabled cipher suites in priority order");
5127         for (i = 0; ; i++) {
5128                 const char *cipher;
5129
5130                 cipher = SSL_get_cipher_list(ssl, i);
5131                 if (!cipher)
5132                         break;
5133                 wpa_printf(MSG_DEBUG, "Cipher %d: %s", i, cipher);
5134         }
5135
5136         SSL_free(ssl);
5137 }
5138
5139
5140 #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(BORINGSSL_API_VERSION)
5141
5142 static const char * openssl_pkey_type_str(const EVP_PKEY *pkey)
5143 {
5144         if (!pkey)
5145                 return "NULL";
5146         switch (EVP_PKEY_type(EVP_PKEY_id(pkey))) {
5147         case EVP_PKEY_RSA:
5148                 return "RSA";
5149         case EVP_PKEY_DSA:
5150                 return "DSA";
5151         case EVP_PKEY_DH:
5152                 return "DH";
5153         case EVP_PKEY_EC:
5154                 return "EC";
5155         }
5156         return "?";
5157 }
5158
5159
5160 static void openssl_debug_dump_certificate(int i, X509 *cert)
5161 {
5162         char buf[256];
5163         EVP_PKEY *pkey;
5164         ASN1_INTEGER *ser;
5165         char serial_num[128];
5166
5167         X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
5168
5169         ser = X509_get_serialNumber(cert);
5170         if (ser)
5171                 wpa_snprintf_hex_uppercase(serial_num, sizeof(serial_num),
5172                                            ASN1_STRING_get0_data(ser),
5173                                            ASN1_STRING_length(ser));
5174         else
5175                 serial_num[0] = '\0';
5176
5177         pkey = X509_get_pubkey(cert);
5178         wpa_printf(MSG_DEBUG, "%d: %s (%s) %s", i, buf,
5179                    openssl_pkey_type_str(pkey), serial_num);
5180         EVP_PKEY_free(pkey);
5181 }
5182
5183
5184 static void openssl_debug_dump_certificates(SSL_CTX *ssl_ctx)
5185 {
5186         STACK_OF(X509) *certs;
5187
5188         wpa_printf(MSG_DEBUG, "OpenSSL: Configured certificate chain");
5189         if (SSL_CTX_get0_chain_certs(ssl_ctx, &certs) == 1) {
5190                 int i;
5191
5192                 for (i = sk_X509_num(certs); i > 0; i--)
5193                         openssl_debug_dump_certificate(i, sk_X509_value(certs,
5194                                                                         i - 1));
5195         }
5196         openssl_debug_dump_certificate(0, SSL_CTX_get0_certificate(ssl_ctx));
5197 }
5198
5199 #endif
5200
5201
5202 static void openssl_debug_dump_certificate_chains(SSL_CTX *ssl_ctx)
5203 {
5204 #if !defined(LIBRESSL_VERSION_NUMBER) && !defined(BORINGSSL_API_VERSION)
5205         int res;
5206
5207         for (res = SSL_CTX_set_current_cert(ssl_ctx, SSL_CERT_SET_FIRST);
5208              res == 1;
5209              res = SSL_CTX_set_current_cert(ssl_ctx, SSL_CERT_SET_NEXT))
5210                 openssl_debug_dump_certificates(ssl_ctx);
5211
5212         SSL_CTX_set_current_cert(ssl_ctx, SSL_CERT_SET_FIRST);
5213 #endif
5214 }
5215
5216
5217 static void openssl_debug_dump_ctx(SSL_CTX *ssl_ctx)
5218 {
5219         openssl_debug_dump_cipher_list(ssl_ctx);
5220         openssl_debug_dump_certificate_chains(ssl_ctx);
5221 }
5222
5223
5224 int tls_global_set_params(void *tls_ctx,
5225                           const struct tls_connection_params *params)
5226 {
5227         struct tls_data *data = tls_ctx;
5228         SSL_CTX *ssl_ctx = data->ssl;
5229         unsigned long err;
5230
5231         while ((err = ERR_get_error())) {
5232                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
5233                            __func__, ERR_error_string(err, NULL));
5234         }
5235
5236         os_free(data->check_cert_subject);
5237         data->check_cert_subject = NULL;
5238         if (params->check_cert_subject) {
5239                 data->check_cert_subject =
5240                         os_strdup(params->check_cert_subject);
5241                 if (!data->check_cert_subject)
5242                         return -1;
5243         }
5244
5245         if (tls_global_ca_cert(data, params->ca_cert) ||
5246             tls_global_client_cert(data, params->client_cert) ||
5247             tls_global_private_key(data, params->private_key,
5248                                    params->private_key_passwd) ||
5249             tls_global_client_cert(data, params->client_cert2) ||
5250             tls_global_private_key(data, params->private_key2,
5251                                    params->private_key_passwd2) ||
5252             tls_global_dh(data, params->dh_file)) {
5253                 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
5254                 return -1;
5255         }
5256
5257         if (params->openssl_ciphers &&
5258             SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
5259                 wpa_printf(MSG_INFO,
5260                            "OpenSSL: Failed to set cipher string '%s'",
5261                            params->openssl_ciphers);
5262                 return -1;
5263         }
5264
5265         if (!params->openssl_ecdh_curves) {
5266 #ifndef OPENSSL_IS_BORINGSSL
5267 #ifndef OPENSSL_NO_EC
5268 #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) && \
5269         (OPENSSL_VERSION_NUMBER < 0x10100000L)
5270                 if (SSL_CTX_set_ecdh_auto(ssl_ctx, 1) != 1) {
5271                         wpa_printf(MSG_INFO,
5272                                    "OpenSSL: Failed to set ECDH curves to auto");
5273                         return -1;
5274                 }
5275 #endif /* >= 1.0.2 && < 1.1.0 */
5276 #endif /* OPENSSL_NO_EC */
5277 #endif /* OPENSSL_IS_BORINGSSL */
5278         } else if (params->openssl_ecdh_curves[0]) {
5279 #if defined(OPENSSL_IS_BORINGSSL) || (OPENSSL_VERSION_NUMBER < 0x10002000L)
5280                 wpa_printf(MSG_INFO,
5281                         "OpenSSL: ECDH configuration nnot supported");
5282                 return -1;
5283 #else /* OPENSSL_IS_BORINGSSL || < 1.0.2 */
5284 #ifndef OPENSSL_NO_EC
5285 #if OPENSSL_VERSION_NUMBER < 0x10100000L
5286                 SSL_CTX_set_ecdh_auto(ssl_ctx, 1);
5287 #endif
5288                 if (SSL_CTX_set1_curves_list(ssl_ctx,
5289                                              params->openssl_ecdh_curves) !=
5290                     1) {
5291                         wpa_printf(MSG_INFO,
5292                                    "OpenSSL: Failed to set ECDH curves '%s'",
5293                                    params->openssl_ecdh_curves);
5294                         return -1;
5295                 }
5296 #else /* OPENSSL_NO_EC */
5297                 wpa_printf(MSG_INFO, "OpenSSL: ECDH not supported");
5298                 return -1;
5299 #endif /* OPENSSL_NO_EC */
5300 #endif /* OPENSSL_IS_BORINGSSL */
5301         }
5302
5303 #ifdef SSL_OP_NO_TICKET
5304         if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
5305                 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
5306         else
5307                 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
5308 #endif /*  SSL_OP_NO_TICKET */
5309
5310 #ifdef HAVE_OCSP
5311         SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
5312         SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
5313         os_free(tls_global->ocsp_stapling_response);
5314         if (params->ocsp_stapling_response)
5315                 tls_global->ocsp_stapling_response =
5316                         os_strdup(params->ocsp_stapling_response);
5317         else
5318                 tls_global->ocsp_stapling_response = NULL;
5319 #endif /* HAVE_OCSP */
5320
5321         openssl_debug_dump_ctx(ssl_ctx);
5322
5323         return 0;
5324 }
5325
5326
5327 #ifdef EAP_FAST_OR_TEAP
5328 /* Pre-shared secred requires a patch to openssl, so this function is
5329  * commented out unless explicitly needed for EAP-FAST in order to be able to
5330  * build this file with unmodified openssl. */
5331
5332 #if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
5333 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
5334                            STACK_OF(SSL_CIPHER) *peer_ciphers,
5335                            const SSL_CIPHER **cipher, void *arg)
5336 #else /* OPENSSL_IS_BORINGSSL */
5337 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
5338                            STACK_OF(SSL_CIPHER) *peer_ciphers,
5339                            SSL_CIPHER **cipher, void *arg)
5340 #endif /* OPENSSL_IS_BORINGSSL */
5341 {
5342         struct tls_connection *conn = arg;
5343         int ret;
5344
5345 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
5346         (defined(LIBRESSL_VERSION_NUMBER) && \
5347          LIBRESSL_VERSION_NUMBER < 0x20700000L)
5348         if (conn == NULL || conn->session_ticket_cb == NULL)
5349                 return 0;
5350
5351         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
5352                                       conn->session_ticket,
5353                                       conn->session_ticket_len,
5354                                       s->s3->client_random,
5355                                       s->s3->server_random, secret);
5356 #else
5357         unsigned char client_random[SSL3_RANDOM_SIZE];
5358         unsigned char server_random[SSL3_RANDOM_SIZE];
5359
5360         if (conn == NULL || conn->session_ticket_cb == NULL)
5361                 return 0;
5362
5363         SSL_get_client_random(s, client_random, sizeof(client_random));
5364         SSL_get_server_random(s, server_random, sizeof(server_random));
5365
5366         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
5367                                       conn->session_ticket,
5368                                       conn->session_ticket_len,
5369                                       client_random,
5370                                       server_random, secret);
5371 #endif
5372
5373         os_free(conn->session_ticket);
5374         conn->session_ticket = NULL;
5375
5376         if (ret <= 0)
5377                 return 0;
5378
5379         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
5380         return 1;
5381 }
5382
5383
5384 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
5385                                      int len, void *arg)
5386 {
5387         struct tls_connection *conn = arg;
5388
5389         if (conn == NULL || conn->session_ticket_cb == NULL)
5390                 return 0;
5391
5392         wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
5393
5394         os_free(conn->session_ticket);
5395         conn->session_ticket = NULL;
5396
5397         wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
5398                     "extension", data, len);
5399
5400         conn->session_ticket = os_memdup(data, len);
5401         if (conn->session_ticket == NULL)
5402                 return 0;
5403
5404         conn->session_ticket_len = len;
5405
5406         return 1;
5407 }
5408 #endif /* EAP_FAST_OR_TEAP */
5409
5410
5411 int tls_connection_set_session_ticket_cb(void *tls_ctx,
5412                                          struct tls_connection *conn,
5413                                          tls_session_ticket_cb cb,
5414                                          void *ctx)
5415 {
5416 #ifdef EAP_FAST_OR_TEAP
5417         conn->session_ticket_cb = cb;
5418         conn->session_ticket_cb_ctx = ctx;
5419
5420         if (cb) {
5421                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
5422                                               conn) != 1)
5423                         return -1;
5424                 SSL_set_session_ticket_ext_cb(conn->ssl,
5425                                               tls_session_ticket_ext_cb, conn);
5426         } else {
5427                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
5428                         return -1;
5429                 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
5430         }
5431
5432         return 0;
5433 #else /* EAP_FAST_OR_TEAP */
5434         return -1;
5435 #endif /* EAP_FAST_OR_TEAP */
5436 }
5437
5438
5439 int tls_get_library_version(char *buf, size_t buf_len)
5440 {
5441 #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
5442         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
5443                            OPENSSL_VERSION_TEXT,
5444                            OpenSSL_version(OPENSSL_VERSION));
5445 #else
5446         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
5447                            OPENSSL_VERSION_TEXT,
5448                            SSLeay_version(SSLEAY_VERSION));
5449 #endif
5450 }
5451
5452
5453 void tls_connection_set_success_data(struct tls_connection *conn,
5454                                      struct wpabuf *data)
5455 {
5456         SSL_SESSION *sess;
5457         struct wpabuf *old;
5458
5459         if (tls_ex_idx_session < 0)
5460                 goto fail;
5461         sess = SSL_get_session(conn->ssl);
5462         if (!sess)
5463                 goto fail;
5464         old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
5465         if (old) {
5466                 wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
5467                            old);
5468                 wpabuf_free(old);
5469         }
5470         if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
5471                 goto fail;
5472
5473         wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
5474         conn->success_data = 1;
5475         return;
5476
5477 fail:
5478         wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
5479         wpabuf_free(data);
5480 }
5481
5482
5483 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
5484 {
5485         wpa_printf(MSG_DEBUG,
5486                    "OpenSSL: Success data accepted for resumed session");
5487         conn->success_data = 1;
5488 }
5489
5490
5491 const struct wpabuf *
5492 tls_connection_get_success_data(struct tls_connection *conn)
5493 {
5494         SSL_SESSION *sess;
5495
5496         if (tls_ex_idx_session < 0 ||
5497             !(sess = SSL_get_session(conn->ssl)))
5498                 return NULL;
5499         return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
5500 }
5501
5502
5503 void tls_connection_remove_session(struct tls_connection *conn)
5504 {
5505         SSL_SESSION *sess;
5506
5507         sess = SSL_get_session(conn->ssl);
5508         if (!sess)
5509                 return;
5510
5511         if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
5512                 wpa_printf(MSG_DEBUG,
5513                            "OpenSSL: Session was not cached");
5514         else
5515                 wpa_printf(MSG_DEBUG,
5516                            "OpenSSL: Removed cached session to disable session resumption");
5517 }
5518
5519
5520 int tls_get_tls_unique(struct tls_connection *conn, u8 *buf, size_t max_len)
5521 {
5522         size_t len;
5523         int reused;
5524
5525         reused = SSL_session_reused(conn->ssl);
5526         if ((conn->server && !reused) || (!conn->server && reused))
5527                 len = SSL_get_peer_finished(conn->ssl, buf, max_len);
5528         else
5529                 len = SSL_get_finished(conn->ssl, buf, max_len);
5530
5531         if (len == 0 || len > max_len)
5532                 return -1;
5533
5534         return len;
5535 }
5536
5537
5538 u16 tls_connection_get_cipher_suite(struct tls_connection *conn)
5539 {
5540         const SSL_CIPHER *cipher;
5541
5542         cipher = SSL_get_current_cipher(conn->ssl);
5543         if (!cipher)
5544                 return 0;
5545 #if OPENSSL_VERSION_NUMBER >= 0x10101000L && !defined(LIBRESSL_VERSION_NUMBER)
5546         return SSL_CIPHER_get_protocol_id(cipher);
5547 #else
5548         return SSL_CIPHER_get_id(cipher) & 0xFFFF;
5549 #endif
5550 }