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