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