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