62e18c8bda3dfd50071f24987d171192cd9ac369
[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 static void tls_set_conn_flags(SSL *ssl, unsigned int flags)
1947 {
1948 #ifdef SSL_OP_NO_TICKET
1949         if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
1950                 SSL_set_options(ssl, SSL_OP_NO_TICKET);
1951 #ifdef SSL_clear_options
1952         else
1953                 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
1954 #endif /* SSL_clear_options */
1955 #endif /* SSL_OP_NO_TICKET */
1956
1957 #ifdef SSL_OP_NO_TLSv1
1958         if (flags & TLS_CONN_DISABLE_TLSv1_0)
1959                 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
1960         else
1961                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
1962 #endif /* SSL_OP_NO_TLSv1 */
1963 #ifdef SSL_OP_NO_TLSv1_1
1964         if (flags & TLS_CONN_DISABLE_TLSv1_1)
1965                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
1966         else
1967                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
1968 #endif /* SSL_OP_NO_TLSv1_1 */
1969 #ifdef SSL_OP_NO_TLSv1_2
1970         if (flags & TLS_CONN_DISABLE_TLSv1_2)
1971                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
1972         else
1973                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
1974 #endif /* SSL_OP_NO_TLSv1_2 */
1975 }
1976
1977
1978 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1979                               int verify_peer, unsigned int flags,
1980                               const u8 *session_ctx, size_t session_ctx_len)
1981 {
1982         static int counter = 0;
1983
1984         if (conn == NULL)
1985                 return -1;
1986
1987         if (verify_peer) {
1988                 conn->ca_cert_verify = 1;
1989                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1990                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1991                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1992         } else {
1993                 conn->ca_cert_verify = 0;
1994                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1995         }
1996
1997         tls_set_conn_flags(conn->ssl, flags);
1998         conn->flags = flags;
1999
2000         SSL_set_accept_state(conn->ssl);
2001
2002         /*
2003          * Set session id context in order to avoid fatal errors when client
2004          * tries to resume a session. However, set the context to a unique
2005          * value in order to effectively disable session resumption for now
2006          * since not all areas of the server code are ready for it (e.g.,
2007          * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
2008          * handshake).
2009          */
2010         counter++;
2011         SSL_set_session_id_context(conn->ssl,
2012                                    (const unsigned char *) &counter,
2013                                    sizeof(counter));
2014
2015         return 0;
2016 }
2017
2018
2019 static int tls_connection_client_cert(struct tls_connection *conn,
2020                                       const char *client_cert,
2021                                       const u8 *client_cert_blob,
2022                                       size_t client_cert_blob_len)
2023 {
2024         if (client_cert == NULL && client_cert_blob == NULL)
2025                 return 0;
2026
2027         if (client_cert_blob &&
2028             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
2029                                      client_cert_blob_len) == 1) {
2030                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
2031                            "OK");
2032                 return 0;
2033         } else if (client_cert_blob) {
2034                 tls_show_errors(MSG_DEBUG, __func__,
2035                                 "SSL_use_certificate_ASN1 failed");
2036         }
2037
2038         if (client_cert == NULL)
2039                 return -1;
2040
2041 #ifdef ANDROID
2042         if (os_strncmp("keystore://", client_cert, 11) == 0) {
2043                 BIO *bio = BIO_from_keystore(&client_cert[11]);
2044                 X509 *x509 = NULL;
2045                 int ret = -1;
2046                 if (bio) {
2047                         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
2048                         BIO_free(bio);
2049                 }
2050                 if (x509) {
2051                         if (SSL_use_certificate(conn->ssl, x509) == 1)
2052                                 ret = 0;
2053                         X509_free(x509);
2054                 }
2055                 return ret;
2056         }
2057 #endif /* ANDROID */
2058
2059 #ifndef OPENSSL_NO_STDIO
2060         if (SSL_use_certificate_file(conn->ssl, client_cert,
2061                                      SSL_FILETYPE_ASN1) == 1) {
2062                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
2063                            " --> OK");
2064                 return 0;
2065         }
2066
2067         if (SSL_use_certificate_file(conn->ssl, client_cert,
2068                                      SSL_FILETYPE_PEM) == 1) {
2069                 ERR_clear_error();
2070                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
2071                            " --> OK");
2072                 return 0;
2073         }
2074
2075         tls_show_errors(MSG_DEBUG, __func__,
2076                         "SSL_use_certificate_file failed");
2077 #else /* OPENSSL_NO_STDIO */
2078         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2079 #endif /* OPENSSL_NO_STDIO */
2080
2081         return -1;
2082 }
2083
2084
2085 static int tls_global_client_cert(struct tls_data *data,
2086                                   const char *client_cert)
2087 {
2088 #ifndef OPENSSL_NO_STDIO
2089         SSL_CTX *ssl_ctx = data->ssl;
2090
2091         if (client_cert == NULL)
2092                 return 0;
2093
2094         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2095                                          SSL_FILETYPE_ASN1) != 1 &&
2096             SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
2097             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
2098                                          SSL_FILETYPE_PEM) != 1) {
2099                 tls_show_errors(MSG_INFO, __func__,
2100                                 "Failed to load client certificate");
2101                 return -1;
2102         }
2103         return 0;
2104 #else /* OPENSSL_NO_STDIO */
2105         if (client_cert == NULL)
2106                 return 0;
2107         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
2108         return -1;
2109 #endif /* OPENSSL_NO_STDIO */
2110 }
2111
2112
2113 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
2114 {
2115         if (password == NULL) {
2116                 return 0;
2117         }
2118         os_strlcpy(buf, (char *) password, size);
2119         return os_strlen(buf);
2120 }
2121
2122
2123 #ifdef PKCS12_FUNCS
2124 static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
2125                             const char *passwd)
2126 {
2127         EVP_PKEY *pkey;
2128         X509 *cert;
2129         STACK_OF(X509) *certs;
2130         int res = 0;
2131         char buf[256];
2132
2133         pkey = NULL;
2134         cert = NULL;
2135         certs = NULL;
2136         if (!passwd)
2137                 passwd = "";
2138         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
2139                 tls_show_errors(MSG_DEBUG, __func__,
2140                                 "Failed to parse PKCS12 file");
2141                 PKCS12_free(p12);
2142                 return -1;
2143         }
2144         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
2145
2146         if (cert) {
2147                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
2148                                   sizeof(buf));
2149                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
2150                            "subject='%s'", buf);
2151                 if (ssl) {
2152                         if (SSL_use_certificate(ssl, cert) != 1)
2153                                 res = -1;
2154                 } else {
2155                         if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
2156                                 res = -1;
2157                 }
2158                 X509_free(cert);
2159         }
2160
2161         if (pkey) {
2162                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
2163                 if (ssl) {
2164                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
2165                                 res = -1;
2166                 } else {
2167                         if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
2168                                 res = -1;
2169                 }
2170                 EVP_PKEY_free(pkey);
2171         }
2172
2173         if (certs) {
2174 #if OPENSSL_VERSION_NUMBER >= 0x10002000L
2175                 SSL_clear_chain_certs(ssl);
2176                 while ((cert = sk_X509_pop(certs)) != NULL) {
2177                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
2178                                           sizeof(buf));
2179                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2180                                    " from PKCS12: subject='%s'", buf);
2181                         if (SSL_add1_chain_cert(ssl, cert) != 1) {
2182                                 res = -1;
2183                                 break;
2184                         }
2185                 }
2186                 sk_X509_free(certs);
2187 #ifndef OPENSSL_IS_BORINGSSL
2188                 res = SSL_build_cert_chain(ssl,
2189                                            SSL_BUILD_CHAIN_FLAG_CHECK |
2190                                            SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
2191                 if (!res) {
2192                         tls_show_errors(MSG_DEBUG, __func__,
2193                                         "Failed to build certificate chain");
2194                 } else if (res == 2) {
2195                         wpa_printf(MSG_DEBUG,
2196                                    "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
2197                 }
2198 #endif /* OPENSSL_IS_BORINGSSL */
2199                 /*
2200                  * Try to continue regardless of result since it is possible for
2201                  * the extra certificates not to be required.
2202                  */
2203                 res = 0;
2204 #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2205 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
2206                 SSL_CTX_clear_extra_chain_certs(data->ssl);
2207 #endif /* OPENSSL_VERSION_NUMBER >= 0x10001000L */
2208                 while ((cert = sk_X509_pop(certs)) != NULL) {
2209                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
2210                                           sizeof(buf));
2211                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
2212                                    " from PKCS12: subject='%s'", buf);
2213                         /*
2214                          * There is no SSL equivalent for the chain cert - so
2215                          * always add it to the context...
2216                          */
2217                         if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
2218                         {
2219                                 res = -1;
2220                                 break;
2221                         }
2222                 }
2223                 sk_X509_free(certs);
2224 #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
2225         }
2226
2227         PKCS12_free(p12);
2228
2229         if (res < 0)
2230                 tls_get_errors(data);
2231
2232         return res;
2233 }
2234 #endif  /* PKCS12_FUNCS */
2235
2236
2237 static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
2238                            const char *private_key, const char *passwd)
2239 {
2240 #ifdef PKCS12_FUNCS
2241         FILE *f;
2242         PKCS12 *p12;
2243
2244         f = fopen(private_key, "rb");
2245         if (f == NULL)
2246                 return -1;
2247
2248         p12 = d2i_PKCS12_fp(f, NULL);
2249         fclose(f);
2250
2251         if (p12 == NULL) {
2252                 tls_show_errors(MSG_INFO, __func__,
2253                                 "Failed to use PKCS#12 file");
2254                 return -1;
2255         }
2256
2257         return tls_parse_pkcs12(data, ssl, p12, passwd);
2258
2259 #else /* PKCS12_FUNCS */
2260         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
2261                    "p12/pfx files");
2262         return -1;
2263 #endif  /* PKCS12_FUNCS */
2264 }
2265
2266
2267 static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
2268                                 const u8 *blob, size_t len, const char *passwd)
2269 {
2270 #ifdef PKCS12_FUNCS
2271         PKCS12 *p12;
2272
2273         p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
2274         if (p12 == NULL) {
2275                 tls_show_errors(MSG_INFO, __func__,
2276                                 "Failed to use PKCS#12 blob");
2277                 return -1;
2278         }
2279
2280         return tls_parse_pkcs12(data, ssl, p12, passwd);
2281
2282 #else /* PKCS12_FUNCS */
2283         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
2284                    "p12/pfx blobs");
2285         return -1;
2286 #endif  /* PKCS12_FUNCS */
2287 }
2288
2289
2290 #ifndef OPENSSL_NO_ENGINE
2291 static int tls_engine_get_cert(struct tls_connection *conn,
2292                                const char *cert_id,
2293                                X509 **cert)
2294 {
2295         /* this runs after the private key is loaded so no PIN is required */
2296         struct {
2297                 const char *cert_id;
2298                 X509 *cert;
2299         } params;
2300         params.cert_id = cert_id;
2301         params.cert = NULL;
2302
2303         if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
2304                              0, &params, NULL, 1)) {
2305                 unsigned long err = ERR_get_error();
2306
2307                 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
2308                            " '%s' [%s]", cert_id,
2309                            ERR_error_string(err, NULL));
2310                 if (tls_is_pin_error(err))
2311                         return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
2312                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2313         }
2314         if (!params.cert) {
2315                 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
2316                            " '%s'", cert_id);
2317                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
2318         }
2319         *cert = params.cert;
2320         return 0;
2321 }
2322 #endif /* OPENSSL_NO_ENGINE */
2323
2324
2325 static int tls_connection_engine_client_cert(struct tls_connection *conn,
2326                                              const char *cert_id)
2327 {
2328 #ifndef OPENSSL_NO_ENGINE
2329         X509 *cert;
2330
2331         if (tls_engine_get_cert(conn, cert_id, &cert))
2332                 return -1;
2333
2334         if (!SSL_use_certificate(conn->ssl, cert)) {
2335                 tls_show_errors(MSG_ERROR, __func__,
2336                                 "SSL_use_certificate failed");
2337                 X509_free(cert);
2338                 return -1;
2339         }
2340         X509_free(cert);
2341         wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
2342                    "OK");
2343         return 0;
2344
2345 #else /* OPENSSL_NO_ENGINE */
2346         return -1;
2347 #endif /* OPENSSL_NO_ENGINE */
2348 }
2349
2350
2351 static int tls_connection_engine_ca_cert(struct tls_data *data,
2352                                          struct tls_connection *conn,
2353                                          const char *ca_cert_id)
2354 {
2355 #ifndef OPENSSL_NO_ENGINE
2356         X509 *cert;
2357         SSL_CTX *ssl_ctx = data->ssl;
2358         X509_STORE *store;
2359
2360         if (tls_engine_get_cert(conn, ca_cert_id, &cert))
2361                 return -1;
2362
2363         /* start off the same as tls_connection_ca_cert */
2364         store = X509_STORE_new();
2365         if (store == NULL) {
2366                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
2367                            "certificate store", __func__);
2368                 X509_free(cert);
2369                 return -1;
2370         }
2371         SSL_CTX_set_cert_store(ssl_ctx, store);
2372         if (!X509_STORE_add_cert(store, cert)) {
2373                 unsigned long err = ERR_peek_error();
2374                 tls_show_errors(MSG_WARNING, __func__,
2375                                 "Failed to add CA certificate from engine "
2376                                 "to certificate store");
2377                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
2378                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
2379                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
2380                                    " already in hash table error",
2381                                    __func__);
2382                 } else {
2383                         X509_free(cert);
2384                         return -1;
2385                 }
2386         }
2387         X509_free(cert);
2388         wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
2389                    "to certificate store", __func__);
2390         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
2391         conn->ca_cert_verify = 1;
2392
2393         return 0;
2394
2395 #else /* OPENSSL_NO_ENGINE */
2396         return -1;
2397 #endif /* OPENSSL_NO_ENGINE */
2398 }
2399
2400
2401 static int tls_connection_engine_private_key(struct tls_connection *conn)
2402 {
2403 #ifndef OPENSSL_NO_ENGINE
2404         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
2405                 tls_show_errors(MSG_ERROR, __func__,
2406                                 "ENGINE: cannot use private key for TLS");
2407                 return -1;
2408         }
2409         if (!SSL_check_private_key(conn->ssl)) {
2410                 tls_show_errors(MSG_INFO, __func__,
2411                                 "Private key failed verification");
2412                 return -1;
2413         }
2414         return 0;
2415 #else /* OPENSSL_NO_ENGINE */
2416         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
2417                    "engine support was not compiled in");
2418         return -1;
2419 #endif /* OPENSSL_NO_ENGINE */
2420 }
2421
2422
2423 static int tls_connection_private_key(struct tls_data *data,
2424                                       struct tls_connection *conn,
2425                                       const char *private_key,
2426                                       const char *private_key_passwd,
2427                                       const u8 *private_key_blob,
2428                                       size_t private_key_blob_len)
2429 {
2430         SSL_CTX *ssl_ctx = data->ssl;
2431         char *passwd;
2432         int ok;
2433
2434         if (private_key == NULL && private_key_blob == NULL)
2435                 return 0;
2436
2437         if (private_key_passwd) {
2438                 passwd = os_strdup(private_key_passwd);
2439                 if (passwd == NULL)
2440                         return -1;
2441         } else
2442                 passwd = NULL;
2443
2444         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2445         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2446
2447         ok = 0;
2448         while (private_key_blob) {
2449                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
2450                                             (u8 *) private_key_blob,
2451                                             private_key_blob_len) == 1) {
2452                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2453                                    "ASN1(EVP_PKEY_RSA) --> OK");
2454                         ok = 1;
2455                         break;
2456                 }
2457
2458                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
2459                                             (u8 *) private_key_blob,
2460                                             private_key_blob_len) == 1) {
2461                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
2462                                    "ASN1(EVP_PKEY_DSA) --> OK");
2463                         ok = 1;
2464                         break;
2465                 }
2466
2467                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
2468                                                (u8 *) private_key_blob,
2469                                                private_key_blob_len) == 1) {
2470                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2471                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
2472                         ok = 1;
2473                         break;
2474                 }
2475
2476                 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
2477                                          private_key_blob_len, passwd) == 0) {
2478                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
2479                                    "OK");
2480                         ok = 1;
2481                         break;
2482                 }
2483
2484                 break;
2485         }
2486
2487         while (!ok && private_key) {
2488 #ifndef OPENSSL_NO_STDIO
2489                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2490                                             SSL_FILETYPE_ASN1) == 1) {
2491                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2492                                    "SSL_use_PrivateKey_File (DER) --> OK");
2493                         ok = 1;
2494                         break;
2495                 }
2496
2497                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
2498                                             SSL_FILETYPE_PEM) == 1) {
2499                         wpa_printf(MSG_DEBUG, "OpenSSL: "
2500                                    "SSL_use_PrivateKey_File (PEM) --> OK");
2501                         ok = 1;
2502                         break;
2503                 }
2504 #else /* OPENSSL_NO_STDIO */
2505                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
2506                            __func__);
2507 #endif /* OPENSSL_NO_STDIO */
2508
2509                 if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
2510                     == 0) {
2511                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
2512                                    "--> OK");
2513                         ok = 1;
2514                         break;
2515                 }
2516
2517                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
2518                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
2519                                    "access certificate store --> OK");
2520                         ok = 1;
2521                         break;
2522                 }
2523
2524                 break;
2525         }
2526
2527         if (!ok) {
2528                 tls_show_errors(MSG_INFO, __func__,
2529                                 "Failed to load private key");
2530                 os_free(passwd);
2531                 return -1;
2532         }
2533         ERR_clear_error();
2534         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2535         os_free(passwd);
2536
2537         if (!SSL_check_private_key(conn->ssl)) {
2538                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
2539                                 "verification");
2540                 return -1;
2541         }
2542
2543         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
2544         return 0;
2545 }
2546
2547
2548 static int tls_global_private_key(struct tls_data *data,
2549                                   const char *private_key,
2550                                   const char *private_key_passwd)
2551 {
2552         SSL_CTX *ssl_ctx = data->ssl;
2553         char *passwd;
2554
2555         if (private_key == NULL)
2556                 return 0;
2557
2558         if (private_key_passwd) {
2559                 passwd = os_strdup(private_key_passwd);
2560                 if (passwd == NULL)
2561                         return -1;
2562         } else
2563                 passwd = NULL;
2564
2565         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
2566         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
2567         if (
2568 #ifndef OPENSSL_NO_STDIO
2569             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2570                                         SSL_FILETYPE_ASN1) != 1 &&
2571             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
2572                                         SSL_FILETYPE_PEM) != 1 &&
2573 #endif /* OPENSSL_NO_STDIO */
2574             tls_read_pkcs12(data, NULL, private_key, passwd)) {
2575                 tls_show_errors(MSG_INFO, __func__,
2576                                 "Failed to load private key");
2577                 os_free(passwd);
2578                 ERR_clear_error();
2579                 return -1;
2580         }
2581         os_free(passwd);
2582         ERR_clear_error();
2583         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
2584
2585         if (!SSL_CTX_check_private_key(ssl_ctx)) {
2586                 tls_show_errors(MSG_INFO, __func__,
2587                                 "Private key failed verification");
2588                 return -1;
2589         }
2590
2591         return 0;
2592 }
2593
2594
2595 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
2596 {
2597 #ifdef OPENSSL_NO_DH
2598         if (dh_file == NULL)
2599                 return 0;
2600         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2601                    "dh_file specified");
2602         return -1;
2603 #else /* OPENSSL_NO_DH */
2604         DH *dh;
2605         BIO *bio;
2606
2607         /* TODO: add support for dh_blob */
2608         if (dh_file == NULL)
2609                 return 0;
2610         if (conn == NULL)
2611                 return -1;
2612
2613         bio = BIO_new_file(dh_file, "r");
2614         if (bio == NULL) {
2615                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2616                            dh_file, ERR_error_string(ERR_get_error(), NULL));
2617                 return -1;
2618         }
2619         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2620         BIO_free(bio);
2621 #ifndef OPENSSL_NO_DSA
2622         while (dh == NULL) {
2623                 DSA *dsa;
2624                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2625                            " trying to parse as DSA params", dh_file,
2626                            ERR_error_string(ERR_get_error(), NULL));
2627                 bio = BIO_new_file(dh_file, "r");
2628                 if (bio == NULL)
2629                         break;
2630                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2631                 BIO_free(bio);
2632                 if (!dsa) {
2633                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2634                                    "'%s': %s", dh_file,
2635                                    ERR_error_string(ERR_get_error(), NULL));
2636                         break;
2637                 }
2638
2639                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2640                 dh = DSA_dup_DH(dsa);
2641                 DSA_free(dsa);
2642                 if (dh == NULL) {
2643                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2644                                    "params into DH params");
2645                         break;
2646                 }
2647                 break;
2648         }
2649 #endif /* !OPENSSL_NO_DSA */
2650         if (dh == NULL) {
2651                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2652                            "'%s'", dh_file);
2653                 return -1;
2654         }
2655
2656         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
2657                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2658                            "%s", dh_file,
2659                            ERR_error_string(ERR_get_error(), NULL));
2660                 DH_free(dh);
2661                 return -1;
2662         }
2663         DH_free(dh);
2664         return 0;
2665 #endif /* OPENSSL_NO_DH */
2666 }
2667
2668
2669 static int tls_global_dh(struct tls_data *data, const char *dh_file)
2670 {
2671 #ifdef OPENSSL_NO_DH
2672         if (dh_file == NULL)
2673                 return 0;
2674         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
2675                    "dh_file specified");
2676         return -1;
2677 #else /* OPENSSL_NO_DH */
2678         SSL_CTX *ssl_ctx = data->ssl;
2679         DH *dh;
2680         BIO *bio;
2681
2682         /* TODO: add support for dh_blob */
2683         if (dh_file == NULL)
2684                 return 0;
2685         if (ssl_ctx == NULL)
2686                 return -1;
2687
2688         bio = BIO_new_file(dh_file, "r");
2689         if (bio == NULL) {
2690                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
2691                            dh_file, ERR_error_string(ERR_get_error(), NULL));
2692                 return -1;
2693         }
2694         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
2695         BIO_free(bio);
2696 #ifndef OPENSSL_NO_DSA
2697         while (dh == NULL) {
2698                 DSA *dsa;
2699                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
2700                            " trying to parse as DSA params", dh_file,
2701                            ERR_error_string(ERR_get_error(), NULL));
2702                 bio = BIO_new_file(dh_file, "r");
2703                 if (bio == NULL)
2704                         break;
2705                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
2706                 BIO_free(bio);
2707                 if (!dsa) {
2708                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
2709                                    "'%s': %s", dh_file,
2710                                    ERR_error_string(ERR_get_error(), NULL));
2711                         break;
2712                 }
2713
2714                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
2715                 dh = DSA_dup_DH(dsa);
2716                 DSA_free(dsa);
2717                 if (dh == NULL) {
2718                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
2719                                    "params into DH params");
2720                         break;
2721                 }
2722                 break;
2723         }
2724 #endif /* !OPENSSL_NO_DSA */
2725         if (dh == NULL) {
2726                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
2727                            "'%s'", dh_file);
2728                 return -1;
2729         }
2730
2731         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
2732                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
2733                            "%s", dh_file,
2734                            ERR_error_string(ERR_get_error(), NULL));
2735                 DH_free(dh);
2736                 return -1;
2737         }
2738         DH_free(dh);
2739         return 0;
2740 #endif /* OPENSSL_NO_DH */
2741 }
2742
2743
2744 int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
2745                               struct tls_random *keys)
2746 {
2747         SSL *ssl;
2748
2749         if (conn == NULL || keys == NULL)
2750                 return -1;
2751         ssl = conn->ssl;
2752 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2753         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2754                 return -1;
2755
2756         os_memset(keys, 0, sizeof(*keys));
2757         keys->client_random = ssl->s3->client_random;
2758         keys->client_random_len = SSL3_RANDOM_SIZE;
2759         keys->server_random = ssl->s3->server_random;
2760         keys->server_random_len = SSL3_RANDOM_SIZE;
2761 #else
2762         if (ssl == NULL)
2763                 return -1;
2764
2765         os_memset(keys, 0, sizeof(*keys));
2766         keys->client_random = conn->client_random;
2767         keys->client_random_len = SSL_get_client_random(
2768                 ssl, conn->client_random, sizeof(conn->client_random));
2769         keys->server_random = conn->server_random;
2770         keys->server_random_len = SSL_get_server_random(
2771                 ssl, conn->server_random, sizeof(conn->server_random));
2772 #endif
2773
2774         return 0;
2775 }
2776
2777
2778 #ifndef CONFIG_FIPS
2779 static int openssl_get_keyblock_size(SSL *ssl)
2780 {
2781 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2782         const EVP_CIPHER *c;
2783         const EVP_MD *h;
2784         int md_size;
2785
2786         if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
2787             ssl->read_hash == NULL)
2788                 return -1;
2789
2790         c = ssl->enc_read_ctx->cipher;
2791 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2792         h = EVP_MD_CTX_md(ssl->read_hash);
2793 #else
2794         h = ssl->read_hash;
2795 #endif
2796         if (h)
2797                 md_size = EVP_MD_size(h);
2798 #if OPENSSL_VERSION_NUMBER >= 0x10000000L
2799         else if (ssl->s3)
2800                 md_size = ssl->s3->tmp.new_mac_secret_size;
2801 #endif
2802         else
2803                 return -1;
2804
2805         wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
2806                    "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
2807                    EVP_CIPHER_iv_length(c));
2808         return 2 * (EVP_CIPHER_key_length(c) +
2809                     md_size +
2810                     EVP_CIPHER_iv_length(c));
2811 #else
2812         const SSL_CIPHER *ssl_cipher;
2813         int cipher, digest;
2814         const EVP_CIPHER *c;
2815         const EVP_MD *h;
2816
2817         ssl_cipher = SSL_get_current_cipher(ssl);
2818         if (!ssl_cipher)
2819                 return -1;
2820         cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
2821         digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
2822         wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
2823                    cipher, digest);
2824         if (cipher < 0 || digest < 0)
2825                 return -1;
2826         c = EVP_get_cipherbynid(cipher);
2827         h = EVP_get_digestbynid(digest);
2828         if (!c || !h)
2829                 return -1;
2830
2831         wpa_printf(MSG_DEBUG,
2832                    "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
2833                    EVP_CIPHER_key_length(c), EVP_MD_size(h),
2834                    EVP_CIPHER_iv_length(c));
2835         return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
2836                     EVP_CIPHER_iv_length(c));
2837 #endif
2838 }
2839 #endif /* CONFIG_FIPS */
2840
2841
2842 static int openssl_tls_prf(struct tls_connection *conn,
2843                            const char *label, int server_random_first,
2844                            int skip_keyblock, u8 *out, size_t out_len)
2845 {
2846 #ifdef CONFIG_FIPS
2847         wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
2848                    "mode");
2849         return -1;
2850 #else /* CONFIG_FIPS */
2851 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2852         SSL *ssl;
2853         u8 *rnd;
2854         int ret = -1;
2855         int skip = 0;
2856         u8 *tmp_out = NULL;
2857         u8 *_out = out;
2858         const char *ver;
2859
2860         /*
2861          * TLS library did not support key generation, so get the needed TLS
2862          * session parameters and use an internal implementation of TLS PRF to
2863          * derive the key.
2864          */
2865
2866         if (conn == NULL)
2867                 return -1;
2868         ssl = conn->ssl;
2869         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
2870             ssl->session->master_key_length <= 0)
2871                 return -1;
2872         ver = SSL_get_version(ssl);
2873
2874         if (skip_keyblock) {
2875                 skip = openssl_get_keyblock_size(ssl);
2876                 if (skip < 0)
2877                         return -1;
2878                 tmp_out = os_malloc(skip + out_len);
2879                 if (!tmp_out)
2880                         return -1;
2881                 _out = tmp_out;
2882         }
2883
2884         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2885         if (!rnd) {
2886                 os_free(tmp_out);
2887                 return -1;
2888         }
2889
2890         if (server_random_first) {
2891                 os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
2892                 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
2893                         SSL3_RANDOM_SIZE);
2894         } else {
2895                 os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
2896                 os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
2897                         SSL3_RANDOM_SIZE);
2898         }
2899
2900         if (os_strcmp(ver, "TLSv1.2") == 0) {
2901                 tls_prf_sha256(ssl->session->master_key,
2902                                ssl->session->master_key_length,
2903                                label, rnd, 2 * SSL3_RANDOM_SIZE,
2904                                _out, skip + out_len);
2905                 ret = 0;
2906         } else if (tls_prf_sha1_md5(ssl->session->master_key,
2907                                     ssl->session->master_key_length,
2908                                     label, rnd, 2 * SSL3_RANDOM_SIZE,
2909                                     _out, skip + out_len) == 0) {
2910                 ret = 0;
2911         }
2912         os_free(rnd);
2913         if (ret == 0 && skip_keyblock)
2914                 os_memcpy(out, _out + skip, out_len);
2915         bin_clear_free(tmp_out, skip);
2916
2917         return ret;
2918 #else
2919         SSL *ssl;
2920         SSL_SESSION *sess;
2921         u8 *rnd;
2922         int ret = -1;
2923         int skip = 0;
2924         u8 *tmp_out = NULL;
2925         u8 *_out = out;
2926         unsigned char client_random[SSL3_RANDOM_SIZE];
2927         unsigned char server_random[SSL3_RANDOM_SIZE];
2928         unsigned char master_key[64];
2929         size_t master_key_len;
2930         const char *ver;
2931
2932         /*
2933          * TLS library did not support key generation, so get the needed TLS
2934          * session parameters and use an internal implementation of TLS PRF to
2935          * derive the key.
2936          */
2937
2938         if (conn == NULL)
2939                 return -1;
2940         ssl = conn->ssl;
2941         if (ssl == NULL)
2942                 return -1;
2943         ver = SSL_get_version(ssl);
2944         sess = SSL_get_session(ssl);
2945         if (!ver || !sess)
2946                 return -1;
2947
2948         if (skip_keyblock) {
2949                 skip = openssl_get_keyblock_size(ssl);
2950                 if (skip < 0)
2951                         return -1;
2952                 tmp_out = os_malloc(skip + out_len);
2953                 if (!tmp_out)
2954                         return -1;
2955                 _out = tmp_out;
2956         }
2957
2958         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
2959         if (!rnd) {
2960                 os_free(tmp_out);
2961                 return -1;
2962         }
2963
2964         SSL_get_client_random(ssl, client_random, sizeof(client_random));
2965         SSL_get_server_random(ssl, server_random, sizeof(server_random));
2966         master_key_len = SSL_SESSION_get_master_key(sess, master_key,
2967                                                     sizeof(master_key));
2968
2969         if (server_random_first) {
2970                 os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
2971                 os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random,
2972                           SSL3_RANDOM_SIZE);
2973         } else {
2974                 os_memcpy(rnd, client_random, SSL3_RANDOM_SIZE);
2975                 os_memcpy(rnd + SSL3_RANDOM_SIZE, server_random,
2976                           SSL3_RANDOM_SIZE);
2977         }
2978
2979         if (os_strcmp(ver, "TLSv1.2") == 0) {
2980                 tls_prf_sha256(master_key, master_key_len,
2981                                label, rnd, 2 * SSL3_RANDOM_SIZE,
2982                                _out, skip + out_len);
2983                 ret = 0;
2984         } else if (tls_prf_sha1_md5(master_key, master_key_len,
2985                                     label, rnd, 2 * SSL3_RANDOM_SIZE,
2986                                     _out, skip + out_len) == 0) {
2987                 ret = 0;
2988         }
2989         os_memset(master_key, 0, sizeof(master_key));
2990         os_free(rnd);
2991         if (ret == 0 && skip_keyblock)
2992                 os_memcpy(out, _out + skip, out_len);
2993         bin_clear_free(tmp_out, skip);
2994
2995         return ret;
2996 #endif
2997 #endif /* CONFIG_FIPS */
2998 }
2999
3000
3001 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
3002                        const char *label, int server_random_first,
3003                        int skip_keyblock, u8 *out, size_t out_len)
3004 {
3005 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3006         SSL *ssl;
3007         if (conn == NULL)
3008                 return -1;
3009         if (server_random_first || skip_keyblock)
3010                 return openssl_tls_prf(conn, label,
3011                                        server_random_first, skip_keyblock,
3012                                        out, out_len);
3013         ssl = conn->ssl;
3014         if (SSL_export_keying_material(ssl, out, out_len, label,
3015                                        os_strlen(label), NULL, 0, 0) == 1) {
3016                 wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
3017                 return 0;
3018         }
3019 #endif
3020         return openssl_tls_prf(conn, label, server_random_first,
3021                                skip_keyblock, out, out_len);
3022 }
3023
3024
3025 static struct wpabuf *
3026 openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
3027                   int server)
3028 {
3029         int res;
3030         struct wpabuf *out_data;
3031
3032         /*
3033          * Give TLS handshake data from the server (if available) to OpenSSL
3034          * for processing.
3035          */
3036         if (in_data && wpabuf_len(in_data) > 0 &&
3037             BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
3038             < 0) {
3039                 tls_show_errors(MSG_INFO, __func__,
3040                                 "Handshake failed - BIO_write");
3041                 return NULL;
3042         }
3043
3044         /* Initiate TLS handshake or continue the existing handshake */
3045         if (server)
3046                 res = SSL_accept(conn->ssl);
3047         else
3048                 res = SSL_connect(conn->ssl);
3049         if (res != 1) {
3050                 int err = SSL_get_error(conn->ssl, res);
3051                 if (err == SSL_ERROR_WANT_READ)
3052                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
3053                                    "more data");
3054                 else if (err == SSL_ERROR_WANT_WRITE)
3055                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
3056                                    "write");
3057                 else {
3058                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
3059                         conn->failed++;
3060                 }
3061         }
3062
3063         /* Get the TLS handshake data to be sent to the server */
3064         res = BIO_ctrl_pending(conn->ssl_out);
3065         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
3066         out_data = wpabuf_alloc(res);
3067         if (out_data == NULL) {
3068                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
3069                            "handshake output (%d bytes)", res);
3070                 if (BIO_reset(conn->ssl_out) < 0) {
3071                         tls_show_errors(MSG_INFO, __func__,
3072                                         "BIO_reset failed");
3073                 }
3074                 return NULL;
3075         }
3076         res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
3077                                       res);
3078         if (res < 0) {
3079                 tls_show_errors(MSG_INFO, __func__,
3080                                 "Handshake failed - BIO_read");
3081                 if (BIO_reset(conn->ssl_out) < 0) {
3082                         tls_show_errors(MSG_INFO, __func__,
3083                                         "BIO_reset failed");
3084                 }
3085                 wpabuf_free(out_data);
3086                 return NULL;
3087         }
3088         wpabuf_put(out_data, res);
3089
3090         return out_data;
3091 }
3092
3093
3094 static struct wpabuf *
3095 openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
3096 {
3097         struct wpabuf *appl_data;
3098         int res;
3099
3100         appl_data = wpabuf_alloc(max_len + 100);
3101         if (appl_data == NULL)
3102                 return NULL;
3103
3104         res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
3105                        wpabuf_size(appl_data));
3106         if (res < 0) {
3107                 int err = SSL_get_error(conn->ssl, res);
3108                 if (err == SSL_ERROR_WANT_READ ||
3109                     err == SSL_ERROR_WANT_WRITE) {
3110                         wpa_printf(MSG_DEBUG, "SSL: No Application Data "
3111                                    "included");
3112                 } else {
3113                         tls_show_errors(MSG_INFO, __func__,
3114                                         "Failed to read possible "
3115                                         "Application Data");
3116                 }
3117                 wpabuf_free(appl_data);
3118                 return NULL;
3119         }
3120
3121         wpabuf_put(appl_data, res);
3122         wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
3123                             "message", appl_data);
3124
3125         return appl_data;
3126 }
3127
3128
3129 static struct wpabuf *
3130 openssl_connection_handshake(struct tls_connection *conn,
3131                              const struct wpabuf *in_data,
3132                              struct wpabuf **appl_data, int server)
3133 {
3134         struct wpabuf *out_data;
3135
3136         if (appl_data)
3137                 *appl_data = NULL;
3138
3139         out_data = openssl_handshake(conn, in_data, server);
3140         if (out_data == NULL)
3141                 return NULL;
3142         if (conn->invalid_hb_used) {
3143                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3144                 wpabuf_free(out_data);
3145                 return NULL;
3146         }
3147
3148         if (SSL_is_init_finished(conn->ssl)) {
3149                 wpa_printf(MSG_DEBUG,
3150                            "OpenSSL: Handshake finished - resumed=%d",
3151                            tls_connection_resumed(conn->ssl_ctx, conn));
3152                 if (appl_data && in_data)
3153                         *appl_data = openssl_get_appl_data(conn,
3154                                                            wpabuf_len(in_data));
3155         }
3156
3157         if (conn->invalid_hb_used) {
3158                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3159                 if (appl_data) {
3160                         wpabuf_free(*appl_data);
3161                         *appl_data = NULL;
3162                 }
3163                 wpabuf_free(out_data);
3164                 return NULL;
3165         }
3166
3167         return out_data;
3168 }
3169
3170
3171 struct wpabuf *
3172 tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
3173                          const struct wpabuf *in_data,
3174                          struct wpabuf **appl_data)
3175 {
3176         return openssl_connection_handshake(conn, in_data, appl_data, 0);
3177 }
3178
3179
3180 struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
3181                                                 struct tls_connection *conn,
3182                                                 const struct wpabuf *in_data,
3183                                                 struct wpabuf **appl_data)
3184 {
3185         return openssl_connection_handshake(conn, in_data, appl_data, 1);
3186 }
3187
3188
3189 struct wpabuf * tls_connection_encrypt(void *tls_ctx,
3190                                        struct tls_connection *conn,
3191                                        const struct wpabuf *in_data)
3192 {
3193         int res;
3194         struct wpabuf *buf;
3195
3196         if (conn == NULL)
3197                 return NULL;
3198
3199         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
3200         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
3201             (res = BIO_reset(conn->ssl_out)) < 0) {
3202                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3203                 return NULL;
3204         }
3205         res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
3206         if (res < 0) {
3207                 tls_show_errors(MSG_INFO, __func__,
3208                                 "Encryption failed - SSL_write");
3209                 return NULL;
3210         }
3211
3212         /* Read encrypted data to be sent to the server */
3213         buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
3214         if (buf == NULL)
3215                 return NULL;
3216         res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
3217         if (res < 0) {
3218                 tls_show_errors(MSG_INFO, __func__,
3219                                 "Encryption failed - BIO_read");
3220                 wpabuf_free(buf);
3221                 return NULL;
3222         }
3223         wpabuf_put(buf, res);
3224
3225         return buf;
3226 }
3227
3228
3229 struct wpabuf * tls_connection_decrypt(void *tls_ctx,
3230                                        struct tls_connection *conn,
3231                                        const struct wpabuf *in_data)
3232 {
3233         int res;
3234         struct wpabuf *buf;
3235
3236         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
3237         res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
3238                         wpabuf_len(in_data));
3239         if (res < 0) {
3240                 tls_show_errors(MSG_INFO, __func__,
3241                                 "Decryption failed - BIO_write");
3242                 return NULL;
3243         }
3244         if (BIO_reset(conn->ssl_out) < 0) {
3245                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
3246                 return NULL;
3247         }
3248
3249         /* Read decrypted data for further processing */
3250         /*
3251          * Even though we try to disable TLS compression, it is possible that
3252          * this cannot be done with all TLS libraries. Add extra buffer space
3253          * to handle the possibility of the decrypted data being longer than
3254          * input data.
3255          */
3256         buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
3257         if (buf == NULL)
3258                 return NULL;
3259         res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
3260         if (res < 0) {
3261                 tls_show_errors(MSG_INFO, __func__,
3262                                 "Decryption failed - SSL_read");
3263                 wpabuf_free(buf);
3264                 return NULL;
3265         }
3266         wpabuf_put(buf, res);
3267
3268         if (conn->invalid_hb_used) {
3269                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
3270                 wpabuf_free(buf);
3271                 return NULL;
3272         }
3273
3274         return buf;
3275 }
3276
3277
3278 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
3279 {
3280 #if OPENSSL_VERSION_NUMBER >= 0x10001000L
3281         return conn ? SSL_cache_hit(conn->ssl) : 0;
3282 #else
3283         return conn ? conn->ssl->hit : 0;
3284 #endif
3285 }
3286
3287
3288 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
3289                                    u8 *ciphers)
3290 {
3291         char buf[100], *pos, *end;
3292         u8 *c;
3293         int ret;
3294
3295         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
3296                 return -1;
3297
3298         buf[0] = '\0';
3299         pos = buf;
3300         end = pos + sizeof(buf);
3301
3302         c = ciphers;
3303         while (*c != TLS_CIPHER_NONE) {
3304                 const char *suite;
3305
3306                 switch (*c) {
3307                 case TLS_CIPHER_RC4_SHA:
3308                         suite = "RC4-SHA";
3309                         break;
3310                 case TLS_CIPHER_AES128_SHA:
3311                         suite = "AES128-SHA";
3312                         break;
3313                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
3314                         suite = "DHE-RSA-AES128-SHA";
3315                         break;
3316                 case TLS_CIPHER_ANON_DH_AES128_SHA:
3317                         suite = "ADH-AES128-SHA";
3318                         break;
3319                 default:
3320                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
3321                                    "cipher selection: %d", *c);
3322                         return -1;
3323                 }
3324                 ret = os_snprintf(pos, end - pos, ":%s", suite);
3325                 if (os_snprintf_error(end - pos, ret))
3326                         break;
3327                 pos += ret;
3328
3329                 c++;
3330         }
3331
3332         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
3333
3334 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
3335 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3336         if (os_strstr(buf, ":ADH-")) {
3337                 /*
3338                  * Need to drop to security level 0 to allow anonymous
3339                  * cipher suites for EAP-FAST.
3340                  */
3341                 SSL_set_security_level(conn->ssl, 0);
3342         } else if (SSL_get_security_level(conn->ssl) == 0) {
3343                 /* Force at least security level 1 */
3344                 SSL_set_security_level(conn->ssl, 1);
3345         }
3346 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3347 #endif
3348
3349         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
3350                 tls_show_errors(MSG_INFO, __func__,
3351                                 "Cipher suite configuration failed");
3352                 return -1;
3353         }
3354
3355         return 0;
3356 }
3357
3358
3359 int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
3360                     char *buf, size_t buflen)
3361 {
3362         const char *name;
3363         if (conn == NULL || conn->ssl == NULL)
3364                 return -1;
3365
3366         name = SSL_get_version(conn->ssl);
3367         if (name == NULL)
3368                 return -1;
3369
3370         os_strlcpy(buf, name, buflen);
3371         return 0;
3372 }
3373
3374
3375 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
3376                    char *buf, size_t buflen)
3377 {
3378         const char *name;
3379         if (conn == NULL || conn->ssl == NULL)
3380                 return -1;
3381
3382         name = SSL_get_cipher(conn->ssl);
3383         if (name == NULL)
3384                 return -1;
3385
3386         os_strlcpy(buf, name, buflen);
3387         return 0;
3388 }
3389
3390
3391 int tls_connection_enable_workaround(void *ssl_ctx,
3392                                      struct tls_connection *conn)
3393 {
3394         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
3395
3396         return 0;
3397 }
3398
3399
3400 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3401 /* ClientHello TLS extensions require a patch to openssl, so this function is
3402  * commented out unless explicitly needed for EAP-FAST in order to be able to
3403  * build this file with unmodified openssl. */
3404 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
3405                                     int ext_type, const u8 *data,
3406                                     size_t data_len)
3407 {
3408         if (conn == NULL || conn->ssl == NULL || ext_type != 35)
3409                 return -1;
3410
3411         if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
3412                                        data_len) != 1)
3413                 return -1;
3414
3415         return 0;
3416 }
3417 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3418
3419
3420 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
3421 {
3422         if (conn == NULL)
3423                 return -1;
3424         return conn->failed;
3425 }
3426
3427
3428 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
3429 {
3430         if (conn == NULL)
3431                 return -1;
3432         return conn->read_alerts;
3433 }
3434
3435
3436 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
3437 {
3438         if (conn == NULL)
3439                 return -1;
3440         return conn->write_alerts;
3441 }
3442
3443
3444 #ifdef HAVE_OCSP
3445
3446 static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
3447 {
3448 #ifndef CONFIG_NO_STDOUT_DEBUG
3449         BIO *out;
3450         size_t rlen;
3451         char *txt;
3452         int res;
3453
3454         if (wpa_debug_level > MSG_DEBUG)
3455                 return;
3456
3457         out = BIO_new(BIO_s_mem());
3458         if (!out)
3459                 return;
3460
3461         OCSP_RESPONSE_print(out, rsp, 0);
3462         rlen = BIO_ctrl_pending(out);
3463         txt = os_malloc(rlen + 1);
3464         if (!txt) {
3465                 BIO_free(out);
3466                 return;
3467         }
3468
3469         res = BIO_read(out, txt, rlen);
3470         if (res > 0) {
3471                 txt[res] = '\0';
3472                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
3473         }
3474         os_free(txt);
3475         BIO_free(out);
3476 #endif /* CONFIG_NO_STDOUT_DEBUG */
3477 }
3478
3479
3480 static void debug_print_cert(X509 *cert, const char *title)
3481 {
3482 #ifndef CONFIG_NO_STDOUT_DEBUG
3483         BIO *out;
3484         size_t rlen;
3485         char *txt;
3486         int res;
3487
3488         if (wpa_debug_level > MSG_DEBUG)
3489                 return;
3490
3491         out = BIO_new(BIO_s_mem());
3492         if (!out)
3493                 return;
3494
3495         X509_print(out, cert);
3496         rlen = BIO_ctrl_pending(out);
3497         txt = os_malloc(rlen + 1);
3498         if (!txt) {
3499                 BIO_free(out);
3500                 return;
3501         }
3502
3503         res = BIO_read(out, txt, rlen);
3504         if (res > 0) {
3505                 txt[res] = '\0';
3506                 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
3507         }
3508         os_free(txt);
3509
3510         BIO_free(out);
3511 #endif /* CONFIG_NO_STDOUT_DEBUG */
3512 }
3513
3514
3515 static int ocsp_resp_cb(SSL *s, void *arg)
3516 {
3517         struct tls_connection *conn = arg;
3518         const unsigned char *p;
3519         int len, status, reason;
3520         OCSP_RESPONSE *rsp;
3521         OCSP_BASICRESP *basic;
3522         OCSP_CERTID *id;
3523         ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
3524         X509_STORE *store;
3525         STACK_OF(X509) *certs = NULL;
3526
3527         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
3528         if (!p) {
3529                 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
3530                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3531         }
3532
3533         wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
3534
3535         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
3536         if (!rsp) {
3537                 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
3538                 return 0;
3539         }
3540
3541         ocsp_debug_print_resp(rsp);
3542
3543         status = OCSP_response_status(rsp);
3544         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
3545                 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
3546                            status, OCSP_response_status_str(status));
3547                 return 0;
3548         }
3549
3550         basic = OCSP_response_get1_basic(rsp);
3551         if (!basic) {
3552                 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
3553                 return 0;
3554         }
3555
3556         store = SSL_CTX_get_cert_store(conn->ssl_ctx);
3557         if (conn->peer_issuer) {
3558                 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
3559
3560                 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
3561                         tls_show_errors(MSG_INFO, __func__,
3562                                         "OpenSSL: Could not add issuer to certificate store");
3563                 }
3564                 certs = sk_X509_new_null();
3565                 if (certs) {
3566                         X509 *cert;
3567                         cert = X509_dup(conn->peer_issuer);
3568                         if (cert && !sk_X509_push(certs, cert)) {
3569                                 tls_show_errors(
3570                                         MSG_INFO, __func__,
3571                                         "OpenSSL: Could not add issuer to OCSP responder trust store");
3572                                 X509_free(cert);
3573                                 sk_X509_free(certs);
3574                                 certs = NULL;
3575                         }
3576                         if (certs && conn->peer_issuer_issuer) {
3577                                 cert = X509_dup(conn->peer_issuer_issuer);
3578                                 if (cert && !sk_X509_push(certs, cert)) {
3579                                         tls_show_errors(
3580                                                 MSG_INFO, __func__,
3581                                                 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
3582                                         X509_free(cert);
3583                                 }
3584                         }
3585                 }
3586         }
3587
3588         status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
3589         sk_X509_pop_free(certs, X509_free);
3590         if (status <= 0) {
3591                 tls_show_errors(MSG_INFO, __func__,
3592                                 "OpenSSL: OCSP response failed verification");
3593                 OCSP_BASICRESP_free(basic);
3594                 OCSP_RESPONSE_free(rsp);
3595                 return 0;
3596         }
3597
3598         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
3599
3600         if (!conn->peer_cert) {
3601                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
3602                 OCSP_BASICRESP_free(basic);
3603                 OCSP_RESPONSE_free(rsp);
3604                 return 0;
3605         }
3606
3607         if (!conn->peer_issuer) {
3608                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
3609                 OCSP_BASICRESP_free(basic);
3610                 OCSP_RESPONSE_free(rsp);
3611                 return 0;
3612         }
3613
3614         id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
3615         if (!id) {
3616                 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
3617                 OCSP_BASICRESP_free(basic);
3618                 OCSP_RESPONSE_free(rsp);
3619                 return 0;
3620         }
3621
3622         if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
3623                                    &this_update, &next_update)) {
3624                 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
3625                            (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
3626                            " (OCSP not required)");
3627                 OCSP_BASICRESP_free(basic);
3628                 OCSP_RESPONSE_free(rsp);
3629                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
3630         }
3631
3632         if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
3633                 tls_show_errors(MSG_INFO, __func__,
3634                                 "OpenSSL: OCSP status times invalid");
3635                 OCSP_BASICRESP_free(basic);
3636                 OCSP_RESPONSE_free(rsp);
3637                 return 0;
3638         }
3639
3640         OCSP_BASICRESP_free(basic);
3641         OCSP_RESPONSE_free(rsp);
3642
3643         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
3644                    OCSP_cert_status_str(status));
3645
3646         if (status == V_OCSP_CERTSTATUS_GOOD)
3647                 return 1;
3648         if (status == V_OCSP_CERTSTATUS_REVOKED)
3649                 return 0;
3650         if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
3651                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
3652                 return 0;
3653         }
3654         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
3655         return 1;
3656 }
3657
3658
3659 static int ocsp_status_cb(SSL *s, void *arg)
3660 {
3661         char *tmp;
3662         char *resp;
3663         size_t len;
3664
3665         if (tls_global->ocsp_stapling_response == NULL) {
3666                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
3667                 return SSL_TLSEXT_ERR_OK;
3668         }
3669
3670         resp = os_readfile(tls_global->ocsp_stapling_response, &len);
3671         if (resp == NULL) {
3672                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
3673                 /* TODO: Build OCSPResponse with responseStatus = internalError
3674                  */
3675                 return SSL_TLSEXT_ERR_OK;
3676         }
3677         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
3678         tmp = OPENSSL_malloc(len);
3679         if (tmp == NULL) {
3680                 os_free(resp);
3681                 return SSL_TLSEXT_ERR_ALERT_FATAL;
3682         }
3683
3684         os_memcpy(tmp, resp, len);
3685         os_free(resp);
3686         SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
3687
3688         return SSL_TLSEXT_ERR_OK;
3689 }
3690
3691 #endif /* HAVE_OCSP */
3692
3693
3694 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
3695                               const struct tls_connection_params *params)
3696 {
3697         struct tls_data *data = tls_ctx;
3698         int ret;
3699         unsigned long err;
3700         int can_pkcs11 = 0;
3701         const char *key_id = params->key_id;
3702         const char *cert_id = params->cert_id;
3703         const char *ca_cert_id = params->ca_cert_id;
3704         const char *engine_id = params->engine ? params->engine_id : NULL;
3705
3706         if (conn == NULL)
3707                 return -1;
3708
3709         /*
3710          * If the engine isn't explicitly configured, and any of the
3711          * cert/key fields are actually PKCS#11 URIs, then automatically
3712          * use the PKCS#11 ENGINE.
3713          */
3714         if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
3715                 can_pkcs11 = 1;
3716
3717         if (!key_id && params->private_key && can_pkcs11 &&
3718             os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
3719                 can_pkcs11 = 2;
3720                 key_id = params->private_key;
3721         }
3722
3723         if (!cert_id && params->client_cert && can_pkcs11 &&
3724             os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
3725                 can_pkcs11 = 2;
3726                 cert_id = params->client_cert;
3727         }
3728
3729         if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
3730             os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
3731                 can_pkcs11 = 2;
3732                 ca_cert_id = params->ca_cert;
3733         }
3734
3735         /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
3736         if (can_pkcs11 == 2 && !engine_id)
3737                 engine_id = "pkcs11";
3738
3739 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3740 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3741         if (params->flags & TLS_CONN_EAP_FAST) {
3742                 wpa_printf(MSG_DEBUG,
3743                            "OpenSSL: Use TLSv1_method() for EAP-FAST");
3744                 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
3745                         tls_show_errors(MSG_INFO, __func__,
3746                                         "Failed to set TLSv1_method() for EAP-FAST");
3747                         return -1;
3748                 }
3749         }
3750 #endif
3751 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3752
3753         while ((err = ERR_get_error())) {
3754                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3755                            __func__, ERR_error_string(err, NULL));
3756         }
3757
3758         if (engine_id) {
3759                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
3760                 ret = tls_engine_init(conn, engine_id, params->pin,
3761                                       key_id, cert_id, ca_cert_id);
3762                 if (ret)
3763                         return ret;
3764         }
3765         if (tls_connection_set_subject_match(conn,
3766                                              params->subject_match,
3767                                              params->altsubject_match,
3768                                              params->suffix_match,
3769                                              params->domain_match))
3770                 return -1;
3771
3772         if (engine_id && ca_cert_id) {
3773                 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
3774                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3775         } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
3776                                           params->ca_cert_blob,
3777                                           params->ca_cert_blob_len,
3778                                           params->ca_path))
3779                 return -1;
3780
3781         if (engine_id && cert_id) {
3782                 if (tls_connection_engine_client_cert(conn, cert_id))
3783                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3784         } else if (tls_connection_client_cert(conn, params->client_cert,
3785                                               params->client_cert_blob,
3786                                               params->client_cert_blob_len))
3787                 return -1;
3788
3789         if (engine_id && key_id) {
3790                 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
3791                 if (tls_connection_engine_private_key(conn))
3792                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
3793         } else if (tls_connection_private_key(data, conn,
3794                                               params->private_key,
3795                                               params->private_key_passwd,
3796                                               params->private_key_blob,
3797                                               params->private_key_blob_len)) {
3798                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
3799                            params->private_key);
3800                 return -1;
3801         }
3802
3803         if (tls_connection_dh(conn, params->dh_file)) {
3804                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
3805                            params->dh_file);
3806                 return -1;
3807         }
3808
3809         if (params->openssl_ciphers &&
3810             SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
3811                 wpa_printf(MSG_INFO,
3812                            "OpenSSL: Failed to set cipher string '%s'",
3813                            params->openssl_ciphers);
3814                 return -1;
3815         }
3816
3817         tls_set_conn_flags(conn->ssl, params->flags);
3818
3819 #ifdef HAVE_OCSP
3820         if (params->flags & TLS_CONN_REQUEST_OCSP) {
3821                 SSL_CTX *ssl_ctx = data->ssl;
3822                 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
3823                 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
3824                 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
3825         }
3826 #else /* HAVE_OCSP */
3827         if (params->flags & TLS_CONN_REQUIRE_OCSP) {
3828                 wpa_printf(MSG_INFO,
3829                            "OpenSSL: No OCSP support included - reject configuration");
3830                 return -1;
3831         }
3832         if (params->flags & TLS_CONN_REQUEST_OCSP) {
3833                 wpa_printf(MSG_DEBUG,
3834                            "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
3835         }
3836 #endif /* HAVE_OCSP */
3837
3838         conn->flags = params->flags;
3839
3840         tls_get_errors(data);
3841
3842         return 0;
3843 }
3844
3845
3846 int tls_global_set_params(void *tls_ctx,
3847                           const struct tls_connection_params *params)
3848 {
3849         struct tls_data *data = tls_ctx;
3850         SSL_CTX *ssl_ctx = data->ssl;
3851         unsigned long err;
3852
3853         while ((err = ERR_get_error())) {
3854                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
3855                            __func__, ERR_error_string(err, NULL));
3856         }
3857
3858         if (tls_global_ca_cert(data, params->ca_cert) ||
3859             tls_global_client_cert(data, params->client_cert) ||
3860             tls_global_private_key(data, params->private_key,
3861                                    params->private_key_passwd) ||
3862             tls_global_dh(data, params->dh_file)) {
3863                 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
3864                 return -1;
3865         }
3866
3867         if (params->openssl_ciphers &&
3868             SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
3869                 wpa_printf(MSG_INFO,
3870                            "OpenSSL: Failed to set cipher string '%s'",
3871                            params->openssl_ciphers);
3872                 return -1;
3873         }
3874
3875 #ifdef SSL_OP_NO_TICKET
3876         if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
3877                 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
3878 #ifdef SSL_CTX_clear_options
3879         else
3880                 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
3881 #endif /* SSL_clear_options */
3882 #endif /*  SSL_OP_NO_TICKET */
3883
3884 #ifdef HAVE_OCSP
3885         SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
3886         SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
3887         os_free(tls_global->ocsp_stapling_response);
3888         if (params->ocsp_stapling_response)
3889                 tls_global->ocsp_stapling_response =
3890                         os_strdup(params->ocsp_stapling_response);
3891         else
3892                 tls_global->ocsp_stapling_response = NULL;
3893 #endif /* HAVE_OCSP */
3894
3895         return 0;
3896 }
3897
3898
3899 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3900 /* Pre-shared secred requires a patch to openssl, so this function is
3901  * commented out unless explicitly needed for EAP-FAST in order to be able to
3902  * build this file with unmodified openssl. */
3903
3904 #ifdef OPENSSL_IS_BORINGSSL
3905 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3906                            STACK_OF(SSL_CIPHER) *peer_ciphers,
3907                            const SSL_CIPHER **cipher, void *arg)
3908 #else /* OPENSSL_IS_BORINGSSL */
3909 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
3910                            STACK_OF(SSL_CIPHER) *peer_ciphers,
3911                            SSL_CIPHER **cipher, void *arg)
3912 #endif /* OPENSSL_IS_BORINGSSL */
3913 {
3914         struct tls_connection *conn = arg;
3915         int ret;
3916
3917 #if OPENSSL_VERSION_NUMBER < 0x10100000L
3918         if (conn == NULL || conn->session_ticket_cb == NULL)
3919                 return 0;
3920
3921         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3922                                       conn->session_ticket,
3923                                       conn->session_ticket_len,
3924                                       s->s3->client_random,
3925                                       s->s3->server_random, secret);
3926 #else
3927         unsigned char client_random[SSL3_RANDOM_SIZE];
3928         unsigned char server_random[SSL3_RANDOM_SIZE];
3929
3930         if (conn == NULL || conn->session_ticket_cb == NULL)
3931                 return 0;
3932
3933         SSL_get_client_random(s, client_random, sizeof(client_random));
3934         SSL_get_server_random(s, server_random, sizeof(server_random));
3935
3936         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
3937                                       conn->session_ticket,
3938                                       conn->session_ticket_len,
3939                                       client_random,
3940                                       server_random, secret);
3941 #endif
3942
3943         os_free(conn->session_ticket);
3944         conn->session_ticket = NULL;
3945
3946         if (ret <= 0)
3947                 return 0;
3948
3949         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
3950         return 1;
3951 }
3952
3953
3954 static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
3955                                      int len, void *arg)
3956 {
3957         struct tls_connection *conn = arg;
3958
3959         if (conn == NULL || conn->session_ticket_cb == NULL)
3960                 return 0;
3961
3962         wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
3963
3964         os_free(conn->session_ticket);
3965         conn->session_ticket = NULL;
3966
3967         wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
3968                     "extension", data, len);
3969
3970         conn->session_ticket = os_malloc(len);
3971         if (conn->session_ticket == NULL)
3972                 return 0;
3973
3974         os_memcpy(conn->session_ticket, data, len);
3975         conn->session_ticket_len = len;
3976
3977         return 1;
3978 }
3979 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
3980
3981
3982 int tls_connection_set_session_ticket_cb(void *tls_ctx,
3983                                          struct tls_connection *conn,
3984                                          tls_session_ticket_cb cb,
3985                                          void *ctx)
3986 {
3987 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
3988         conn->session_ticket_cb = cb;
3989         conn->session_ticket_cb_ctx = ctx;
3990
3991         if (cb) {
3992                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
3993                                               conn) != 1)
3994                         return -1;
3995                 SSL_set_session_ticket_ext_cb(conn->ssl,
3996                                               tls_session_ticket_ext_cb, conn);
3997         } else {
3998                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
3999                         return -1;
4000                 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
4001         }
4002
4003         return 0;
4004 #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4005         return -1;
4006 #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
4007 }
4008
4009
4010 int tls_get_library_version(char *buf, size_t buf_len)
4011 {
4012         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
4013                            OPENSSL_VERSION_TEXT,
4014                            SSLeay_version(SSLEAY_VERSION));
4015 }