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