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