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