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