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