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