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