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