Ensure that we call the server_cert_cb, if present, for server certificates
[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 (*server_cert_cb)(int ok_so_far, X509* cert, void *ca_ctx);
134     void *server_cert_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 void debug_print_cert(X509 *cert, const char *title);
1565
1566 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1567 {
1568         char buf[256];
1569         X509 *err_cert;
1570         int err, depth;
1571         SSL *ssl;
1572         struct tls_connection *conn;
1573         struct tls_context *context;
1574         char *match, *altmatch, *suffix_match, *domain_match;
1575         const char *err_str;
1576
1577         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1578         if (!err_cert)
1579                 return 0;
1580
1581     // debug_print_cert(err_cert, "\n\n***** tls_verify_cb:\n");
1582
1583         err = X509_STORE_CTX_get_error(x509_ctx);
1584         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1585         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1586                                          SSL_get_ex_data_X509_STORE_CTX_idx());
1587         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1588
1589         conn = SSL_get_app_data(ssl);
1590         if (conn == NULL)
1591                 return 0;
1592
1593         if (depth == 0)
1594                 conn->peer_cert = err_cert;
1595         else if (depth == 1)
1596                 conn->peer_issuer = err_cert;
1597         else if (depth == 2)
1598                 conn->peer_issuer_issuer = err_cert;
1599
1600         wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb(enter) - preverify_ok=%d "
1601                    "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s' server_cert_cb=%p server_cert_only=%d",
1602                    preverify_ok, err, X509_verify_cert_error_string(err),
1603                conn->ca_cert_verify, depth, buf, conn->server_cert_cb, conn->server_cert_only);
1604
1605
1606         context = conn->context;
1607         match = conn->subject_match;
1608         altmatch = conn->altsubject_match;
1609         suffix_match = conn->suffix_match;
1610         domain_match = conn->domain_match;
1611
1612         if (!preverify_ok && !conn->ca_cert_verify)
1613                 preverify_ok = 1;
1614
1615         if (!preverify_ok && depth > 0 && conn->server_cert_only) {
1616         wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb: allowing cert because depth > 0 && conn->server_cert_only\n");
1617                 preverify_ok = 1;
1618     }
1619         if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
1620             (err == X509_V_ERR_CERT_HAS_EXPIRED ||
1621              err == X509_V_ERR_CERT_NOT_YET_VALID)) {
1622                 wpa_printf(MSG_DEBUG, "tls_verify_cb: OpenSSL: Ignore certificate validity "
1623                            "time mismatch");
1624                 preverify_ok = 1;
1625         }
1626
1627         err_str = X509_verify_cert_error_string(err);
1628
1629 #ifdef CONFIG_SHA256
1630         if (depth == 0) {
1631         if (conn->server_cert_cb) {
1632             preverify_ok = conn->server_cert_cb(preverify_ok, err_cert, conn->server_cert_ctx);
1633             wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb: server_cert_cb returned %d", preverify_ok);
1634         }
1635         if (conn->server_cert_only) {
1636             /*
1637              * Do not require preverify_ok so we can explicity allow otherwise
1638              * invalid pinned server certificates.
1639              */
1640             struct wpabuf *cert;
1641             cert = get_x509_cert(err_cert);
1642             if (!cert) {
1643                 wpa_printf(MSG_DEBUG, "tls_verify_cb: OpenSSL: Could not fetch "
1644                            "server certificate data");
1645                 preverify_ok = 0;
1646             } else {
1647                 u8 hash[32];
1648                 const u8 *addr[1];
1649                 size_t len[1];
1650                 addr[0] = wpabuf_head(cert);
1651                 len[0] = wpabuf_len(cert);
1652                 if (sha256_vector(1, addr, len, hash) < 0 ||
1653                     os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
1654                     err_str = "Server certificate mismatch";
1655                     err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
1656                     preverify_ok = 0;
1657                 } else if (!preverify_ok) {
1658                     /*
1659                      * Certificate matches pinned certificate, allow
1660                      * regardless of other problems.
1661                      */
1662                     wpa_printf(MSG_DEBUG,
1663                                "tls_verify_cb: OpenSSL: Ignore validation issues for a pinned server certificate");
1664                     preverify_ok = 1;
1665                 }
1666                 wpabuf_free(cert);
1667             }
1668         }
1669     }
1670 #endif /* CONFIG_SHA256 */
1671
1672         if (!preverify_ok) {
1673                 wpa_printf(MSG_WARNING, "tls_verify_cb: TLS: Certificate verification failed,"
1674                            " error %d (%s) depth %d for '%s'", err, err_str,
1675                            depth, buf);
1676                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1677                                        err_str, TLS_FAIL_UNSPECIFIED);
1678                 return preverify_ok;
1679         }
1680
1681         wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb(exit) - preverify_ok=%d "
1682                    "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
1683                    preverify_ok, err, err_str,
1684                    conn->ca_cert_verify, depth, buf);
1685         if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1686                 wpa_printf(MSG_WARNING, "tls_verify_cb: TLS: Subject '%s' did not "
1687                            "match with '%s'", buf, match);
1688                 preverify_ok = 0;
1689                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1690                                        "Subject mismatch",
1691                                        TLS_FAIL_SUBJECT_MISMATCH);
1692         } else if (depth == 0 && altmatch &&
1693                    !tls_match_altsubject(err_cert, altmatch)) {
1694                 wpa_printf(MSG_WARNING, "tls_verify_cb: TLS: altSubjectName match "
1695                            "'%s' not found", altmatch);
1696                 preverify_ok = 0;
1697                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1698                                        "AltSubject mismatch",
1699                                        TLS_FAIL_ALTSUBJECT_MISMATCH);
1700         } else if (depth == 0 && suffix_match &&
1701                    !tls_match_suffix(err_cert, suffix_match, 0)) {
1702                 wpa_printf(MSG_WARNING, "tls_verify_cb: TLS: Domain suffix match '%s' not found",
1703                            suffix_match);
1704                 preverify_ok = 0;
1705                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1706                                        "Domain suffix mismatch",
1707                                        TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
1708         } else if (depth == 0 && domain_match &&
1709                    !tls_match_suffix(err_cert, domain_match, 1)) {
1710                 wpa_printf(MSG_WARNING, "tls_verify_cb: TLS: Domain match '%s' not found",
1711                            domain_match);
1712                 preverify_ok = 0;
1713                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1714                                        "Domain mismatch",
1715                                        TLS_FAIL_DOMAIN_MISMATCH);
1716         } else
1717                 openssl_tls_cert_event(conn, err_cert, depth, buf);
1718
1719         if (conn->cert_probe && preverify_ok && depth == 0) {
1720                 wpa_printf(MSG_DEBUG, "tls_verify_cb: OpenSSL: Reject server certificate "
1721                            "on probe-only run");
1722                 preverify_ok = 0;
1723                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
1724                                        "Server certificate chain probe",
1725                                        TLS_FAIL_SERVER_CHAIN_PROBE);
1726         }
1727
1728         if (preverify_ok && context->event_cb != NULL)
1729                 context->event_cb(context->cb_ctx,
1730                                   TLS_CERT_CHAIN_SUCCESS, NULL);
1731
1732         return preverify_ok;
1733 }
1734
1735
1736 #ifndef OPENSSL_NO_STDIO
1737 static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
1738 {
1739         SSL_CTX *ssl_ctx = data->ssl;
1740         X509_LOOKUP *lookup;
1741         int ret = 0;
1742
1743         lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
1744                                        X509_LOOKUP_file());
1745         if (lookup == NULL) {
1746                 tls_show_errors(MSG_WARNING, __func__,
1747                                 "Failed add lookup for X509 store");
1748                 return -1;
1749         }
1750
1751         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1752                 unsigned long err = ERR_peek_error();
1753                 tls_show_errors(MSG_WARNING, __func__,
1754                                 "Failed load CA in DER format");
1755                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1756                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1757                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1758                                    "cert already in hash table error",
1759                                    __func__);
1760                 } else
1761                         ret = -1;
1762         }
1763
1764         return ret;
1765 }
1766 #endif /* OPENSSL_NO_STDIO */
1767
1768
1769 static int tls_connection_ca_cert(struct tls_data *data,
1770                                   struct tls_connection *conn,
1771                                   const char *ca_cert, const u8 *ca_cert_blob,
1772                                   size_t ca_cert_blob_len, const char *ca_path,
1773                                   int (*server_cert_cb)(int ok_so_far, X509* cert, void *ca_ctx),
1774                                   void *server_cert_ctx)
1775 {
1776         SSL_CTX *ssl_ctx = data->ssl;
1777         X509_STORE *store;
1778
1779         /*
1780          * Remove previously configured trusted CA certificates before adding
1781          * new ones.
1782          */
1783         store = X509_STORE_new();
1784         if (store == NULL) {
1785                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1786                            "certificate store", __func__);
1787                 return -1;
1788         }
1789         SSL_CTX_set_cert_store(ssl_ctx, store);
1790
1791         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1792         conn->ca_cert_verify = 1;
1793     conn->server_cert_cb = server_cert_cb;
1794     conn->server_cert_ctx = server_cert_ctx;
1795
1796         if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
1797                 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
1798                            "chain; setting conn->ca_cert_verify=0");
1799                 conn->cert_probe = 1;
1800                 conn->ca_cert_verify = 0;
1801                 return 0;
1802         }
1803
1804         if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
1805 #ifdef CONFIG_SHA256
1806                 const char *pos = ca_cert + 7;
1807                 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
1808                         wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
1809                                    "hash value '%s'", ca_cert);
1810                         return -1;
1811                 }
1812                 pos += 14;
1813                 if (os_strlen(pos) != 32 * 2) {
1814                         wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
1815                                    "hash length in ca_cert '%s'", ca_cert);
1816                         return -1;
1817                 }
1818                 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
1819                         wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
1820                                    "value in ca_cert '%s'", ca_cert);
1821                         return -1;
1822                 }
1823                 conn->server_cert_only = 1;
1824                 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
1825                            "certificate match");
1826                 return 0;
1827 #else /* CONFIG_SHA256 */
1828                 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
1829                            "cannot validate server certificate hash");
1830                 return -1;
1831 #endif /* CONFIG_SHA256 */
1832         }
1833
1834         if (ca_cert_blob) {
1835                 X509 *cert = d2i_X509(NULL,
1836                                       (const unsigned char **) &ca_cert_blob,
1837                                       ca_cert_blob_len);
1838                 if (cert == NULL) {
1839                         tls_show_errors(MSG_WARNING, __func__,
1840                                         "Failed to parse ca_cert_blob");
1841                         return -1;
1842                 }
1843
1844                 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
1845                                          cert)) {
1846                         unsigned long err = ERR_peek_error();
1847                         tls_show_errors(MSG_WARNING, __func__,
1848                                         "Failed to add ca_cert_blob to "
1849                                         "certificate store");
1850                         if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1851                             ERR_GET_REASON(err) ==
1852                             X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1853                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1854                                            "cert already in hash table error",
1855                                            __func__);
1856                         } else {
1857                                 X509_free(cert);
1858                                 return -1;
1859                         }
1860                 }
1861                 X509_free(cert);
1862                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1863                            "to certificate store", __func__);
1864                 return 0;
1865         }
1866
1867 #ifdef ANDROID
1868         if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
1869                 BIO *bio = BIO_from_keystore(&ca_cert[11]);
1870                 STACK_OF(X509_INFO) *stack = NULL;
1871                 stack_index_t i;
1872
1873                 if (bio) {
1874                         stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
1875                         BIO_free(bio);
1876                 }
1877                 if (!stack)
1878                         return -1;
1879
1880                 for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
1881                         X509_INFO *info = sk_X509_INFO_value(stack, i);
1882                         if (info->x509) {
1883                                 X509_STORE_add_cert(ssl_ctx->cert_store,
1884                                                     info->x509);
1885                         }
1886                         if (info->crl) {
1887                                 X509_STORE_add_crl(ssl_ctx->cert_store,
1888                                                    info->crl);
1889                         }
1890                 }
1891                 sk_X509_INFO_pop_free(stack, X509_INFO_free);
1892                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1893                 return 0;
1894         }
1895 #endif /* ANDROID */
1896
1897 #ifdef CONFIG_NATIVE_WINDOWS
1898         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1899             0) {
1900                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1901                            "system certificate store");
1902                 return 0;
1903         }
1904 #endif /* CONFIG_NATIVE_WINDOWS */
1905
1906         if (ca_cert || ca_path) {
1907 #ifndef OPENSSL_NO_STDIO
1908                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1909                     1) {
1910                         tls_show_errors(MSG_WARNING, __func__,
1911                                         "Failed to load root certificates");
1912                         if (ca_cert &&
1913                             tls_load_ca_der(data, ca_cert) == 0) {
1914                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1915                                            "DER format CA certificate",
1916                                            __func__);
1917                         } else
1918                                 return -1;
1919                 } else {
1920                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1921                                    "certificate(s) loaded");
1922                         tls_get_errors(data);
1923                 }
1924 #else /* OPENSSL_NO_STDIO */
1925                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1926                            __func__);
1927                 return -1;
1928 #endif /* OPENSSL_NO_STDIO */
1929         } else {
1930                 /* No ca_cert configured - do not try to verify server
1931                  * certificate */
1932                 wpa_printf(MSG_DEBUG, "OpenSSL: tls_connection_ca_cert: No ca_cert; setting conn->ca_cert_verify=0");
1933                 conn->ca_cert_verify = 0;
1934         }
1935
1936         return 0;
1937 }
1938
1939
1940 static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
1941 {
1942         SSL_CTX *ssl_ctx = data->ssl;
1943
1944         if (ca_cert) {
1945                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1946                 {
1947                         tls_show_errors(MSG_WARNING, __func__,
1948                                         "Failed to load root certificates");
1949                         return -1;
1950                 }
1951
1952                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1953                            "certificate(s) loaded");
1954
1955 #ifndef OPENSSL_NO_STDIO
1956                 /* Add the same CAs to the client certificate requests */
1957                 SSL_CTX_set_client_CA_list(ssl_ctx,
1958                                            SSL_load_client_CA_file(ca_cert));
1959 #endif /* OPENSSL_NO_STDIO */
1960         }
1961
1962         return 0;
1963 }
1964
1965
1966 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1967 {
1968         int flags;
1969
1970         if (check_crl) {
1971                 struct tls_data *data = ssl_ctx;
1972                 X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
1973                 if (cs == NULL) {
1974                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
1975                                         "certificate store when enabling "
1976                                         "check_crl");
1977                         return -1;
1978                 }
1979                 flags = X509_V_FLAG_CRL_CHECK;
1980                 if (check_crl == 2)
1981                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
1982                 X509_STORE_set_flags(cs, flags);
1983         }
1984         return 0;
1985 }
1986
1987
1988 static int tls_connection_set_subject_match(struct tls_connection *conn,
1989                                             const char *subject_match,
1990                                             const char *altsubject_match,
1991                                             const char *suffix_match,
1992                                             const char *domain_match)
1993 {
1994         os_free(conn->subject_match);
1995         conn->subject_match = NULL;
1996         if (subject_match) {
1997                 conn->subject_match = os_strdup(subject_match);
1998                 if (conn->subject_match == NULL)
1999                         return -1;
2000         }
2001
2002         os_free(conn->altsubject_match);
2003         conn->altsubject_match = NULL;
2004         if (altsubject_match) {
2005                 conn->altsubject_match = os_strdup(altsubject_match);
2006                 if (conn->altsubject_match == NULL)
2007                         return -1;
2008         }
2009
2010         os_free(conn->suffix_match);
2011         conn->suffix_match = NULL;
2012         if (suffix_match) {
2013                 conn->suffix_match = os_strdup(suffix_match);
2014                 if (conn->suffix_match == NULL)
2015                         return -1;
2016         }
2017
2018         os_free(conn->domain_match);
2019         conn->domain_match = NULL;
2020         if (domain_match) {
2021                 conn->domain_match = os_strdup(domain_match);
2022                 if (conn->domain_match == NULL)
2023                         return -1;
2024         }
2025
2026         return 0;
2027 }
2028
2029
2030 static void tls_set_conn_flags(SSL *ssl, unsigned int flags)
2031 {
2032 #ifdef SSL_OP_NO_TICKET
2033         if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
2034                 SSL_set_options(ssl, SSL_OP_NO_TICKET);
2035 #ifdef SSL_clear_options
2036         else
2037                 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
2038 #endif /* SSL_clear_options */
2039 #endif /* SSL_OP_NO_TICKET */
2040
2041 #ifdef SSL_OP_NO_TLSv1
2042         if (flags & TLS_CONN_DISABLE_TLSv1_0)
2043                 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
2044         else
2045                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
2046 #endif /* SSL_OP_NO_TLSv1 */
2047 #ifdef SSL_OP_NO_TLSv1_1
2048         if (flags & TLS_CONN_DISABLE_TLSv1_1)
2049                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
2050         else
2051                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
2052 #endif /* SSL_OP_NO_TLSv1_1 */
2053 #ifdef SSL_OP_NO_TLSv1_2
2054         if (flags & TLS_CONN_DISABLE_TLSv1_2)
2055                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
2056         else
2057                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
2058 #endif /* SSL_OP_NO_TLSv1_2 */
2059 }
2060
2061
2062 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
2063                               int verify_peer, unsigned int flags,
2064                               const u8 *session_ctx, size_t session_ctx_len)
2065 {
2066         static int counter = 0;
2067         struct tls_data *data = ssl_ctx;
2068
2069         if (conn == NULL)
2070                 return -1;
2071
2072         if (verify_peer) {
2073                 conn->ca_cert_verify = 1;
2074                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
2075                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
2076                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
2077         } else {
2078                 wpa_printf(MSG_DEBUG, "OpenSSL: tls_connection_set_verify: !verify_peer; setting conn->ca_cert_verify=0");
2079                 conn->ca_cert_verify = 0;
2080                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
2081         }
2082
2083         tls_set_conn_flags(conn->ssl, flags);
2084         conn->flags = flags;
2085
2086         SSL_set_accept_state(conn->ssl);
2087
2088         if (data->tls_session_lifetime == 0) {
2089                 /*
2090                  * Set session id context to a unique value to make sure
2091                  * session resumption cannot be used either through session
2092                  * caching or TLS ticket extension.
2093                  */
2094                 counter++;
2095                 SSL_set_session_id_context(conn->ssl,
2096                                            (const unsigned char *) &counter,
2097                                            sizeof(counter));
2098         } else if (session_ctx) {
2099                 SSL_set_session_id_context(conn->ssl, session_ctx,
2100                                            session_ctx_len);
2101         }
2102
2103         return 0;
2104 }
2105
2106
2107 static int tls_connection_client_cert(struct tls_connection *conn,
2108                                       const char *client_cert,
2109                                       const u8 *client_cert_blob,
2110                                       size_t client_cert_blob_len)
2111 {
2112         if (client_cert == NULL && client_cert_blob == NULL)
2113                 return 0;
2114
2115         if (client_cert_blob &&
2116             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
2117                                      client_cert_blob_len) == 1) {
2118                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
2119                            "OK");
2120                 return 0;
2121         } else if (client_cert_blob) {
2122                 tls_show_errors(MSG_DEBUG, __func__,
2123                                 "SSL_use_certificate_ASN1 failed");
2124         }
2125
2126         if (client_cert == NULL)
2127                 return -1;
2128
2129 #ifdef ANDROID
2130         if (os_strncmp("keystore://", client_cert, 11) == 0) {
2131                 BIO *bio = BIO_from_keystore(&client_cert[11]);
2132                 X509 *x509 = NULL;
2133                 int ret = -1;
2134                 if (bio) {
2135                         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2136                         BIO_free(bio);
2137                 }
2138                 if (x509) {
2139                         if (SSL_use_certificate(conn->ssl, x509) == 1)
2140                                 ret = 0;
2141                         X509_free(x509);
2142                 }
2143                 return ret;
2144         }
2145 #endif /* ANDROID */
2146
2147 #ifndef OPENSSL_NO_STDIO
2148         if (SSL_use_certificate_file(conn->ssl, client_cert,
2149                                      SSL_FILETYPE_ASN1) == 1) {
2150                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2151                            " --> OK");
2152                 return 0;
2153         }
2154
2155         if (SSL_use_certificate_file(conn->ssl, client_cert,
2156                                      SSL_FILETYPE_PEM) == 1) {
2157                 ERR_clear_error();
2158                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2159                            " --> OK");
2160                 return 0;
2161         }
2162
2163         tls_show_errors(MSG_DEBUG, __func__,
2164                         "SSL_use_certificate_file failed");
2165 #else /* OPENSSL_NO_STDIO */
2166         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2167 #endif /* OPENSSL_NO_STDIO */
2168
2169         return -1;
2170 }
2171
2172
2173 static int tls_global_client_cert(struct tls_data *data,
2174                                   const char *client_cert)
2175 {
2176 #ifndef OPENSSL_NO_STDIO
2177         SSL_CTX *ssl_ctx = data->ssl;
2178
2179         if (client_cert == NULL)
2180                 return 0;
2181
2182         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2183                                          SSL_FILETYPE_ASN1) != 1 &&
2184             SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2185             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2186                                          SSL_FILETYPE_PEM) != 1) {
2187                 tls_show_errors(MSG_INFO, __func__,
2188                                 "Failed to load client certificate");
2189                 return -1;
2190         }
2191         return 0;
2192 #else /* OPENSSL_NO_STDIO */
2193         if (client_cert == NULL)
2194                 return 0;
2195         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2196         return -1;
2197 #endif /* OPENSSL_NO_STDIO */
2198 }
2199
2200
2201 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2202 {
2203         if (password == NULL) {
2204                 return 0;
2205         }
2206         os_strlcpy(buf, (char *) password, size);
2207         return os_strlen(buf);
2208 }
2209
2210
2211 #ifdef PKCS12_FUNCS
2212 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
2213                             const char *passwd)
2214 {
2215         EVP_PKEY *pkey;
2216         X509 *cert;
2217         STACK_OF(X509) *certs;
2218         int res = 0;
2219         char buf[256];
2220
2221         pkey = NULL;
2222         cert = NULL;
2223         certs = NULL;
2224         if (!passwd)
2225                 passwd = "";
2226         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2227                 tls_show_errors(MSG_DEBUG, __func__,
2228                                 "Failed to parse PKCS12 file");
2229                 PKCS12_free(p12);
2230                 return -1;
2231         }
2232         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2233
2234         if (cert) {
2235                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2236                                   sizeof(buf));
2237                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2238                            "subject='%s'", buf);
2239                 if (ssl) {
2240                         if (SSL_use_certificate(ssl, cert) != 1)
2241                                 res = -1;
2242                 } else {
2243                         if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
2244                                 res = -1;
2245                 }
2246                 X509_free(cert);
2247         }
2248
2249         if (pkey) {
2250                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2251                 if (ssl) {
2252                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
2253                                 res = -1;
2254                 } else {
2255                         if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
2256                                 res = -1;
2257                 }
2258                 EVP_PKEY_free(pkey);
2259         }
2260
2261         if (certs) {
2262 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2263                 SSL_clear_chain_certs(ssl);
2264                 while ((cert = sk_X509_pop(certs)) != NULL) {
2265                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
2266                                           sizeof(buf));
2267                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2268                                    " from PKCS12: subject='%s'", buf);
2269                         if (SSL_add1_chain_cert(ssl, cert) != 1) {
2270                                 tls_show_errors(MSG_DEBUG, __func__,
2271                                                 "Failed to add additional certificate");
2272                                 res = -1;
2273                                 break;
2274                         }
2275                 }
2276                 if (!res) {
2277                         /* Try to continue anyway */
2278                 }
2279                 sk_X509_free(certs);
2280 #ifndef OPENSSL_IS_BORINGSSL
2281                 res = SSL_build_cert_chain(ssl,
2282                                            SSL_BUILD_CHAIN_FLAG_CHECK |
2283                                            SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2284                 if (!res) {
2285                         tls_show_errors(MSG_DEBUG, __func__,
2286                                         "Failed to build certificate chain");
2287                 } else if (res == 2) {
2288                         wpa_printf(MSG_DEBUG,
2289                                    "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2290                 }
2291 #endif /* OPENSSL_IS_BORINGSSL */
2292                 /*
2293                  * Try to continue regardless of result since it is possible for
2294                  * the extra certificates not to be required.
2295                  */
2296                 res = 0;
2297 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2298 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2299                 SSL_CTX_clear_extra_chain_certs(data->ssl);
2300 #endif /* OPENSSL_VERSION_NUMBER >= 0x10001000L */
2301                 while ((cert = sk_X509_pop(certs)) != NULL) {
2302                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
2303                                           sizeof(buf));
2304                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2305                                    " from PKCS12: subject='%s'", buf);
2306                         /*
2307                          * There is no SSL equivalent for the chain cert - so
2308                          * always add it to the context...
2309                          */
2310                         if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
2311                         {
2312                                 res = -1;
2313                                 break;
2314                         }
2315                 }
2316                 sk_X509_free(certs);
2317 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2318         }
2319
2320         PKCS12_free(p12);
2321
2322         if (res < 0)
2323                 tls_get_errors(data);
2324
2325         return res;
2326 }
2327 #endif  /* PKCS12_FUNCS */
2328
2329
2330 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
2331                            const char *private_key, const char *passwd)
2332 {
2333 #ifdef PKCS12_FUNCS
2334         FILE *f;
2335         PKCS12 *p12;
2336
2337         f = fopen(private_key, "rb");
2338         if (f == NULL)
2339                 return -1;
2340
2341         p12 = d2i_PKCS12_fp(f, NULL);
2342         fclose(f);
2343
2344         if (p12 == NULL) {
2345                 tls_show_errors(MSG_INFO, __func__,
2346                                 "Failed to use PKCS#12 file");
2347                 return -1;
2348         }
2349
2350         return tls_parse_pkcs12(data, ssl, p12, passwd);
2351
2352 #else /* PKCS12_FUNCS */
2353         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2354                    "p12/pfx files");
2355         return -1;
2356 #endif  /* PKCS12_FUNCS */
2357 }
2358
2359
2360 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
2361                                 const u8 *blob, size_t len, const char *passwd)
2362 {
2363 #ifdef PKCS12_FUNCS
2364         PKCS12 *p12;
2365
2366         p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2367         if (p12 == NULL) {
2368                 tls_show_errors(MSG_INFO, __func__,
2369                                 "Failed to use PKCS#12 blob");
2370                 return -1;
2371         }
2372
2373         return tls_parse_pkcs12(data, ssl, p12, passwd);
2374
2375 #else /* PKCS12_FUNCS */
2376         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2377                    "p12/pfx blobs");
2378         return -1;
2379 #endif  /* PKCS12_FUNCS */
2380 }
2381
2382
2383 #ifndef OPENSSL_NO_ENGINE
2384 static int tls_engine_get_cert(struct tls_connection *conn,
2385                                const char *cert_id,
2386                                X509 **cert)
2387 {
2388         /* this runs after the private key is loaded so no PIN is required */
2389         struct {
2390                 const char *cert_id;
2391                 X509 *cert;
2392         } params;
2393         params.cert_id = cert_id;
2394         params.cert = NULL;
2395
2396         if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2397                              0, &params, NULL, 1)) {
2398                 unsigned long err = ERR_get_error();
2399
2400                 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2401                            " '%s' [%s]", cert_id,
2402                            ERR_error_string(err, NULL));
2403                 if (tls_is_pin_error(err))
2404                         return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2405                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2406         }
2407         if (!params.cert) {
2408                 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2409                            " '%s'", cert_id);
2410                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2411         }
2412         *cert = params.cert;
2413         return 0;
2414 }
2415 #endif /* OPENSSL_NO_ENGINE */
2416
2417
2418 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2419                                              const char *cert_id)
2420 {
2421 #ifndef OPENSSL_NO_ENGINE
2422         X509 *cert;
2423
2424         if (tls_engine_get_cert(conn, cert_id, &cert))
2425                 return -1;
2426
2427         if (!SSL_use_certificate(conn->ssl, cert)) {
2428                 tls_show_errors(MSG_ERROR, __func__,
2429                                 "SSL_use_certificate failed");
2430                 X509_free(cert);
2431                 return -1;
2432         }
2433         X509_free(cert);
2434         wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2435                    "OK");
2436         return 0;
2437
2438 #else /* OPENSSL_NO_ENGINE */
2439         return -1;
2440 #endif /* OPENSSL_NO_ENGINE */
2441 }
2442
2443
2444 static int tls_connection_engine_ca_cert(struct tls_data *data,
2445                                          struct tls_connection *conn,
2446                                          const char *ca_cert_id)
2447 {
2448 #ifndef OPENSSL_NO_ENGINE
2449         X509 *cert;
2450         SSL_CTX *ssl_ctx = data->ssl;
2451         X509_STORE *store;
2452
2453         if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2454                 return -1;
2455
2456         /* start off the same as tls_connection_ca_cert */
2457         store = X509_STORE_new();
2458         if (store == NULL) {
2459                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2460                            "certificate store", __func__);
2461                 X509_free(cert);
2462                 return -1;
2463         }
2464         SSL_CTX_set_cert_store(ssl_ctx, store);
2465         if (!X509_STORE_add_cert(store, cert)) {
2466                 unsigned long err = ERR_peek_error();
2467                 tls_show_errors(MSG_WARNING, __func__,
2468                                 "Failed to add CA certificate from engine "
2469                                 "to certificate store");
2470                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2471                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2472                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2473                                    " already in hash table error",
2474                                    __func__);
2475                 } else {
2476                         X509_free(cert);
2477                         return -1;
2478                 }
2479         }
2480         X509_free(cert);
2481         wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2482                    "to certificate store", __func__);
2483         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2484         conn->ca_cert_verify = 1;
2485
2486         return 0;
2487
2488 #else /* OPENSSL_NO_ENGINE */
2489         return -1;
2490 #endif /* OPENSSL_NO_ENGINE */
2491 }
2492
2493
2494 static int tls_connection_engine_private_key(struct tls_connection *conn)
2495 {
2496 #ifndef OPENSSL_NO_ENGINE
2497         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2498                 tls_show_errors(MSG_ERROR, __func__,
2499                                 "ENGINE: cannot use private key for TLS");
2500                 return -1;
2501         }
2502         if (!SSL_check_private_key(conn->ssl)) {
2503                 tls_show_errors(MSG_INFO, __func__,
2504                                 "Private key failed verification");
2505                 return -1;
2506         }
2507         return 0;
2508 #else /* OPENSSL_NO_ENGINE */
2509         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2510                    "engine support was not compiled in");
2511         return -1;
2512 #endif /* OPENSSL_NO_ENGINE */
2513 }
2514
2515
2516 static int tls_connection_private_key(struct tls_data *data,
2517                                       struct tls_connection *conn,
2518                                       const char *private_key,
2519                                       const char *private_key_passwd,
2520                                       const u8 *private_key_blob,
2521                                       size_t private_key_blob_len)
2522 {
2523         SSL_CTX *ssl_ctx = data->ssl;
2524         char *passwd;
2525         int ok;
2526
2527         if (private_key == NULL && private_key_blob == NULL)
2528                 return 0;
2529
2530         if (private_key_passwd) {
2531                 passwd = os_strdup(private_key_passwd);
2532                 if (passwd == NULL)
2533                         return -1;
2534         } else
2535                 passwd = NULL;
2536
2537         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2538         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2539
2540         ok = 0;
2541         while (private_key_blob) {
2542                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2543                                             (u8 *) private_key_blob,
2544                                             private_key_blob_len) == 1) {
2545                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2546                                    "ASN1(EVP_PKEY_RSA) --> OK");
2547                         ok = 1;
2548                         break;
2549                 }
2550
2551                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2552                                             (u8 *) private_key_blob,
2553                                             private_key_blob_len) == 1) {
2554                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2555                                    "ASN1(EVP_PKEY_DSA) --> OK");
2556                         ok = 1;
2557                         break;
2558                 }
2559
2560                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2561                                                (u8 *) private_key_blob,
2562                                                private_key_blob_len) == 1) {
2563                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2564                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
2565                         ok = 1;
2566                         break;
2567                 }
2568
2569                 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
2570                                          private_key_blob_len, passwd) == 0) {
2571                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2572                                    "OK");
2573                         ok = 1;
2574                         break;
2575                 }
2576
2577                 break;
2578         }
2579
2580         while (!ok && private_key) {
2581 #ifndef OPENSSL_NO_STDIO
2582                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2583                                             SSL_FILETYPE_ASN1) == 1) {
2584                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2585                                    "SSL_use_PrivateKey_File (DER) --> OK");
2586                         ok = 1;
2587                         break;
2588                 }
2589
2590                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2591                                             SSL_FILETYPE_PEM) == 1) {
2592                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2593                                    "SSL_use_PrivateKey_File (PEM) --> OK");
2594                         ok = 1;
2595                         break;
2596                 }
2597 #else /* OPENSSL_NO_STDIO */
2598                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2599                            __func__);
2600 #endif /* OPENSSL_NO_STDIO */
2601
2602                 if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
2603                     == 0) {
2604                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2605                                    "--> OK");
2606                         ok = 1;
2607                         break;
2608                 }
2609
2610                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2611                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2612                                    "access certificate store --> OK");
2613                         ok = 1;
2614                         break;
2615                 }
2616
2617                 break;
2618         }
2619
2620         if (!ok) {
2621                 tls_show_errors(MSG_INFO, __func__,
2622                                 "Failed to load private key");
2623                 os_free(passwd);
2624                 return -1;
2625         }
2626         ERR_clear_error();
2627         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2628         os_free(passwd);
2629
2630         if (!SSL_check_private_key(conn->ssl)) {
2631                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2632                                 "verification");
2633                 return -1;
2634         }
2635
2636         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2637         return 0;
2638 }
2639
2640
2641 static int tls_global_private_key(struct tls_data *data,
2642                                   const char *private_key,
2643                                   const char *private_key_passwd)
2644 {
2645         SSL_CTX *ssl_ctx = data->ssl;
2646         char *passwd;
2647
2648         if (private_key == NULL)
2649                 return 0;
2650
2651         if (private_key_passwd) {
2652                 passwd = os_strdup(private_key_passwd);
2653                 if (passwd == NULL)
2654                         return -1;
2655         } else
2656                 passwd = NULL;
2657
2658         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2659         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2660         if (
2661 #ifndef OPENSSL_NO_STDIO
2662             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2663                                         SSL_FILETYPE_ASN1) != 1 &&
2664             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2665                                         SSL_FILETYPE_PEM) != 1 &&
2666 #endif /* OPENSSL_NO_STDIO */
2667             tls_read_pkcs12(data, NULL, private_key, passwd)) {
2668                 tls_show_errors(MSG_INFO, __func__,
2669                                 "Failed to load private key");
2670                 os_free(passwd);
2671                 ERR_clear_error();
2672                 return -1;
2673         }
2674         os_free(passwd);
2675         ERR_clear_error();
2676         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2677
2678         if (!SSL_CTX_check_private_key(ssl_ctx)) {
2679                 tls_show_errors(MSG_INFO, __func__,
2680                                 "Private key failed verification");
2681                 return -1;
2682         }
2683
2684         return 0;
2685 }
2686
2687
2688 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2689 {
2690 #ifdef OPENSSL_NO_DH
2691         if (dh_file == NULL)
2692                 return 0;
2693         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2694                    "dh_file specified");
2695         return -1;
2696 #else /* OPENSSL_NO_DH */
2697         DH *dh;
2698         BIO *bio;
2699
2700         /* TODO: add support for dh_blob */
2701         if (dh_file == NULL)
2702                 return 0;
2703         if (conn == NULL)
2704                 return -1;
2705
2706         bio = BIO_new_file(dh_file, "r");
2707         if (bio == NULL) {
2708                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2709                            dh_file, ERR_error_string(ERR_get_error(), NULL));
2710                 return -1;
2711         }
2712         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2713         BIO_free(bio);
2714 #ifndef OPENSSL_NO_DSA
2715         while (dh == NULL) {
2716                 DSA *dsa;
2717                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2718                            " trying to parse as DSA params", dh_file,
2719                            ERR_error_string(ERR_get_error(), NULL));
2720                 bio = BIO_new_file(dh_file, "r");
2721                 if (bio == NULL)
2722                         break;
2723                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2724                 BIO_free(bio);
2725                 if (!dsa) {
2726                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2727                                    "'%s': %s", dh_file,
2728                                    ERR_error_string(ERR_get_error(), NULL));
2729                         break;
2730                 }
2731
2732                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2733                 dh = DSA_dup_DH(dsa);
2734                 DSA_free(dsa);
2735                 if (dh == NULL) {
2736                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2737                                    "params into DH params");
2738                         break;
2739                 }
2740                 break;
2741         }
2742 #endif /* !OPENSSL_NO_DSA */
2743         if (dh == NULL) {
2744                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2745                            "'%s'", dh_file);
2746                 return -1;
2747         }
2748
2749         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2750                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2751                            "%s", dh_file,
2752                            ERR_error_string(ERR_get_error(), NULL));
2753                 DH_free(dh);
2754                 return -1;
2755         }
2756         DH_free(dh);
2757         return 0;
2758 #endif /* OPENSSL_NO_DH */
2759 }
2760
2761
2762 static int tls_global_dh(struct tls_data *data, const char *dh_file)
2763 {
2764 #ifdef OPENSSL_NO_DH
2765         if (dh_file == NULL)
2766                 return 0;
2767         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2768                    "dh_file specified");
2769         return -1;
2770 #else /* OPENSSL_NO_DH */
2771         SSL_CTX *ssl_ctx = data->ssl;
2772         DH *dh;
2773         BIO *bio;
2774
2775         /* TODO: add support for dh_blob */
2776         if (dh_file == NULL)
2777                 return 0;
2778         if (ssl_ctx == NULL)
2779                 return -1;
2780
2781         bio = BIO_new_file(dh_file, "r");
2782         if (bio == NULL) {
2783                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2784                            dh_file, ERR_error_string(ERR_get_error(), NULL));
2785                 return -1;
2786         }
2787         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2788         BIO_free(bio);
2789 #ifndef OPENSSL_NO_DSA
2790         while (dh == NULL) {
2791                 DSA *dsa;
2792                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2793                            " trying to parse as DSA params", dh_file,
2794                            ERR_error_string(ERR_get_error(), NULL));
2795                 bio = BIO_new_file(dh_file, "r");
2796                 if (bio == NULL)
2797                         break;
2798                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2799                 BIO_free(bio);
2800                 if (!dsa) {
2801                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2802                                    "'%s': %s", dh_file,
2803                                    ERR_error_string(ERR_get_error(), NULL));
2804                         break;
2805                 }
2806
2807                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2808                 dh = DSA_dup_DH(dsa);
2809                 DSA_free(dsa);
2810                 if (dh == NULL) {
2811                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2812                                    "params into DH params");
2813                         break;
2814                 }
2815                 break;
2816         }
2817 #endif /* !OPENSSL_NO_DSA */
2818         if (dh == NULL) {
2819                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2820                            "'%s'", dh_file);
2821                 return -1;
2822         }
2823
2824         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2825                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2826                            "%s", dh_file,
2827                            ERR_error_string(ERR_get_error(), NULL));
2828                 DH_free(dh);
2829                 return -1;
2830         }
2831         DH_free(dh);
2832         return 0;
2833 #endif /* OPENSSL_NO_DH */
2834 }
2835
2836
2837 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
2838                               struct tls_random *keys)
2839 {
2840         SSL *ssl;
2841
2842         if (conn == NULL || keys == NULL)
2843                 return -1;
2844         ssl = conn->ssl;
2845 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2846         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2847                 return -1;
2848
2849         os_memset(keys, 0, sizeof(*keys));
2850         keys->client_random = ssl->s3->client_random;
2851         keys->client_random_len = SSL3_RANDOM_SIZE;
2852         keys->server_random = ssl->s3->server_random;
2853         keys->server_random_len = SSL3_RANDOM_SIZE;
2854 #else
2855         if (ssl == NULL)
2856                 return -1;
2857
2858         os_memset(keys, 0, sizeof(*keys));
2859         keys->client_random = conn->client_random;
2860         keys->client_random_len = SSL_get_client_random(
2861                 ssl, conn->client_random, sizeof(conn->client_random));
2862         keys->server_random = conn->server_random;
2863         keys->server_random_len = SSL_get_server_random(
2864                 ssl, conn->server_random, sizeof(conn->server_random));
2865 #endif
2866
2867         return 0;
2868 }
2869
2870
2871 #ifndef CONFIG_FIPS
2872 static int openssl_get_keyblock_size(SSL *ssl)
2873 {
2874 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2875         const EVP_CIPHER *c;
2876         const EVP_MD *h;
2877         int md_size;
2878
2879         if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2880             ssl->read_hash == NULL)
2881                 return -1;
2882
2883         c = ssl->enc_read_ctx->cipher;
2884 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2885         h = EVP_MD_CTX_md(ssl->read_hash);
2886 #else
2887         h = ssl->read_hash;
2888 #endif
2889         if (h)
2890                 md_size = EVP_MD_size(h);
2891 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2892         else if (ssl->s3)
2893                 md_size = ssl->s3->tmp.new_mac_secret_size;
2894 #endif
2895         else
2896                 return -1;
2897
2898         wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2899                    "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2900                    EVP_CIPHER_iv_length(c));
2901         return 2 * (EVP_CIPHER_key_length(c) +
2902                     md_size +
2903                     EVP_CIPHER_iv_length(c));
2904 #else
2905         const SSL_CIPHER *ssl_cipher;
2906         int cipher, digest;
2907         const EVP_CIPHER *c;
2908         const EVP_MD *h;
2909
2910         ssl_cipher = SSL_get_current_cipher(ssl);
2911         if (!ssl_cipher)
2912                 return -1;
2913         cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
2914         digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
2915         wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
2916                    cipher, digest);
2917         if (cipher < 0 || digest < 0)
2918                 return -1;
2919         c = EVP_get_cipherbynid(cipher);
2920         h = EVP_get_digestbynid(digest);
2921         if (!c || !h)
2922                 return -1;
2923
2924         wpa_printf(MSG_DEBUG,
2925                    "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
2926                    EVP_CIPHER_key_length(c), EVP_MD_size(h),
2927                    EVP_CIPHER_iv_length(c));
2928         return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
2929                     EVP_CIPHER_iv_length(c));
2930 #endif
2931 }
2932 #endif /* CONFIG_FIPS */
2933
2934
2935 static int openssl_tls_prf(struct tls_connection *conn,
2936                            const char *label, int server_random_first,
2937                            int skip_keyblock, u8 *out, size_t out_len)
2938 {
2939 #ifdef CONFIG_FIPS
2940         wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2941                    "mode");
2942         return -1;
2943 #else /* CONFIG_FIPS */
2944 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2945         SSL *ssl;
2946         u8 *rnd;
2947         int ret = -1;
2948         int skip = 0;
2949         u8 *tmp_out = NULL;
2950         u8 *_out = out;
2951         const char *ver;
2952
2953         /*
2954          * TLS library did not support key generation, so get the needed TLS
2955          * session parameters and use an internal implementation of TLS PRF to
2956          * derive the key.
2957          */
2958
2959         if (conn == NULL)
2960                 return -1;
2961         ssl = conn->ssl;
2962         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2963             ssl->session->master_key_length <= 0)
2964                 return -1;
2965         ver = SSL_get_version(ssl);
2966
2967         if (skip_keyblock) {
2968                 skip = openssl_get_keyblock_size(ssl);
2969                 if (skip < 0)
2970                         return -1;
2971                 tmp_out = os_malloc(skip + out_len);
2972                 if (!tmp_out)
2973                         return -1;
2974                 _out = tmp_out;
2975         }
2976
2977         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2978         if (!rnd) {
2979                 os_free(tmp_out);
2980                 return -1;
2981         }
2982
2983         if (server_random_first) {
2984                 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2985                 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2986                         SSL3_RANDOM_SIZE);
2987         } else {
2988                 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2989                 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2990                         SSL3_RANDOM_SIZE);
2991         }
2992
2993         if (os_strcmp(ver, "TLSv1.2") == 0) {
2994                 tls_prf_sha256(ssl->session->master_key,
2995                                ssl->session->master_key_length,
2996                                label, rnd, 2 * SSL3_RANDOM_SIZE,
2997                                _out, skip + out_len);
2998                 ret = 0;
2999         } else if (tls_prf_sha1_md5(ssl->session->master_key,
3000                                     ssl->session->master_key_length,
3001                                     label, rnd, 2 * SSL3_RANDOM_SIZE,
3002                                     _out, skip + out_len) == 0) {
3003                 ret = 0;
3004         }
3005         os_free(rnd);
3006         if (ret == 0 && skip_keyblock)
3007                 os_memcpy(out, _out + skip, out_len);
3008         bin_clear_free(tmp_out, skip);
3009
3010         return ret;
3011 #else
3012         SSL *ssl;
3013         SSL_SESSION *sess;
3014         u8 *rnd;
3015         int ret = -1;
3016         int skip = 0;
3017         u8 *tmp_out = NULL;
3018         u8 *_out = out;
3019         unsigned char client_random[SSL3_RANDOM_SIZE];
3020         unsigned char server_random[SSL3_RANDOM_SIZE];
3021         unsigned char master_key[64];
3022         size_t master_key_len;
3023         const char *ver;
3024
3025         /*
3026          * TLS library did not support key generation, so get the needed TLS
3027          * session parameters and use an internal implementation of TLS PRF to
3028          * derive the key.
3029          */
3030
3031         if (conn == NULL)
3032                 return -1;
3033         ssl = conn->ssl;
3034         if (ssl == NULL)
3035                 return -1;
3036         ver = SSL_get_version(ssl);
3037         sess = SSL_get_session(ssl);
3038         if (!ver || !sess)
3039                 return -1;
3040
3041         if (skip_keyblock) {
3042                 skip = openssl_get_keyblock_size(ssl);
3043                 if (skip < 0)
3044                         return -1;
3045                 tmp_out = os_malloc(skip + out_len);
3046                 if (!tmp_out)
3047                         return -1;
3048                 _out = tmp_out;
3049         }
3050
3051         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
3052         if (!rnd) {
3053                 os_free(tmp_out);
3054                 return -1;
3055         }
3056
3057         SSL_get_client_random(ssl, client_random, sizeof(client_random));
3058         SSL_get_server_random(ssl, server_random, sizeof(server_random));
3059         master_key_len = SSL_SESSION_get_master_key(sess, master_key,
3060                                                     sizeof(master_key));
3061
3062         if (server_random_first) {
3063                 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
3064                 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random,
3065                           SSL3_RANDOM_SIZE);
3066         } else {
3067                 os_memcpy(rnd, client_random, SSL3_RANDOM_SIZE);
3068                 os_memcpy(rnd + SSL3_RANDOM_SIZE, server_random,
3069                           SSL3_RANDOM_SIZE);
3070         }
3071
3072         if (os_strcmp(ver, "TLSv1.2") == 0) {
3073                 tls_prf_sha256(master_key, master_key_len,
3074                                label, rnd, 2 * SSL3_RANDOM_SIZE,
3075                                _out, skip + out_len);
3076                 ret = 0;
3077         } else if (tls_prf_sha1_md5(master_key, master_key_len,
3078                                     label, rnd, 2 * SSL3_RANDOM_SIZE,
3079                                     _out, skip + out_len) == 0) {
3080                 ret = 0;
3081         }
3082         os_memset(master_key, 0, sizeof(master_key));
3083         os_free(rnd);
3084         if (ret == 0 && skip_keyblock)
3085                 os_memcpy(out, _out + skip, out_len);
3086         bin_clear_free(tmp_out, skip);
3087
3088         return ret;
3089 #endif
3090 #endif /* CONFIG_FIPS */
3091 }
3092
3093
3094 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
3095                        const char *label, int server_random_first,
3096                        int skip_keyblock, u8 *out, size_t out_len)
3097 {
3098 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3099         SSL *ssl;
3100         if (conn == NULL)
3101                 return -1;
3102         if (server_random_first || skip_keyblock)
3103                 return openssl_tls_prf(conn, label,
3104                                        server_random_first, skip_keyblock,
3105                                        out, out_len);
3106         ssl = conn->ssl;
3107         if (SSL_export_keying_material(ssl, out, out_len, label,
3108                                        os_strlen(label), NULL, 0, 0) == 1) {
3109                 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
3110                 return 0;
3111         }
3112 #endif
3113         return openssl_tls_prf(conn, label, server_random_first,
3114                                skip_keyblock, out, out_len);
3115 }
3116
3117
3118 static struct wpabuf *
3119 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
3120                   int server)
3121 {
3122         int res;
3123         struct wpabuf *out_data;
3124
3125         /*
3126          * Give TLS handshake data from the server (if available) to OpenSSL
3127          * for processing.
3128          */
3129         if (in_data && wpabuf_len(in_data) > 0 &&
3130             BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
3131             < 0) {
3132                 tls_show_errors(MSG_INFO, __func__,
3133                                 "Handshake failed - BIO_write");
3134                 return NULL;
3135         }
3136
3137         /* Initiate TLS handshake or continue the existing handshake */
3138         if (server)
3139                 res = SSL_accept(conn->ssl);
3140         else
3141                 res = SSL_connect(conn->ssl);
3142         if (res != 1) {
3143                 int err = SSL_get_error(conn->ssl, res);
3144                 if (err == SSL_ERROR_WANT_READ)
3145                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
3146                                    "more data");
3147                 else if (err == SSL_ERROR_WANT_WRITE)
3148                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
3149                                    "write");
3150                 else {
3151                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
3152                         conn->failed++;
3153                 }
3154         }
3155
3156         /* Get the TLS handshake data to be sent to the server */
3157         res = BIO_ctrl_pending(conn->ssl_out);
3158         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
3159         out_data = wpabuf_alloc(res);
3160         if (out_data == NULL) {
3161                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
3162                            "handshake output (%d bytes)", res);
3163                 if (BIO_reset(conn->ssl_out) < 0) {
3164                         tls_show_errors(MSG_INFO, __func__,
3165                                         "BIO_reset failed");
3166                 }
3167                 return NULL;
3168         }
3169         res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
3170                                       res);
3171         if (res < 0) {
3172                 tls_show_errors(MSG_INFO, __func__,
3173                                 "Handshake failed - BIO_read");
3174                 if (BIO_reset(conn->ssl_out) < 0) {
3175                         tls_show_errors(MSG_INFO, __func__,
3176                                         "BIO_reset failed");
3177                 }
3178                 wpabuf_free(out_data);
3179                 return NULL;
3180         }
3181         wpabuf_put(out_data, res);
3182
3183         return out_data;
3184 }
3185
3186
3187 static struct wpabuf *
3188 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
3189 {
3190         struct wpabuf *appl_data;
3191         int res;
3192
3193         appl_data = wpabuf_alloc(max_len + 100);
3194         if (appl_data == NULL)
3195                 return NULL;
3196
3197         res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
3198                        wpabuf_size(appl_data));
3199         if (res < 0) {
3200                 int err = SSL_get_error(conn->ssl, res);
3201                 if (err == SSL_ERROR_WANT_READ ||
3202                     err == SSL_ERROR_WANT_WRITE) {
3203                         wpa_printf(MSG_DEBUG, "SSL: No Application Data "
3204                                    "included");
3205                 } else {
3206                         tls_show_errors(MSG_INFO, __func__,
3207                                         "Failed to read possible "
3208                                         "Application Data");
3209                 }
3210                 wpabuf_free(appl_data);
3211                 return NULL;
3212         }
3213
3214         wpabuf_put(appl_data, res);
3215         wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
3216                             "message", appl_data);
3217
3218         return appl_data;
3219 }
3220
3221
3222 static struct wpabuf *
3223 openssl_connection_handshake(struct tls_connection *conn,
3224                              const struct wpabuf *in_data,
3225                              struct wpabuf **appl_data, int server)
3226 {
3227         struct wpabuf *out_data;
3228
3229         if (appl_data)
3230                 *appl_data = NULL;
3231
3232         out_data = openssl_handshake(conn, in_data, server);
3233         if (out_data == NULL)
3234                 return NULL;
3235         if (conn->invalid_hb_used) {
3236                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3237                 wpabuf_free(out_data);
3238                 return NULL;
3239         }
3240
3241         if (SSL_is_init_finished(conn->ssl)) {
3242                 wpa_printf(MSG_DEBUG,
3243                            "OpenSSL: Handshake finished - resumed=%d",
3244                            tls_connection_resumed(conn->ssl_ctx, conn));
3245                 if (appl_data && in_data)
3246                         *appl_data = openssl_get_appl_data(conn,
3247                                                            wpabuf_len(in_data));
3248         }
3249
3250         if (conn->invalid_hb_used) {
3251                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3252                 if (appl_data) {
3253                         wpabuf_free(*appl_data);
3254                         *appl_data = NULL;
3255                 }
3256                 wpabuf_free(out_data);
3257                 return NULL;
3258         }
3259
3260         return out_data;
3261 }
3262
3263
3264 struct wpabuf *
3265 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
3266                          const struct wpabuf *in_data,
3267                          struct wpabuf **appl_data)
3268 {
3269         return openssl_connection_handshake(conn, in_data, appl_data, 0);
3270 }
3271
3272
3273 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
3274                                                 struct tls_connection *conn,
3275                                                 const struct wpabuf *in_data,
3276                                                 struct wpabuf **appl_data)
3277 {
3278         return openssl_connection_handshake(conn, in_data, appl_data, 1);
3279 }
3280
3281
3282 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
3283                                        struct tls_connection *conn,
3284                                        const struct wpabuf *in_data)
3285 {
3286         int res;
3287         struct wpabuf *buf;
3288
3289         if (conn == NULL)
3290                 return NULL;
3291
3292         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3293         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
3294             (res = BIO_reset(conn->ssl_out)) < 0) {
3295                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3296                 return NULL;
3297         }
3298         res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
3299         if (res < 0) {
3300                 tls_show_errors(MSG_INFO, __func__,
3301                                 "Encryption failed - SSL_write");
3302                 return NULL;
3303         }
3304
3305         /* Read encrypted data to be sent to the server */
3306         buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
3307         if (buf == NULL)
3308                 return NULL;
3309         res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
3310         if (res < 0) {
3311                 tls_show_errors(MSG_INFO, __func__,
3312                                 "Encryption failed - BIO_read");
3313                 wpabuf_free(buf);
3314                 return NULL;
3315         }
3316         wpabuf_put(buf, res);
3317
3318         return buf;
3319 }
3320
3321
3322 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3323                                        struct tls_connection *conn,
3324                                        const struct wpabuf *in_data)
3325 {
3326         int res;
3327         struct wpabuf *buf;
3328
3329         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3330         res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3331                         wpabuf_len(in_data));
3332         if (res < 0) {
3333                 tls_show_errors(MSG_INFO, __func__,
3334                                 "Decryption failed - BIO_write");
3335                 return NULL;
3336         }
3337         if (BIO_reset(conn->ssl_out) < 0) {
3338                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3339                 return NULL;
3340         }
3341
3342         /* Read decrypted data for further processing */
3343         /*
3344          * Even though we try to disable TLS compression, it is possible that
3345          * this cannot be done with all TLS libraries. Add extra buffer space
3346          * to handle the possibility of the decrypted data being longer than
3347          * input data.
3348          */
3349         buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3350         if (buf == NULL)
3351                 return NULL;
3352         res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3353         if (res < 0) {
3354                 tls_show_errors(MSG_INFO, __func__,
3355                                 "Decryption failed - SSL_read");
3356                 wpabuf_free(buf);
3357                 return NULL;
3358         }
3359         wpabuf_put(buf, res);
3360
3361         if (conn->invalid_hb_used) {
3362                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3363                 wpabuf_free(buf);
3364                 return NULL;
3365         }
3366
3367         return buf;
3368 }
3369
3370
3371 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3372 {
3373 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3374         return conn ? SSL_cache_hit(conn->ssl) : 0;
3375 #else
3376         return conn ? conn->ssl->hit : 0;
3377 #endif
3378 }
3379
3380
3381 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3382                                    u8 *ciphers)
3383 {
3384         char buf[100], *pos, *end;
3385         u8 *c;
3386         int ret;
3387
3388         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3389                 return -1;
3390
3391         buf[0] = '\0';
3392         pos = buf;
3393         end = pos + sizeof(buf);
3394
3395         c = ciphers;
3396         while (*c != TLS_CIPHER_NONE) {
3397                 const char *suite;
3398
3399                 switch (*c) {
3400                 case TLS_CIPHER_RC4_SHA:
3401                         suite = "RC4-SHA";
3402                         break;
3403                 case TLS_CIPHER_AES128_SHA:
3404                         suite = "AES128-SHA";
3405                         break;
3406                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3407                         suite = "DHE-RSA-AES128-SHA";
3408                         break;
3409                 case TLS_CIPHER_ANON_DH_AES128_SHA:
3410                         suite = "ADH-AES128-SHA";
3411                         break;
3412                 default:
3413                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3414                                    "cipher selection: %d", *c);
3415                         return -1;
3416                 }
3417                 ret = os_snprintf(pos, end - pos, ":%s", suite);
3418                 if (os_snprintf_error(end - pos, ret))
3419                         break;
3420                 pos += ret;
3421
3422                 c++;
3423         }
3424
3425         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3426
3427 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3428 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3429         if (os_strstr(buf, ":ADH-")) {
3430                 /*
3431                  * Need to drop to security level 0 to allow anonymous
3432                  * cipher suites for EAP-FAST.
3433                  */
3434                 SSL_set_security_level(conn->ssl, 0);
3435         } else if (SSL_get_security_level(conn->ssl) == 0) {
3436                 /* Force at least security level 1 */
3437                 SSL_set_security_level(conn->ssl, 1);
3438         }
3439 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3440 #endif
3441
3442         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3443                 tls_show_errors(MSG_INFO, __func__,
3444                                 "Cipher suite configuration failed");
3445                 return -1;
3446         }
3447
3448         return 0;
3449 }
3450
3451
3452 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
3453                     char *buf, size_t buflen)
3454 {
3455         const char *name;
3456         if (conn == NULL || conn->ssl == NULL)
3457                 return -1;
3458
3459         name = SSL_get_version(conn->ssl);
3460         if (name == NULL)
3461                 return -1;
3462
3463         os_strlcpy(buf, name, buflen);
3464         return 0;
3465 }
3466
3467
3468 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3469                    char *buf, size_t buflen)
3470 {
3471         const char *name;
3472         if (conn == NULL || conn->ssl == NULL)
3473                 return -1;
3474
3475         name = SSL_get_cipher(conn->ssl);
3476         if (name == NULL)
3477                 return -1;
3478
3479         os_strlcpy(buf, name, buflen);
3480         return 0;
3481 }
3482
3483
3484 int tls_connection_enable_workaround(void *ssl_ctx,
3485                                      struct tls_connection *conn)
3486 {
3487         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3488
3489         return 0;
3490 }
3491
3492
3493 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3494 /* ClientHello TLS extensions require a patch to openssl, so this function is
3495  * commented out unless explicitly needed for EAP-FAST in order to be able to
3496  * build this file with unmodified openssl. */
3497 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3498                                     int ext_type, const u8 *data,
3499                                     size_t data_len)
3500 {
3501         if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3502                 return -1;
3503
3504         if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3505                                        data_len) != 1)
3506                 return -1;
3507
3508         return 0;
3509 }
3510 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3511
3512
3513 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3514 {
3515         if (conn == NULL)
3516                 return -1;
3517         return conn->failed;
3518 }
3519
3520
3521 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3522 {
3523         if (conn == NULL)
3524                 return -1;
3525         return conn->read_alerts;
3526 }
3527
3528
3529 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3530 {
3531         if (conn == NULL)
3532                 return -1;
3533         return conn->write_alerts;
3534 }
3535
3536
3537 #ifdef HAVE_OCSP
3538
3539 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3540 {
3541 #ifndef CONFIG_NO_STDOUT_DEBUG
3542         BIO *out;
3543         size_t rlen;
3544         char *txt;
3545         int res;
3546
3547         if (wpa_debug_level > MSG_DEBUG)
3548                 return;
3549
3550         out = BIO_new(BIO_s_mem());
3551         if (!out)
3552                 return;
3553
3554         OCSP_RESPONSE_print(out, rsp, 0);
3555         rlen = BIO_ctrl_pending(out);
3556         txt = os_malloc(rlen + 1);
3557         if (!txt) {
3558                 BIO_free(out);
3559                 return;
3560         }
3561
3562         res = BIO_read(out, txt, rlen);
3563         if (res > 0) {
3564                 txt[res] = '\0';
3565                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3566         }
3567         os_free(txt);
3568         BIO_free(out);
3569 #endif /* CONFIG_NO_STDOUT_DEBUG */
3570 }
3571
3572
3573 static void debug_print_cert(X509 *cert, const char *title)
3574 {
3575 #ifndef CONFIG_NO_STDOUT_DEBUG
3576         BIO *out;
3577         size_t rlen;
3578         char *txt;
3579         int res;
3580
3581         if (wpa_debug_level > MSG_DEBUG)
3582                 return;
3583
3584         out = BIO_new(BIO_s_mem());
3585         if (!out)
3586                 return;
3587
3588         X509_print(out, cert);
3589         rlen = BIO_ctrl_pending(out);
3590         txt = os_malloc(rlen + 1);
3591         if (!txt) {
3592                 BIO_free(out);
3593                 return;
3594         }
3595
3596         res = BIO_read(out, txt, rlen);
3597         if (res > 0) {
3598                 txt[res] = '\0';
3599                 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3600         }
3601         os_free(txt);
3602
3603         BIO_free(out);
3604 #endif /* CONFIG_NO_STDOUT_DEBUG */
3605 }
3606
3607
3608 static int ocsp_resp_cb(SSL *s, void *arg)
3609 {
3610         struct tls_connection *conn = arg;
3611         const unsigned char *p;
3612         int len, status, reason;
3613         OCSP_RESPONSE *rsp;
3614         OCSP_BASICRESP *basic;
3615         OCSP_CERTID *id;
3616         ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3617         X509_STORE *store;
3618         STACK_OF(X509) *certs = NULL;
3619
3620         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3621         if (!p) {
3622                 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3623                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3624         }
3625
3626         wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3627
3628         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3629         if (!rsp) {
3630                 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3631                 return 0;
3632         }
3633
3634         ocsp_debug_print_resp(rsp);
3635
3636         status = OCSP_response_status(rsp);
3637         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3638                 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3639                            status, OCSP_response_status_str(status));
3640                 return 0;
3641         }
3642
3643         basic = OCSP_response_get1_basic(rsp);
3644         if (!basic) {
3645                 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3646                 return 0;
3647         }
3648
3649         store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3650         if (conn->peer_issuer) {
3651                 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3652
3653                 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3654                         tls_show_errors(MSG_INFO, __func__,
3655                                         "OpenSSL: Could not add issuer to certificate store");
3656                 }
3657                 certs = sk_X509_new_null();
3658                 if (certs) {
3659                         X509 *cert;
3660                         cert = X509_dup(conn->peer_issuer);
3661                         if (cert && !sk_X509_push(certs, cert)) {
3662                                 tls_show_errors(
3663                                         MSG_INFO, __func__,
3664                                         "OpenSSL: Could not add issuer to OCSP responder trust store");
3665                                 X509_free(cert);
3666                                 sk_X509_free(certs);
3667                                 certs = NULL;
3668                         }
3669                         if (certs && conn->peer_issuer_issuer) {
3670                                 cert = X509_dup(conn->peer_issuer_issuer);
3671                                 if (cert && !sk_X509_push(certs, cert)) {
3672                                         tls_show_errors(
3673                                                 MSG_INFO, __func__,
3674                                                 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3675                                         X509_free(cert);
3676                                 }
3677                         }
3678                 }
3679         }
3680
3681         status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3682         sk_X509_pop_free(certs, X509_free);
3683         if (status <= 0) {
3684                 tls_show_errors(MSG_INFO, __func__,
3685                                 "OpenSSL: OCSP response failed verification");
3686                 OCSP_BASICRESP_free(basic);
3687                 OCSP_RESPONSE_free(rsp);
3688                 return 0;
3689         }
3690
3691         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3692
3693         if (!conn->peer_cert) {
3694                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3695                 OCSP_BASICRESP_free(basic);
3696                 OCSP_RESPONSE_free(rsp);
3697                 return 0;
3698         }
3699
3700         if (!conn->peer_issuer) {
3701                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3702                 OCSP_BASICRESP_free(basic);
3703                 OCSP_RESPONSE_free(rsp);
3704                 return 0;
3705         }
3706
3707         id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3708         if (!id) {
3709                 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3710                 OCSP_BASICRESP_free(basic);
3711                 OCSP_RESPONSE_free(rsp);
3712                 return 0;
3713         }
3714
3715         if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3716                                    &this_update, &next_update)) {
3717                 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3718                            (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3719                            " (OCSP not required)");
3720                 OCSP_BASICRESP_free(basic);
3721                 OCSP_RESPONSE_free(rsp);
3722                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3723         }
3724
3725         if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3726                 tls_show_errors(MSG_INFO, __func__,
3727                                 "OpenSSL: OCSP status times invalid");
3728                 OCSP_BASICRESP_free(basic);
3729                 OCSP_RESPONSE_free(rsp);
3730                 return 0;
3731         }
3732
3733         OCSP_BASICRESP_free(basic);
3734         OCSP_RESPONSE_free(rsp);
3735
3736         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3737                    OCSP_cert_status_str(status));
3738
3739         if (status == V_OCSP_CERTSTATUS_GOOD)
3740                 return 1;
3741         if (status == V_OCSP_CERTSTATUS_REVOKED)
3742                 return 0;
3743         if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3744                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3745                 return 0;
3746         }
3747         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3748         return 1;
3749 }
3750
3751
3752 static int ocsp_status_cb(SSL *s, void *arg)
3753 {
3754         char *tmp;
3755         char *resp;
3756         size_t len;
3757
3758         if (tls_global->ocsp_stapling_response == NULL) {
3759                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3760                 return SSL_TLSEXT_ERR_OK;
3761         }
3762
3763         resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3764         if (resp == NULL) {
3765                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3766                 /* TODO: Build OCSPResponse with responseStatus = internalError
3767                  */
3768                 return SSL_TLSEXT_ERR_OK;
3769         }
3770         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3771         tmp = OPENSSL_malloc(len);
3772         if (tmp == NULL) {
3773                 os_free(resp);
3774                 return SSL_TLSEXT_ERR_ALERT_FATAL;
3775         }
3776
3777         os_memcpy(tmp, resp, len);
3778         os_free(resp);
3779         SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3780
3781         return SSL_TLSEXT_ERR_OK;
3782 }
3783
3784 #endif /* HAVE_OCSP */
3785
3786
3787 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3788                               const struct tls_connection_params *params)
3789 {
3790         struct tls_data *data = tls_ctx;
3791         int ret;
3792         unsigned long err;
3793         int can_pkcs11 = 0;
3794         const char *key_id = params->key_id;
3795         const char *cert_id = params->cert_id;
3796         const char *ca_cert_id = params->ca_cert_id;
3797         const char *engine_id = params->engine ? params->engine_id : NULL;
3798
3799         if (conn == NULL)
3800                 return -1;
3801
3802         /*
3803          * If the engine isn't explicitly configured, and any of the
3804          * cert/key fields are actually PKCS#11 URIs, then automatically
3805          * use the PKCS#11 ENGINE.
3806          */
3807         if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3808                 can_pkcs11 = 1;
3809
3810         if (!key_id && params->private_key && can_pkcs11 &&
3811             os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3812                 can_pkcs11 = 2;
3813                 key_id = params->private_key;
3814         }
3815
3816         if (!cert_id && params->client_cert && can_pkcs11 &&
3817             os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3818                 can_pkcs11 = 2;
3819                 cert_id = params->client_cert;
3820         }
3821
3822         if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3823             os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3824                 can_pkcs11 = 2;
3825                 ca_cert_id = params->ca_cert;
3826         }
3827
3828         /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3829         if (can_pkcs11 == 2 && !engine_id)
3830                 engine_id = "pkcs11";
3831
3832 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3833 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3834         if (params->flags & TLS_CONN_EAP_FAST) {
3835                 wpa_printf(MSG_DEBUG,
3836                            "OpenSSL: Use TLSv1_method() for EAP-FAST");
3837                 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3838                         tls_show_errors(MSG_INFO, __func__,
3839                                         "Failed to set TLSv1_method() for EAP-FAST");
3840                         return -1;
3841                 }
3842         }
3843 #endif
3844 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3845
3846         while ((err = ERR_get_error())) {
3847                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3848                            __func__, ERR_error_string(err, NULL));
3849         }
3850
3851         if (engine_id) {
3852                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3853                 ret = tls_engine_init(conn, engine_id, params->pin,
3854                                       key_id, cert_id, ca_cert_id);
3855                 if (ret)
3856                         return ret;
3857         }
3858         if (tls_connection_set_subject_match(conn,
3859                                              params->subject_match,
3860                                              params->altsubject_match,
3861                                              params->suffix_match,
3862                                              params->domain_match))
3863                 return -1;
3864
3865         if (engine_id && ca_cert_id) {
3866                 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
3867                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3868         } else {
3869         if (tls_connection_ca_cert(data, conn, params->ca_cert,
3870                                    params->ca_cert_blob,
3871                                    params->ca_cert_blob_len,
3872                                    params->ca_path, params->server_cert_cb, 
3873                                    params->server_cert_ctx))
3874             return -1;
3875     }
3876
3877         if (engine_id && cert_id) {
3878                 if (tls_connection_engine_client_cert(conn, cert_id))
3879                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3880         } else if (tls_connection_client_cert(conn, params->client_cert,
3881                                               params->client_cert_blob,
3882                                               params->client_cert_blob_len))
3883                 return -1;
3884
3885         if (engine_id && key_id) {
3886                 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3887                 if (tls_connection_engine_private_key(conn))
3888                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3889         } else if (tls_connection_private_key(data, conn,
3890                                               params->private_key,
3891                                               params->private_key_passwd,
3892                                               params->private_key_blob,
3893                                               params->private_key_blob_len)) {
3894                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3895                            params->private_key);
3896                 return -1;
3897         }
3898
3899         if (tls_connection_dh(conn, params->dh_file)) {
3900                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3901                            params->dh_file);
3902                 return -1;
3903         }
3904
3905         if (params->openssl_ciphers &&
3906             SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3907                 wpa_printf(MSG_INFO,
3908                            "OpenSSL: Failed to set cipher string '%s'",
3909                            params->openssl_ciphers);
3910                 return -1;
3911         }
3912
3913         tls_set_conn_flags(conn->ssl, params->flags);
3914
3915 #ifdef HAVE_OCSP
3916         if (params->flags & TLS_CONN_REQUEST_OCSP) {
3917                 SSL_CTX *ssl_ctx = data->ssl;
3918                 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3919                 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3920                 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3921         }
3922 #else /* HAVE_OCSP */
3923         if (params->flags & TLS_CONN_REQUIRE_OCSP) {
3924                 wpa_printf(MSG_INFO,
3925                            "OpenSSL: No OCSP support included - reject configuration");
3926                 return -1;
3927         }
3928         if (params->flags & TLS_CONN_REQUEST_OCSP) {
3929                 wpa_printf(MSG_DEBUG,
3930                            "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
3931         }
3932 #endif /* HAVE_OCSP */
3933
3934         conn->flags = params->flags;
3935
3936         tls_get_errors(data);
3937
3938         return 0;
3939 }
3940
3941
3942 int tls_global_set_params(void *tls_ctx,
3943                           const struct tls_connection_params *params)
3944 {
3945         struct tls_data *data = tls_ctx;
3946         SSL_CTX *ssl_ctx = data->ssl;
3947         unsigned long err;
3948
3949         while ((err = ERR_get_error())) {
3950                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3951                            __func__, ERR_error_string(err, NULL));
3952         }
3953
3954         if (tls_global_ca_cert(data, params->ca_cert) ||
3955             tls_global_client_cert(data, params->client_cert) ||
3956             tls_global_private_key(data, params->private_key,
3957                                    params->private_key_passwd) ||
3958             tls_global_dh(data, params->dh_file)) {
3959                 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
3960                 return -1;
3961         }
3962
3963         if (params->openssl_ciphers &&
3964             SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3965                 wpa_printf(MSG_INFO,
3966                            "OpenSSL: Failed to set cipher string '%s'",
3967                            params->openssl_ciphers);
3968                 return -1;
3969         }
3970
3971 #ifdef SSL_OP_NO_TICKET
3972         if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3973                 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3974 #ifdef SSL_CTX_clear_options
3975         else
3976                 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3977 #endif /* SSL_clear_options */
3978 #endif /*  SSL_OP_NO_TICKET */
3979
3980 #ifdef HAVE_OCSP
3981         SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3982         SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3983         os_free(tls_global->ocsp_stapling_response);
3984         if (params->ocsp_stapling_response)
3985                 tls_global->ocsp_stapling_response =
3986                         os_strdup(params->ocsp_stapling_response);
3987         else
3988                 tls_global->ocsp_stapling_response = NULL;
3989 #endif /* HAVE_OCSP */
3990
3991         return 0;
3992 }
3993
3994
3995 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3996 /* Pre-shared secred requires a patch to openssl, so this function is
3997  * commented out unless explicitly needed for EAP-FAST in order to be able to
3998  * build this file with unmodified openssl. */
3999
4000 #ifdef OPENSSL_IS_BORINGSSL
4001 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
4002                            STACK_OF(SSL_CIPHER) *peer_ciphers,
4003                            const SSL_CIPHER **cipher, void *arg)
4004 #else /* OPENSSL_IS_BORINGSSL */
4005 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
4006                            STACK_OF(SSL_CIPHER) *peer_ciphers,
4007                            SSL_CIPHER **cipher, void *arg)
4008 #endif /* OPENSSL_IS_BORINGSSL */
4009 {
4010         struct tls_connection *conn = arg;
4011         int ret;
4012
4013 #if OPENSSL_VERSION_NUMBER < 0x10100000L
4014         if (conn == NULL || conn->session_ticket_cb == NULL)
4015                 return 0;
4016
4017         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
4018                                       conn->session_ticket,
4019                                       conn->session_ticket_len,
4020                                       s->s3->client_random,
4021                                       s->s3->server_random, secret);
4022 #else
4023         unsigned char client_random[SSL3_RANDOM_SIZE];
4024         unsigned char server_random[SSL3_RANDOM_SIZE];
4025
4026         if (conn == NULL || conn->session_ticket_cb == NULL)
4027                 return 0;
4028
4029         SSL_get_client_random(s, client_random, sizeof(client_random));
4030         SSL_get_server_random(s, server_random, sizeof(server_random));
4031
4032         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
4033                                       conn->session_ticket,
4034                                       conn->session_ticket_len,
4035                                       client_random,
4036                                       server_random, secret);
4037 #endif
4038
4039         os_free(conn->session_ticket);
4040         conn->session_ticket = NULL;
4041
4042         if (ret <= 0)
4043                 return 0;
4044
4045         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
4046         return 1;
4047 }
4048
4049
4050 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
4051                                      int len, void *arg)
4052 {
4053         struct tls_connection *conn = arg;
4054
4055         if (conn == NULL || conn->session_ticket_cb == NULL)
4056                 return 0;
4057
4058         wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
4059
4060         os_free(conn->session_ticket);
4061         conn->session_ticket = NULL;
4062
4063         wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
4064                     "extension", data, len);
4065
4066         conn->session_ticket = os_malloc(len);
4067         if (conn->session_ticket == NULL)
4068                 return 0;
4069
4070         os_memcpy(conn->session_ticket, data, len);
4071         conn->session_ticket_len = len;
4072
4073         return 1;
4074 }
4075 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4076
4077
4078 int tls_connection_set_session_ticket_cb(void *tls_ctx,
4079                                          struct tls_connection *conn,
4080                                          tls_session_ticket_cb cb,
4081                                          void *ctx)
4082 {
4083 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
4084         conn->session_ticket_cb = cb;
4085         conn->session_ticket_cb_ctx = ctx;
4086
4087         if (cb) {
4088                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
4089                                               conn) != 1)
4090                         return -1;
4091                 SSL_set_session_ticket_ext_cb(conn->ssl,
4092                                               tls_session_ticket_ext_cb, conn);
4093         } else {
4094                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
4095                         return -1;
4096                 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
4097         }
4098
4099         return 0;
4100 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4101         return -1;
4102 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4103 }
4104
4105
4106 int tls_get_library_version(char *buf, size_t buf_len)
4107 {
4108         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
4109                            OPENSSL_VERSION_TEXT,
4110                            SSLeay_version(SSLEAY_VERSION));
4111 }
4112
4113
4114 void tls_connection_set_success_data(struct tls_connection *conn,
4115                                      struct wpabuf *data)
4116 {
4117         SSL_SESSION *sess;
4118         struct wpabuf *old;
4119
4120         if (tls_ex_idx_session < 0)
4121                 goto fail;
4122         sess = SSL_get_session(conn->ssl);
4123         if (!sess)
4124                 goto fail;
4125         old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
4126         if (old) {
4127                 wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
4128                            old);
4129                 wpabuf_free(old);
4130         }
4131         if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
4132                 goto fail;
4133
4134         wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
4135         conn->success_data = 1;
4136         return;
4137
4138 fail:
4139         wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
4140         wpabuf_free(data);
4141 }
4142
4143
4144 void tls_connection_set_success_data_resumed(struct tls_connection *conn)
4145 {
4146         wpa_printf(MSG_DEBUG,
4147                    "OpenSSL: Success data accepted for resumed session");
4148         conn->success_data = 1;
4149 }
4150
4151
4152 const struct wpabuf *
4153 tls_connection_get_success_data(struct tls_connection *conn)
4154 {
4155         SSL_SESSION *sess;
4156
4157         if (tls_ex_idx_session < 0 ||
4158             !(sess = SSL_get_session(conn->ssl)))
4159                 return NULL;
4160         return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
4161 }
4162
4163
4164 void tls_connection_remove_session(struct tls_connection *conn)
4165 {
4166         SSL_SESSION *sess;
4167
4168         sess = SSL_get_session(conn->ssl);
4169         if (!sess)
4170                 return;
4171
4172         if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
4173                 wpa_printf(MSG_DEBUG,
4174                            "OpenSSL: Session was not cached");
4175         else
4176                 wpa_printf(MSG_DEBUG,
4177                            "OpenSSL: Removed cached session to disable session resumption");
4178 }