Changed TLS server to use OpenSSL SSL_accept() instead of SSL_read()
[libeap.git] / src / crypto / tls_openssl.c
1 /*
2  * WPA Supplicant / SSL/TLS interface functions for openssl
3  * Copyright (c) 2004-2007, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "includes.h"
16
17 #ifndef CONFIG_SMARTCARD
18 #ifndef OPENSSL_NO_ENGINE
19 #define OPENSSL_NO_ENGINE
20 #endif
21 #endif
22
23 #include <openssl/ssl.h>
24 #include <openssl/err.h>
25 #include <openssl/pkcs12.h>
26 #include <openssl/x509v3.h>
27 #ifndef OPENSSL_NO_ENGINE
28 #include <openssl/engine.h>
29 #endif /* OPENSSL_NO_ENGINE */
30
31 #include "common.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 static int tls_openssl_ref_count = 0;
41
42 struct tls_connection {
43         SSL *ssl;
44         BIO *ssl_in, *ssl_out;
45 #ifndef OPENSSL_NO_ENGINE
46         ENGINE *engine;        /* functional reference to the engine */
47         EVP_PKEY *private_key; /* the private key if using engine */
48 #endif /* OPENSSL_NO_ENGINE */
49         char *subject_match, *altsubject_match;
50         int read_alerts, write_alerts, failed;
51
52         tls_session_ticket_cb session_ticket_cb;
53         void *session_ticket_cb_ctx;
54
55         /* SessionTicket received from OpenSSL hello_extension_cb (server) */
56         u8 *session_ticket;
57         size_t session_ticket_len;
58 };
59
60
61 #ifdef CONFIG_NO_STDOUT_DEBUG
62
63 static void _tls_show_errors(void)
64 {
65         unsigned long err;
66
67         while ((err = ERR_get_error())) {
68                 /* Just ignore the errors, since stdout is disabled */
69         }
70 }
71 #define tls_show_errors(l, f, t) _tls_show_errors()
72
73 #else /* CONFIG_NO_STDOUT_DEBUG */
74
75 static void tls_show_errors(int level, const char *func, const char *txt)
76 {
77         unsigned long err;
78
79         wpa_printf(level, "OpenSSL: %s - %s %s",
80                    func, txt, ERR_error_string(ERR_get_error(), NULL));
81
82         while ((err = ERR_get_error())) {
83                 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
84                            ERR_error_string(err, NULL));
85         }
86 }
87
88 #endif /* CONFIG_NO_STDOUT_DEBUG */
89
90
91 #ifdef CONFIG_NATIVE_WINDOWS
92
93 /* Windows CryptoAPI and access to certificate stores */
94 #include <wincrypt.h>
95
96 #ifdef __MINGW32_VERSION
97 /*
98  * MinGW does not yet include all the needed definitions for CryptoAPI, so
99  * define here whatever extra is needed.
100  */
101 #define CALG_SSL3_SHAMD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
102 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
103 #define CERT_STORE_READONLY_FLAG 0x00008000
104 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
105 #define CRYPT_ACQUIRE_COMPARE_KEY_FLAG 0x00000004
106
107 static BOOL WINAPI
108 (*CryptAcquireCertificatePrivateKey)(PCCERT_CONTEXT pCert, DWORD dwFlags,
109                                      void *pvReserved, HCRYPTPROV *phCryptProv,
110                                      DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
111 = NULL; /* to be loaded from crypt32.dll */
112
113 static PCCERT_CONTEXT WINAPI
114 (*CertEnumCertificatesInStore)(HCERTSTORE hCertStore,
115                                PCCERT_CONTEXT pPrevCertContext)
116 = NULL; /* to be loaded from crypt32.dll */
117
118 static int mingw_load_crypto_func(void)
119 {
120         HINSTANCE dll;
121
122         /* MinGW does not yet have full CryptoAPI support, so load the needed
123          * function here. */
124
125         if (CryptAcquireCertificatePrivateKey)
126                 return 0;
127
128         dll = LoadLibrary("crypt32");
129         if (dll == NULL) {
130                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not load crypt32 "
131                            "library");
132                 return -1;
133         }
134
135         CryptAcquireCertificatePrivateKey = GetProcAddress(
136                 dll, "CryptAcquireCertificatePrivateKey");
137         if (CryptAcquireCertificatePrivateKey == NULL) {
138                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
139                            "CryptAcquireCertificatePrivateKey() address from "
140                            "crypt32 library");
141                 return -1;
142         }
143
144         CertEnumCertificatesInStore = (void *) GetProcAddress(
145                 dll, "CertEnumCertificatesInStore");
146         if (CertEnumCertificatesInStore == NULL) {
147                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
148                            "CertEnumCertificatesInStore() address from "
149                            "crypt32 library");
150                 return -1;
151         }
152
153         return 0;
154 }
155
156 #else /* __MINGW32_VERSION */
157
158 static int mingw_load_crypto_func(void)
159 {
160         return 0;
161 }
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 (mingw_load_crypto_func())
393                 goto err;
394
395         if (!CryptAcquireCertificatePrivateKey(priv->cert,
396                                                CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
397                                                NULL, &priv->crypt_prov,
398                                                &priv->key_spec,
399                                                &priv->free_crypt_prov)) {
400                 cryptoapi_error("Failed to acquire a private key for the "
401                                 "certificate");
402                 goto err;
403         }
404
405         rsa_meth->name = "Microsoft CryptoAPI RSA Method";
406         rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
407         rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
408         rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
409         rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
410         rsa_meth->finish = cryptoapi_finish;
411         rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
412         rsa_meth->app_data = (char *) priv;
413
414         rsa = RSA_new();
415         if (rsa == NULL) {
416                 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
417                        ERR_R_MALLOC_FAILURE);
418                 goto err;
419         }
420
421         if (!SSL_use_certificate(ssl, cert)) {
422                 RSA_free(rsa);
423                 rsa = NULL;
424                 goto err;
425         }
426         pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
427         X509_free(cert);
428         cert = NULL;
429
430         rsa->n = BN_dup(pub_rsa->n);
431         rsa->e = BN_dup(pub_rsa->e);
432         if (!RSA_set_method(rsa, rsa_meth))
433                 goto err;
434
435         if (!SSL_use_RSAPrivateKey(ssl, rsa))
436                 goto err;
437         RSA_free(rsa);
438
439         return 0;
440
441 err:
442         if (cert)
443                 X509_free(cert);
444         if (rsa)
445                 RSA_free(rsa);
446         else {
447                 os_free(rsa_meth);
448                 cryptoapi_free_data(priv);
449         }
450         return -1;
451 }
452
453
454 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
455 {
456         HCERTSTORE cs;
457         PCCERT_CONTEXT ctx = NULL;
458         X509 *cert;
459         char buf[128];
460         const char *store;
461 #ifdef UNICODE
462         WCHAR *wstore;
463 #endif /* UNICODE */
464
465         if (mingw_load_crypto_func())
466                 return -1;
467
468         if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
469                 return -1;
470
471         store = name + 13;
472 #ifdef UNICODE
473         wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
474         if (wstore == NULL)
475                 return -1;
476         wsprintf(wstore, L"%S", store);
477         cs = CertOpenSystemStore(0, wstore);
478         os_free(wstore);
479 #else /* UNICODE */
480         cs = CertOpenSystemStore(0, store);
481 #endif /* UNICODE */
482         if (cs == NULL) {
483                 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
484                            "'%s': error=%d", __func__, store,
485                            (int) GetLastError());
486                 return -1;
487         }
488
489         while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
490                 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
491                                 ctx->cbCertEncoded);
492                 if (cert == NULL) {
493                         wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
494                                    "X509 DER encoding for CA cert");
495                         continue;
496                 }
497
498                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
499                                   sizeof(buf));
500                 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
501                            "system certificate store: subject='%s'", buf);
502
503                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
504                         tls_show_errors(MSG_WARNING, __func__,
505                                         "Failed to add ca_cert to OpenSSL "
506                                         "certificate store");
507                 }
508
509                 X509_free(cert);
510         }
511
512         if (!CertCloseStore(cs, 0)) {
513                 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
514                            "'%s': error=%d", __func__, name + 13,
515                            (int) GetLastError());
516         }
517
518         return 0;
519 }
520
521
522 #else /* CONFIG_NATIVE_WINDOWS */
523
524 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
525 {
526         return -1;
527 }
528
529 #endif /* CONFIG_NATIVE_WINDOWS */
530
531
532 static void ssl_info_cb(const SSL *ssl, int where, int ret)
533 {
534         const char *str;
535         int w;
536
537         wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
538         w = where & ~SSL_ST_MASK;
539         if (w & SSL_ST_CONNECT)
540                 str = "SSL_connect";
541         else if (w & SSL_ST_ACCEPT)
542                 str = "SSL_accept";
543         else
544                 str = "undefined";
545
546         if (where & SSL_CB_LOOP) {
547                 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
548                            str, SSL_state_string_long(ssl));
549         } else if (where & SSL_CB_ALERT) {
550                 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
551                            where & SSL_CB_READ ?
552                            "read (remote end reported an error)" :
553                            "write (local SSL3 detected an error)",
554                            SSL_alert_type_string_long(ret),
555                            SSL_alert_desc_string_long(ret));
556                 if ((ret >> 8) == SSL3_AL_FATAL) {
557                         struct tls_connection *conn =
558                                 SSL_get_app_data((SSL *) ssl);
559                         if (where & SSL_CB_READ)
560                                 conn->read_alerts++;
561                         else
562                                 conn->write_alerts++;
563                 }
564         } else if (where & SSL_CB_EXIT && ret <= 0) {
565                 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
566                            str, ret == 0 ? "failed" : "error",
567                            SSL_state_string_long(ssl));
568         }
569 }
570
571
572 #ifndef OPENSSL_NO_ENGINE
573 /**
574  * tls_engine_load_dynamic_generic - load any openssl engine
575  * @pre: an array of commands and values that load an engine initialized
576  *       in the engine specific function
577  * @post: an array of commands and values that initialize an already loaded
578  *        engine (or %NULL if not required)
579  * @id: the engine id of the engine to load (only required if post is not %NULL
580  *
581  * This function is a generic function that loads any openssl engine.
582  *
583  * Returns: 0 on success, -1 on failure
584  */
585 static int tls_engine_load_dynamic_generic(const char *pre[],
586                                            const char *post[], const char *id)
587 {
588         ENGINE *engine;
589         const char *dynamic_id = "dynamic";
590
591         engine = ENGINE_by_id(id);
592         if (engine) {
593                 ENGINE_free(engine);
594                 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
595                            "available", id);
596                 return 0;
597         }
598         ERR_clear_error();
599
600         engine = ENGINE_by_id(dynamic_id);
601         if (engine == NULL) {
602                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
603                            dynamic_id,
604                            ERR_error_string(ERR_get_error(), NULL));
605                 return -1;
606         }
607
608         /* Perform the pre commands. This will load the engine. */
609         while (pre && pre[0]) {
610                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
611                 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
612                         wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
613                                    "%s %s [%s]", pre[0], pre[1],
614                                    ERR_error_string(ERR_get_error(), NULL));
615                         ENGINE_free(engine);
616                         return -1;
617                 }
618                 pre += 2;
619         }
620
621         /*
622          * Free the reference to the "dynamic" engine. The loaded engine can
623          * now be looked up using ENGINE_by_id().
624          */
625         ENGINE_free(engine);
626
627         engine = ENGINE_by_id(id);
628         if (engine == NULL) {
629                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
630                            id, ERR_error_string(ERR_get_error(), NULL));
631                 return -1;
632         }
633
634         while (post && post[0]) {
635                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
636                 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
637                         wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
638                                 " %s %s [%s]", post[0], post[1],
639                                    ERR_error_string(ERR_get_error(), NULL));
640                         ENGINE_remove(engine);
641                         ENGINE_free(engine);
642                         return -1;
643                 }
644                 post += 2;
645         }
646         ENGINE_free(engine);
647
648         return 0;
649 }
650
651
652 /**
653  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
654  * @pkcs11_so_path: pksc11_so_path from the configuration
655  * @pcks11_module_path: pkcs11_module_path from the configuration
656  */
657 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
658                                           const char *pkcs11_module_path)
659 {
660         char *engine_id = "pkcs11";
661         const char *pre_cmd[] = {
662                 "SO_PATH", NULL /* pkcs11_so_path */,
663                 "ID", NULL /* engine_id */,
664                 "LIST_ADD", "1",
665                 /* "NO_VCHECK", "1", */
666                 "LOAD", NULL,
667                 NULL, NULL
668         };
669         const char *post_cmd[] = {
670                 "MODULE_PATH", NULL /* pkcs11_module_path */,
671                 NULL, NULL
672         };
673
674         if (!pkcs11_so_path || !pkcs11_module_path)
675                 return 0;
676
677         pre_cmd[1] = pkcs11_so_path;
678         pre_cmd[3] = engine_id;
679         post_cmd[1] = pkcs11_module_path;
680
681         wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
682                    pkcs11_so_path);
683
684         return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
685 }
686
687
688 /**
689  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
690  * @opensc_so_path: opensc_so_path from the configuration
691  */
692 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
693 {
694         char *engine_id = "opensc";
695         const char *pre_cmd[] = {
696                 "SO_PATH", NULL /* opensc_so_path */,
697                 "ID", NULL /* engine_id */,
698                 "LIST_ADD", "1",
699                 "LOAD", NULL,
700                 NULL, NULL
701         };
702
703         if (!opensc_so_path)
704                 return 0;
705
706         pre_cmd[1] = opensc_so_path;
707         pre_cmd[3] = engine_id;
708
709         wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
710                    opensc_so_path);
711
712         return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
713 }
714 #endif /* OPENSSL_NO_ENGINE */
715
716
717 void * tls_init(const struct tls_config *conf)
718 {
719         SSL_CTX *ssl;
720
721         if (tls_openssl_ref_count == 0) {
722                 SSL_load_error_strings();
723                 SSL_library_init();
724                 /* TODO: if /dev/urandom is available, PRNG is seeded
725                  * automatically. If this is not the case, random data should
726                  * be added here. */
727
728 #ifdef PKCS12_FUNCS
729                 PKCS12_PBE_add();
730 #endif  /* PKCS12_FUNCS */
731         }
732         tls_openssl_ref_count++;
733
734         ssl = SSL_CTX_new(TLSv1_method());
735         if (ssl == NULL)
736                 return NULL;
737
738         SSL_CTX_set_info_callback(ssl, ssl_info_cb);
739
740 #ifndef OPENSSL_NO_ENGINE
741         if (conf &&
742             (conf->opensc_engine_path || conf->pkcs11_engine_path ||
743              conf->pkcs11_module_path)) {
744                 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
745                 ERR_load_ENGINE_strings();
746                 ENGINE_load_dynamic();
747
748                 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
749                     tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
750                                                    conf->pkcs11_module_path)) {
751                         tls_deinit(ssl);
752                         return NULL;
753                 }
754         }
755 #endif /* OPENSSL_NO_ENGINE */
756
757         return ssl;
758 }
759
760
761 void tls_deinit(void *ssl_ctx)
762 {
763         SSL_CTX *ssl = ssl_ctx;
764         SSL_CTX_free(ssl);
765
766         tls_openssl_ref_count--;
767         if (tls_openssl_ref_count == 0) {
768 #ifndef OPENSSL_NO_ENGINE
769                 ENGINE_cleanup();
770 #endif /* OPENSSL_NO_ENGINE */
771                 CRYPTO_cleanup_all_ex_data();
772                 ERR_remove_state(0);
773                 ERR_free_strings();
774                 EVP_cleanup();
775         }
776 }
777
778
779 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
780                            const char *pin, const char *key_id,
781                            const char *cert_id, const char *ca_cert_id)
782 {
783 #ifndef OPENSSL_NO_ENGINE
784         int ret = -1;
785         if (engine_id == NULL) {
786                 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
787                 return -1;
788         }
789         if (pin == NULL) {
790                 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
791                 return -1;
792         }
793         if (key_id == NULL) {
794                 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
795                 return -1;
796         }
797
798         ERR_clear_error();
799         conn->engine = ENGINE_by_id(engine_id);
800         if (!conn->engine) {
801                 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
802                            engine_id, ERR_error_string(ERR_get_error(), NULL));
803                 goto err;
804         }
805         if (ENGINE_init(conn->engine) != 1) {
806                 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
807                            "(engine: %s) [%s]", engine_id,
808                            ERR_error_string(ERR_get_error(), NULL));
809                 goto err;
810         }
811         wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
812
813         if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
814                 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
815                            ERR_error_string(ERR_get_error(), NULL));
816                 goto err;
817         }
818         /* load private key first in-case PIN is required for cert */
819         conn->private_key = ENGINE_load_private_key(conn->engine,
820                                                     key_id, NULL, NULL);
821         if (!conn->private_key) {
822                 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
823                                 " '%s' [%s]", key_id,
824                            ERR_error_string(ERR_get_error(), NULL));
825                 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
826                 goto err;
827         }
828
829         /* handle a certificate and/or CA certificate */
830         if (cert_id || ca_cert_id) {
831                 const char *cmd_name = "LOAD_CERT_CTRL";
832
833                 /* test if the engine supports a LOAD_CERT_CTRL */
834                 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
835                                  0, (void *)cmd_name, NULL)) {
836                         wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
837                                    " loading certificates");
838                         ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
839                         goto err;
840                 }
841         }
842
843         return 0;
844
845 err:
846         if (conn->engine) {
847                 ENGINE_free(conn->engine);
848                 conn->engine = NULL;
849         }
850
851         if (conn->private_key) {
852                 EVP_PKEY_free(conn->private_key);
853                 conn->private_key = NULL;
854         }
855
856         return ret;
857 #else /* OPENSSL_NO_ENGINE */
858         return 0;
859 #endif /* OPENSSL_NO_ENGINE */
860 }
861
862
863 static void tls_engine_deinit(struct tls_connection *conn)
864 {
865 #ifndef OPENSSL_NO_ENGINE
866         wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
867         if (conn->private_key) {
868                 EVP_PKEY_free(conn->private_key);
869                 conn->private_key = NULL;
870         }
871         if (conn->engine) {
872                 ENGINE_finish(conn->engine);
873                 conn->engine = NULL;
874         }
875 #endif /* OPENSSL_NO_ENGINE */
876 }
877
878
879 int tls_get_errors(void *ssl_ctx)
880 {
881         int count = 0;
882         unsigned long err;
883
884         while ((err = ERR_get_error())) {
885                 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
886                            ERR_error_string(err, NULL));
887                 count++;
888         }
889
890         return count;
891 }
892
893 struct tls_connection * tls_connection_init(void *ssl_ctx)
894 {
895         SSL_CTX *ssl = ssl_ctx;
896         struct tls_connection *conn;
897         long options;
898
899         conn = os_zalloc(sizeof(*conn));
900         if (conn == NULL)
901                 return NULL;
902         conn->ssl = SSL_new(ssl);
903         if (conn->ssl == NULL) {
904                 tls_show_errors(MSG_INFO, __func__,
905                                 "Failed to initialize new SSL connection");
906                 os_free(conn);
907                 return NULL;
908         }
909
910         SSL_set_app_data(conn->ssl, conn);
911         options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
912                 SSL_OP_SINGLE_DH_USE;
913 #ifdef SSL_OP_NO_COMPRESSION
914         options |= SSL_OP_NO_COMPRESSION;
915 #endif /* SSL_OP_NO_COMPRESSION */
916         SSL_set_options(conn->ssl, options);
917
918         conn->ssl_in = BIO_new(BIO_s_mem());
919         if (!conn->ssl_in) {
920                 tls_show_errors(MSG_INFO, __func__,
921                                 "Failed to create a new BIO for ssl_in");
922                 SSL_free(conn->ssl);
923                 os_free(conn);
924                 return NULL;
925         }
926
927         conn->ssl_out = BIO_new(BIO_s_mem());
928         if (!conn->ssl_out) {
929                 tls_show_errors(MSG_INFO, __func__,
930                                 "Failed to create a new BIO for ssl_out");
931                 SSL_free(conn->ssl);
932                 BIO_free(conn->ssl_in);
933                 os_free(conn);
934                 return NULL;
935         }
936
937         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
938
939         return conn;
940 }
941
942
943 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
944 {
945         if (conn == NULL)
946                 return;
947         SSL_free(conn->ssl);
948         tls_engine_deinit(conn);
949         os_free(conn->subject_match);
950         os_free(conn->altsubject_match);
951         os_free(conn->session_ticket);
952         os_free(conn);
953 }
954
955
956 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
957 {
958         return conn ? SSL_is_init_finished(conn->ssl) : 0;
959 }
960
961
962 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
963 {
964         if (conn == NULL)
965                 return -1;
966
967         /* Shutdown previous TLS connection without notifying the peer
968          * because the connection was already terminated in practice
969          * and "close notify" shutdown alert would confuse AS. */
970         SSL_set_quiet_shutdown(conn->ssl, 1);
971         SSL_shutdown(conn->ssl);
972         return 0;
973 }
974
975
976 static int tls_match_altsubject_component(X509 *cert, int type,
977                                           const char *value, size_t len)
978 {
979         GENERAL_NAME *gen;
980         void *ext;
981         int i, found = 0;
982
983         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
984
985         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
986                 gen = sk_GENERAL_NAME_value(ext, i);
987                 if (gen->type != type)
988                         continue;
989                 if (os_strlen((char *) gen->d.ia5->data) == len &&
990                     os_memcmp(value, gen->d.ia5->data, len) == 0)
991                         found++;
992         }
993
994         return found;
995 }
996
997
998 static int tls_match_altsubject(X509 *cert, const char *match)
999 {
1000         int type;
1001         const char *pos, *end;
1002         size_t len;
1003
1004         pos = match;
1005         do {
1006                 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
1007                         type = GEN_EMAIL;
1008                         pos += 6;
1009                 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
1010                         type = GEN_DNS;
1011                         pos += 4;
1012                 } else if (os_strncmp(pos, "URI:", 4) == 0) {
1013                         type = GEN_URI;
1014                         pos += 4;
1015                 } else {
1016                         wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
1017                                    "match '%s'", pos);
1018                         return 0;
1019                 }
1020                 end = os_strchr(pos, ';');
1021                 while (end) {
1022                         if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1023                             os_strncmp(end + 1, "DNS:", 4) == 0 ||
1024                             os_strncmp(end + 1, "URI:", 4) == 0)
1025                                 break;
1026                         end = os_strchr(end + 1, ';');
1027                 }
1028                 if (end)
1029                         len = end - pos;
1030                 else
1031                         len = os_strlen(pos);
1032                 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1033                         return 1;
1034                 pos = end + 1;
1035         } while (end);
1036
1037         return 0;
1038 }
1039
1040
1041 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1042 {
1043         char buf[256];
1044         X509 *err_cert;
1045         int err, depth;
1046         SSL *ssl;
1047         struct tls_connection *conn;
1048         char *match, *altmatch;
1049
1050         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1051         err = X509_STORE_CTX_get_error(x509_ctx);
1052         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1053         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1054                                          SSL_get_ex_data_X509_STORE_CTX_idx());
1055         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1056
1057         conn = SSL_get_app_data(ssl);
1058         match = conn ? conn->subject_match : NULL;
1059         altmatch = conn ? conn->altsubject_match : NULL;
1060
1061         if (!preverify_ok) {
1062                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1063                            " error %d (%s) depth %d for '%s'", err,
1064                            X509_verify_cert_error_string(err), depth, buf);
1065         } else {
1066                 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - "
1067                            "preverify_ok=%d err=%d (%s) depth=%d buf='%s'",
1068                            preverify_ok, err,
1069                            X509_verify_cert_error_string(err), depth, buf);
1070                 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1071                         wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1072                                    "match with '%s'", buf, match);
1073                         preverify_ok = 0;
1074                 } else if (depth == 0 && altmatch &&
1075                            !tls_match_altsubject(err_cert, altmatch)) {
1076                         wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1077                                    "'%s' not found", altmatch);
1078                         preverify_ok = 0;
1079                 }
1080         }
1081
1082         return preverify_ok;
1083 }
1084
1085
1086 #ifndef OPENSSL_NO_STDIO
1087 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1088 {
1089         SSL_CTX *ssl_ctx = _ssl_ctx;
1090         X509_LOOKUP *lookup;
1091         int ret = 0;
1092
1093         lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1094                                        X509_LOOKUP_file());
1095         if (lookup == NULL) {
1096                 tls_show_errors(MSG_WARNING, __func__,
1097                                 "Failed add lookup for X509 store");
1098                 return -1;
1099         }
1100
1101         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1102                 unsigned long err = ERR_peek_error();
1103                 tls_show_errors(MSG_WARNING, __func__,
1104                                 "Failed load CA in DER format");
1105                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1106                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1107                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1108                                    "cert already in hash table error",
1109                                    __func__);
1110                 } else
1111                         ret = -1;
1112         }
1113
1114         return ret;
1115 }
1116 #endif /* OPENSSL_NO_STDIO */
1117
1118
1119 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1120                                   const char *ca_cert, const u8 *ca_cert_blob,
1121                                   size_t ca_cert_blob_len, const char *ca_path)
1122 {
1123         SSL_CTX *ssl_ctx = _ssl_ctx;
1124
1125         /*
1126          * Remove previously configured trusted CA certificates before adding
1127          * new ones.
1128          */
1129         X509_STORE_free(ssl_ctx->cert_store);
1130         ssl_ctx->cert_store = X509_STORE_new();
1131         if (ssl_ctx->cert_store == NULL) {
1132                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1133                            "certificate store", __func__);
1134                 return -1;
1135         }
1136
1137         if (ca_cert_blob) {
1138                 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1139                                       ca_cert_blob_len);
1140                 if (cert == NULL) {
1141                         tls_show_errors(MSG_WARNING, __func__,
1142                                         "Failed to parse ca_cert_blob");
1143                         return -1;
1144                 }
1145
1146                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1147                         unsigned long err = ERR_peek_error();
1148                         tls_show_errors(MSG_WARNING, __func__,
1149                                         "Failed to add ca_cert_blob to "
1150                                         "certificate store");
1151                         if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1152                             ERR_GET_REASON(err) ==
1153                             X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1154                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1155                                            "cert already in hash table error",
1156                                            __func__);
1157                         } else {
1158                                 X509_free(cert);
1159                                 return -1;
1160                         }
1161                 }
1162                 X509_free(cert);
1163                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1164                            "to certificate store", __func__);
1165                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1166                 return 0;
1167         }
1168
1169 #ifdef CONFIG_NATIVE_WINDOWS
1170         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1171             0) {
1172                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1173                            "system certificate store");
1174                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1175                 return 0;
1176         }
1177 #endif /* CONFIG_NATIVE_WINDOWS */
1178
1179         if (ca_cert || ca_path) {
1180 #ifndef OPENSSL_NO_STDIO
1181                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1182                     1) {
1183                         tls_show_errors(MSG_WARNING, __func__,
1184                                         "Failed to load root certificates");
1185                         if (ca_cert &&
1186                             tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1187                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1188                                            "DER format CA certificate",
1189                                            __func__);
1190                         } else
1191                                 return -1;
1192                 } else {
1193                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1194                                    "certificate(s) loaded");
1195                         tls_get_errors(ssl_ctx);
1196                 }
1197                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1198 #else /* OPENSSL_NO_STDIO */
1199                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1200                            __func__);
1201                 return -1;
1202 #endif /* OPENSSL_NO_STDIO */
1203         } else {
1204                 /* No ca_cert configured - do not try to verify server
1205                  * certificate */
1206                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1207         }
1208
1209         return 0;
1210 }
1211
1212
1213 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1214 {
1215         if (ca_cert) {
1216                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1217                 {
1218                         tls_show_errors(MSG_WARNING, __func__,
1219                                         "Failed to load root certificates");
1220                         return -1;
1221                 }
1222
1223                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1224                            "certificate(s) loaded");
1225
1226 #ifndef OPENSSL_NO_STDIO
1227                 /* Add the same CAs to the client certificate requests */
1228                 SSL_CTX_set_client_CA_list(ssl_ctx,
1229                                            SSL_load_client_CA_file(ca_cert));
1230 #endif /* OPENSSL_NO_STDIO */
1231         }
1232
1233         return 0;
1234 }
1235
1236
1237 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1238 {
1239         int flags;
1240
1241         if (check_crl) {
1242                 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1243                 if (cs == NULL) {
1244                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
1245                                         "certificate store when enabling "
1246                                         "check_crl");
1247                         return -1;
1248                 }
1249                 flags = X509_V_FLAG_CRL_CHECK;
1250                 if (check_crl == 2)
1251                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
1252                 X509_STORE_set_flags(cs, flags);
1253         }
1254         return 0;
1255 }
1256
1257
1258 static int tls_connection_set_subject_match(struct tls_connection *conn,
1259                                             const char *subject_match,
1260                                             const char *altsubject_match)
1261 {
1262         os_free(conn->subject_match);
1263         conn->subject_match = NULL;
1264         if (subject_match) {
1265                 conn->subject_match = os_strdup(subject_match);
1266                 if (conn->subject_match == NULL)
1267                         return -1;
1268         }
1269
1270         os_free(conn->altsubject_match);
1271         conn->altsubject_match = NULL;
1272         if (altsubject_match) {
1273                 conn->altsubject_match = os_strdup(altsubject_match);
1274                 if (conn->altsubject_match == NULL)
1275                         return -1;
1276         }
1277
1278         return 0;
1279 }
1280
1281
1282 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1283                               int verify_peer)
1284 {
1285         static int counter = 0;
1286
1287         if (conn == NULL)
1288                 return -1;
1289
1290         if (verify_peer) {
1291                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1292                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1293                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1294         } else {
1295                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1296         }
1297
1298         SSL_set_accept_state(conn->ssl);
1299
1300         /*
1301          * Set session id context in order to avoid fatal errors when client
1302          * tries to resume a session. However, set the context to a unique
1303          * value in order to effectively disable session resumption for now
1304          * since not all areas of the server code are ready for it (e.g.,
1305          * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
1306          * handshake).
1307          */
1308         counter++;
1309         SSL_set_session_id_context(conn->ssl,
1310                                    (const unsigned char *) &counter,
1311                                    sizeof(counter));
1312
1313         return 0;
1314 }
1315
1316
1317 static int tls_connection_client_cert(struct tls_connection *conn,
1318                                       const char *client_cert,
1319                                       const u8 *client_cert_blob,
1320                                       size_t client_cert_blob_len)
1321 {
1322         if (client_cert == NULL && client_cert_blob == NULL)
1323                 return 0;
1324
1325         if (client_cert_blob &&
1326             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1327                                      client_cert_blob_len) == 1) {
1328                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1329                            "OK");
1330                 return 0;
1331         } else if (client_cert_blob) {
1332                 tls_show_errors(MSG_DEBUG, __func__,
1333                                 "SSL_use_certificate_ASN1 failed");
1334         }
1335
1336         if (client_cert == NULL)
1337                 return -1;
1338
1339 #ifndef OPENSSL_NO_STDIO
1340         if (SSL_use_certificate_file(conn->ssl, client_cert,
1341                                      SSL_FILETYPE_ASN1) == 1) {
1342                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1343                            " --> OK");
1344                 return 0;
1345         } else {
1346                 tls_show_errors(MSG_DEBUG, __func__,
1347                                 "SSL_use_certificate_file (DER) failed");
1348         }
1349
1350         if (SSL_use_certificate_file(conn->ssl, client_cert,
1351                                      SSL_FILETYPE_PEM) == 1) {
1352                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1353                            " --> OK");
1354                 return 0;
1355         } else {
1356                 tls_show_errors(MSG_DEBUG, __func__,
1357                                 "SSL_use_certificate_file (PEM) failed");
1358         }
1359 #else /* OPENSSL_NO_STDIO */
1360         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1361 #endif /* OPENSSL_NO_STDIO */
1362
1363         return -1;
1364 }
1365
1366
1367 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1368 {
1369 #ifndef OPENSSL_NO_STDIO
1370         if (client_cert == NULL)
1371                 return 0;
1372
1373         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1374                                          SSL_FILETYPE_ASN1) != 1 &&
1375             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1376                                          SSL_FILETYPE_PEM) != 1) {
1377                 tls_show_errors(MSG_INFO, __func__,
1378                                 "Failed to load client certificate");
1379                 return -1;
1380         }
1381         return 0;
1382 #else /* OPENSSL_NO_STDIO */
1383         if (client_cert == NULL)
1384                 return 0;
1385         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1386         return -1;
1387 #endif /* OPENSSL_NO_STDIO */
1388 }
1389
1390
1391 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1392 {
1393         if (password == NULL) {
1394                 return 0;
1395         }
1396         os_strlcpy(buf, (char *) password, size);
1397         return os_strlen(buf);
1398 }
1399
1400
1401 #ifdef PKCS12_FUNCS
1402 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1403                             const char *passwd)
1404 {
1405         EVP_PKEY *pkey;
1406         X509 *cert;
1407         STACK_OF(X509) *certs;
1408         int res = 0;
1409         char buf[256];
1410
1411         pkey = NULL;
1412         cert = NULL;
1413         certs = NULL;
1414         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1415                 tls_show_errors(MSG_DEBUG, __func__,
1416                                 "Failed to parse PKCS12 file");
1417                 PKCS12_free(p12);
1418                 return -1;
1419         }
1420         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1421
1422         if (cert) {
1423                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1424                                   sizeof(buf));
1425                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1426                            "subject='%s'", buf);
1427                 if (ssl) {
1428                         if (SSL_use_certificate(ssl, cert) != 1)
1429                                 res = -1;
1430                 } else {
1431                         if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1432                                 res = -1;
1433                 }
1434                 X509_free(cert);
1435         }
1436
1437         if (pkey) {
1438                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1439                 if (ssl) {
1440                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
1441                                 res = -1;
1442                 } else {
1443                         if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1444                                 res = -1;
1445                 }
1446                 EVP_PKEY_free(pkey);
1447         }
1448
1449         if (certs) {
1450                 while ((cert = sk_X509_pop(certs)) != NULL) {
1451                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
1452                                           sizeof(buf));
1453                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1454                                    " from PKCS12: subject='%s'", buf);
1455                         /*
1456                          * There is no SSL equivalent for the chain cert - so
1457                          * always add it to the context...
1458                          */
1459                         if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1460                                 res = -1;
1461                                 break;
1462                         }
1463                 }
1464                 sk_X509_free(certs);
1465         }
1466
1467         PKCS12_free(p12);
1468
1469         if (res < 0)
1470                 tls_get_errors(ssl_ctx);
1471
1472         return res;
1473 }
1474 #endif  /* PKCS12_FUNCS */
1475
1476
1477 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1478                            const char *passwd)
1479 {
1480 #ifdef PKCS12_FUNCS
1481         FILE *f;
1482         PKCS12 *p12;
1483
1484         f = fopen(private_key, "rb");
1485         if (f == NULL)
1486                 return -1;
1487
1488         p12 = d2i_PKCS12_fp(f, NULL);
1489         fclose(f);
1490
1491         if (p12 == NULL) {
1492                 tls_show_errors(MSG_INFO, __func__,
1493                                 "Failed to use PKCS#12 file");
1494                 return -1;
1495         }
1496
1497         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1498
1499 #else /* PKCS12_FUNCS */
1500         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1501                    "p12/pfx files");
1502         return -1;
1503 #endif  /* PKCS12_FUNCS */
1504 }
1505
1506
1507 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1508                                 const u8 *blob, size_t len, const char *passwd)
1509 {
1510 #ifdef PKCS12_FUNCS
1511         PKCS12 *p12;
1512
1513         p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1514         if (p12 == NULL) {
1515                 tls_show_errors(MSG_INFO, __func__,
1516                                 "Failed to use PKCS#12 blob");
1517                 return -1;
1518         }
1519
1520         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1521
1522 #else /* PKCS12_FUNCS */
1523         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1524                    "p12/pfx blobs");
1525         return -1;
1526 #endif  /* PKCS12_FUNCS */
1527 }
1528
1529
1530 #ifndef OPENSSL_NO_ENGINE
1531 static int tls_engine_get_cert(struct tls_connection *conn,
1532                                const char *cert_id,
1533                                X509 **cert)
1534 {
1535         /* this runs after the private key is loaded so no PIN is required */
1536         struct {
1537                 const char *cert_id;
1538                 X509 *cert;
1539         } params;
1540         params.cert_id = cert_id;
1541         params.cert = NULL;
1542
1543         if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
1544                              0, &params, NULL, 1)) {
1545                 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
1546                            " '%s' [%s]", cert_id,
1547                            ERR_error_string(ERR_get_error(), NULL));
1548                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1549         }
1550         if (!params.cert) {
1551                 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
1552                            " '%s'", cert_id);
1553                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
1554         }
1555         *cert = params.cert;
1556         return 0;
1557 }
1558 #endif /* OPENSSL_NO_ENGINE */
1559
1560
1561 static int tls_connection_engine_client_cert(struct tls_connection *conn,
1562                                              const char *cert_id)
1563 {
1564 #ifndef OPENSSL_NO_ENGINE
1565         X509 *cert;
1566
1567         if (tls_engine_get_cert(conn, cert_id, &cert))
1568                 return -1;
1569
1570         if (!SSL_use_certificate(conn->ssl, cert)) {
1571                 tls_show_errors(MSG_ERROR, __func__,
1572                                 "SSL_use_certificate failed");
1573                 X509_free(cert);
1574                 return -1;
1575         }
1576         X509_free(cert);
1577         wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
1578                    "OK");
1579         return 0;
1580
1581 #else /* OPENSSL_NO_ENGINE */
1582         return -1;
1583 #endif /* OPENSSL_NO_ENGINE */
1584 }
1585
1586
1587 static int tls_connection_engine_ca_cert(void *_ssl_ctx,
1588                                          struct tls_connection *conn,
1589                                          const char *ca_cert_id)
1590 {
1591 #ifndef OPENSSL_NO_ENGINE
1592         X509 *cert;
1593         SSL_CTX *ssl_ctx = _ssl_ctx;
1594
1595         if (tls_engine_get_cert(conn, ca_cert_id, &cert))
1596                 return -1;
1597
1598         /* start off the same as tls_connection_ca_cert */
1599         X509_STORE_free(ssl_ctx->cert_store);
1600         ssl_ctx->cert_store = X509_STORE_new();
1601         if (ssl_ctx->cert_store == NULL) {
1602                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1603                            "certificate store", __func__);
1604                 X509_free(cert);
1605                 return -1;
1606         }
1607         if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1608                 unsigned long err = ERR_peek_error();
1609                 tls_show_errors(MSG_WARNING, __func__,
1610                                 "Failed to add CA certificate from engine "
1611                                 "to certificate store");
1612                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1613                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1614                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
1615                                    " already in hash table error",
1616                                    __func__);
1617                 } else {
1618                         X509_free(cert);
1619                         return -1;
1620                 }
1621         }
1622         X509_free(cert);
1623         wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
1624                    "to certificate store", __func__);
1625         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1626         return 0;
1627
1628 #else /* OPENSSL_NO_ENGINE */
1629         return -1;
1630 #endif /* OPENSSL_NO_ENGINE */
1631 }
1632
1633
1634 static int tls_connection_engine_private_key(struct tls_connection *conn)
1635 {
1636 #ifndef OPENSSL_NO_ENGINE
1637         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1638                 tls_show_errors(MSG_ERROR, __func__,
1639                                 "ENGINE: cannot use private key for TLS");
1640                 return -1;
1641         }
1642         if (!SSL_check_private_key(conn->ssl)) {
1643                 tls_show_errors(MSG_INFO, __func__,
1644                                 "Private key failed verification");
1645                 return -1;
1646         }
1647         return 0;
1648 #else /* OPENSSL_NO_ENGINE */
1649         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1650                    "engine support was not compiled in");
1651         return -1;
1652 #endif /* OPENSSL_NO_ENGINE */
1653 }
1654
1655
1656 static int tls_connection_private_key(void *_ssl_ctx,
1657                                       struct tls_connection *conn,
1658                                       const char *private_key,
1659                                       const char *private_key_passwd,
1660                                       const u8 *private_key_blob,
1661                                       size_t private_key_blob_len)
1662 {
1663         SSL_CTX *ssl_ctx = _ssl_ctx;
1664         char *passwd;
1665         int ok;
1666
1667         if (private_key == NULL && private_key_blob == NULL)
1668                 return 0;
1669
1670         if (private_key_passwd) {
1671                 passwd = os_strdup(private_key_passwd);
1672                 if (passwd == NULL)
1673                         return -1;
1674         } else
1675                 passwd = NULL;
1676
1677         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1678         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1679
1680         ok = 0;
1681         while (private_key_blob) {
1682                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1683                                             (u8 *) private_key_blob,
1684                                             private_key_blob_len) == 1) {
1685                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1686                                    "ASN1(EVP_PKEY_RSA) --> OK");
1687                         ok = 1;
1688                         break;
1689                 } else {
1690                         tls_show_errors(MSG_DEBUG, __func__,
1691                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
1692                                         " failed");
1693                 }
1694
1695                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1696                                             (u8 *) private_key_blob,
1697                                             private_key_blob_len) == 1) {
1698                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1699                                    "ASN1(EVP_PKEY_DSA) --> OK");
1700                         ok = 1;
1701                         break;
1702                 } else {
1703                         tls_show_errors(MSG_DEBUG, __func__,
1704                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
1705                                         " failed");
1706                 }
1707
1708                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1709                                                (u8 *) private_key_blob,
1710                                                private_key_blob_len) == 1) {
1711                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1712                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
1713                         ok = 1;
1714                         break;
1715                 } else {
1716                         tls_show_errors(MSG_DEBUG, __func__,
1717                                         "SSL_use_RSAPrivateKey_ASN1 failed");
1718                 }
1719
1720                 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1721                                          private_key_blob_len, passwd) == 0) {
1722                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1723                                    "OK");
1724                         ok = 1;
1725                         break;
1726                 }
1727
1728                 break;
1729         }
1730
1731         while (!ok && private_key) {
1732 #ifndef OPENSSL_NO_STDIO
1733                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1734                                             SSL_FILETYPE_ASN1) == 1) {
1735                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1736                                    "SSL_use_PrivateKey_File (DER) --> OK");
1737                         ok = 1;
1738                         break;
1739                 } else {
1740                         tls_show_errors(MSG_DEBUG, __func__,
1741                                         "SSL_use_PrivateKey_File (DER) "
1742                                         "failed");
1743                 }
1744
1745                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1746                                             SSL_FILETYPE_PEM) == 1) {
1747                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1748                                    "SSL_use_PrivateKey_File (PEM) --> OK");
1749                         ok = 1;
1750                         break;
1751                 } else {
1752                         tls_show_errors(MSG_DEBUG, __func__,
1753                                         "SSL_use_PrivateKey_File (PEM) "
1754                                         "failed");
1755                 }
1756 #else /* OPENSSL_NO_STDIO */
1757                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1758                            __func__);
1759 #endif /* OPENSSL_NO_STDIO */
1760
1761                 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
1762                     == 0) {
1763                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
1764                                    "--> OK");
1765                         ok = 1;
1766                         break;
1767                 }
1768
1769                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
1770                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
1771                                    "access certificate store --> OK");
1772                         ok = 1;
1773                         break;
1774                 }
1775
1776                 break;
1777         }
1778
1779         if (!ok) {
1780                 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
1781                 os_free(passwd);
1782                 ERR_clear_error();
1783                 return -1;
1784         }
1785         ERR_clear_error();
1786         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1787         os_free(passwd);
1788         
1789         if (!SSL_check_private_key(conn->ssl)) {
1790                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
1791                                 "verification");
1792                 return -1;
1793         }
1794
1795         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
1796         return 0;
1797 }
1798
1799
1800 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
1801                                   const char *private_key_passwd)
1802 {
1803         char *passwd;
1804
1805         if (private_key == NULL)
1806                 return 0;
1807
1808         if (private_key_passwd) {
1809                 passwd = os_strdup(private_key_passwd);
1810                 if (passwd == NULL)
1811                         return -1;
1812         } else
1813                 passwd = NULL;
1814
1815         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1816         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1817         if (
1818 #ifndef OPENSSL_NO_STDIO
1819             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1820                                         SSL_FILETYPE_ASN1) != 1 &&
1821             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1822                                         SSL_FILETYPE_PEM) != 1 &&
1823 #endif /* OPENSSL_NO_STDIO */
1824             tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
1825                 tls_show_errors(MSG_INFO, __func__,
1826                                 "Failed to load private key");
1827                 os_free(passwd);
1828                 ERR_clear_error();
1829                 return -1;
1830         }
1831         os_free(passwd);
1832         ERR_clear_error();
1833         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1834         
1835         if (!SSL_CTX_check_private_key(ssl_ctx)) {
1836                 tls_show_errors(MSG_INFO, __func__,
1837                                 "Private key failed verification");
1838                 return -1;
1839         }
1840
1841         return 0;
1842 }
1843
1844
1845 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
1846 {
1847 #ifdef OPENSSL_NO_DH
1848         if (dh_file == NULL)
1849                 return 0;
1850         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1851                    "dh_file specified");
1852         return -1;
1853 #else /* OPENSSL_NO_DH */
1854         DH *dh;
1855         BIO *bio;
1856
1857         /* TODO: add support for dh_blob */
1858         if (dh_file == NULL)
1859                 return 0;
1860         if (conn == NULL)
1861                 return -1;
1862
1863         bio = BIO_new_file(dh_file, "r");
1864         if (bio == NULL) {
1865                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1866                            dh_file, ERR_error_string(ERR_get_error(), NULL));
1867                 return -1;
1868         }
1869         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1870         BIO_free(bio);
1871 #ifndef OPENSSL_NO_DSA
1872         while (dh == NULL) {
1873                 DSA *dsa;
1874                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1875                            " trying to parse as DSA params", dh_file,
1876                            ERR_error_string(ERR_get_error(), NULL));
1877                 bio = BIO_new_file(dh_file, "r");
1878                 if (bio == NULL)
1879                         break;
1880                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1881                 BIO_free(bio);
1882                 if (!dsa) {
1883                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1884                                    "'%s': %s", dh_file,
1885                                    ERR_error_string(ERR_get_error(), NULL));
1886                         break;
1887                 }
1888
1889                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1890                 dh = DSA_dup_DH(dsa);
1891                 DSA_free(dsa);
1892                 if (dh == NULL) {
1893                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1894                                    "params into DH params");
1895                         break;
1896                 }
1897                 break;
1898         }
1899 #endif /* !OPENSSL_NO_DSA */
1900         if (dh == NULL) {
1901                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1902                            "'%s'", dh_file);
1903                 return -1;
1904         }
1905
1906         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
1907                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1908                            "%s", dh_file,
1909                            ERR_error_string(ERR_get_error(), NULL));
1910                 DH_free(dh);
1911                 return -1;
1912         }
1913         DH_free(dh);
1914         return 0;
1915 #endif /* OPENSSL_NO_DH */
1916 }
1917
1918
1919 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
1920 {
1921 #ifdef OPENSSL_NO_DH
1922         if (dh_file == NULL)
1923                 return 0;
1924         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1925                    "dh_file specified");
1926         return -1;
1927 #else /* OPENSSL_NO_DH */
1928         DH *dh;
1929         BIO *bio;
1930
1931         /* TODO: add support for dh_blob */
1932         if (dh_file == NULL)
1933                 return 0;
1934         if (ssl_ctx == NULL)
1935                 return -1;
1936
1937         bio = BIO_new_file(dh_file, "r");
1938         if (bio == NULL) {
1939                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1940                            dh_file, ERR_error_string(ERR_get_error(), NULL));
1941                 return -1;
1942         }
1943         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1944         BIO_free(bio);
1945 #ifndef OPENSSL_NO_DSA
1946         while (dh == NULL) {
1947                 DSA *dsa;
1948                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1949                            " trying to parse as DSA params", dh_file,
1950                            ERR_error_string(ERR_get_error(), NULL));
1951                 bio = BIO_new_file(dh_file, "r");
1952                 if (bio == NULL)
1953                         break;
1954                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1955                 BIO_free(bio);
1956                 if (!dsa) {
1957                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1958                                    "'%s': %s", dh_file,
1959                                    ERR_error_string(ERR_get_error(), NULL));
1960                         break;
1961                 }
1962
1963                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1964                 dh = DSA_dup_DH(dsa);
1965                 DSA_free(dsa);
1966                 if (dh == NULL) {
1967                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1968                                    "params into DH params");
1969                         break;
1970                 }
1971                 break;
1972         }
1973 #endif /* !OPENSSL_NO_DSA */
1974         if (dh == NULL) {
1975                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1976                            "'%s'", dh_file);
1977                 return -1;
1978         }
1979
1980         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
1981                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1982                            "%s", dh_file,
1983                            ERR_error_string(ERR_get_error(), NULL));
1984                 DH_free(dh);
1985                 return -1;
1986         }
1987         DH_free(dh);
1988         return 0;
1989 #endif /* OPENSSL_NO_DH */
1990 }
1991
1992
1993 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
1994                             struct tls_keys *keys)
1995 {
1996         SSL *ssl;
1997
1998         if (conn == NULL || keys == NULL)
1999                 return -1;
2000         ssl = conn->ssl;
2001         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
2002                 return -1;
2003
2004         os_memset(keys, 0, sizeof(*keys));
2005         keys->master_key = ssl->session->master_key;
2006         keys->master_key_len = ssl->session->master_key_length;
2007         keys->client_random = ssl->s3->client_random;
2008         keys->client_random_len = SSL3_RANDOM_SIZE;
2009         keys->server_random = ssl->s3->server_random;
2010         keys->server_random_len = SSL3_RANDOM_SIZE;
2011
2012         return 0;
2013 }
2014
2015
2016 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
2017                        const char *label, int server_random_first,
2018                        u8 *out, size_t out_len)
2019 {
2020         return -1;
2021 }
2022
2023
2024 u8 * tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
2025                               const u8 *in_data, size_t in_len,
2026                               size_t *out_len, u8 **appl_data,
2027                               size_t *appl_data_len)
2028 {
2029         int res;
2030         u8 *out_data;
2031
2032         if (appl_data)
2033                 *appl_data = NULL;
2034
2035         /*
2036          * Give TLS handshake data from the server (if available) to OpenSSL
2037          * for processing.
2038          */
2039         if (in_data &&
2040             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
2041                 tls_show_errors(MSG_INFO, __func__,
2042                                 "Handshake failed - BIO_write");
2043                 return NULL;
2044         }
2045
2046         /* Initiate TLS handshake or continue the existing handshake */
2047         res = SSL_connect(conn->ssl);
2048         if (res != 1) {
2049                 int err = SSL_get_error(conn->ssl, res);
2050                 if (err == SSL_ERROR_WANT_READ)
2051                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
2052                                    "more data");
2053                 else if (err == SSL_ERROR_WANT_WRITE)
2054                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
2055                                    "write");
2056                 else {
2057                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
2058                         conn->failed++;
2059                 }
2060         }
2061
2062         /* Get the TLS handshake data to be sent to the server */
2063         res = BIO_ctrl_pending(conn->ssl_out);
2064         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2065         out_data = os_malloc(res == 0 ? 1 : res);
2066         if (out_data == NULL) {
2067                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2068                            "handshake output (%d bytes)", res);
2069                 if (BIO_reset(conn->ssl_out) < 0) {
2070                         tls_show_errors(MSG_INFO, __func__,
2071                                         "BIO_reset failed");
2072                 }
2073                 *out_len = 0;
2074                 return NULL;
2075         }
2076         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
2077         if (res < 0) {
2078                 tls_show_errors(MSG_INFO, __func__,
2079                                 "Handshake failed - BIO_read");
2080                 if (BIO_reset(conn->ssl_out) < 0) {
2081                         tls_show_errors(MSG_INFO, __func__,
2082                                         "BIO_reset failed");
2083                 }
2084                 *out_len = 0;
2085                 return NULL;
2086         }
2087         *out_len = res;
2088
2089         if (SSL_is_init_finished(conn->ssl) && appl_data) {
2090                 *appl_data = os_malloc(in_len);
2091                 if (*appl_data) {
2092                         res = SSL_read(conn->ssl, *appl_data, in_len);
2093                         if (res < 0) {
2094                                 tls_show_errors(MSG_INFO, __func__,
2095                                                 "Failed to read possible "
2096                                                 "Application Data");
2097                                 os_free(*appl_data);
2098                                 *appl_data = NULL;
2099                         } else {
2100                                 *appl_data_len = res;
2101                                 wpa_hexdump_key(MSG_MSGDUMP, "SSL: Application"
2102                                                 " Data in Finish message",
2103                                                 *appl_data, *appl_data_len);
2104                         }
2105                 }
2106         }
2107
2108         return out_data;
2109 }
2110
2111
2112 u8 * tls_connection_server_handshake(void *ssl_ctx,
2113                                      struct tls_connection *conn,
2114                                      const u8 *in_data, size_t in_len,
2115                                      size_t *out_len)
2116 {
2117         int res;
2118         u8 *out_data;
2119
2120         /*
2121          * Give TLS handshake data from the client (if available) to OpenSSL
2122          * for processing.
2123          */
2124         if (in_data &&
2125             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
2126                 tls_show_errors(MSG_INFO, __func__,
2127                                 "Handshake failed - BIO_write");
2128                 return NULL;
2129         }
2130
2131         /* Initiate TLS handshake or continue the existing handshake */
2132         res = SSL_accept(conn->ssl);
2133         if (res != 1) {
2134                 int err = SSL_get_error(conn->ssl, res);
2135                 if (err == SSL_ERROR_WANT_READ)
2136                         wpa_printf(MSG_DEBUG, "SSL: SSL_accept - want "
2137                                    "more data");
2138                 else if (err == SSL_ERROR_WANT_WRITE)
2139                         wpa_printf(MSG_DEBUG, "SSL: SSL_accept - want to "
2140                                    "write");
2141                 else {
2142                         tls_show_errors(MSG_INFO, __func__, "SSL_accept");
2143                         return NULL;
2144                 }
2145         }
2146
2147         /* Get the TLS handshake data to be sent to the client */
2148         res = BIO_ctrl_pending(conn->ssl_out);
2149         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
2150         out_data = os_malloc(res == 0 ? 1 : res);
2151         if (out_data == NULL) {
2152                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
2153                            "handshake output (%d bytes)", res);
2154                 if (BIO_reset(conn->ssl_out) < 0) {
2155                         tls_show_errors(MSG_INFO, __func__,
2156                                         "BIO_reset failed");
2157                 }
2158                 *out_len = 0;
2159                 return NULL;
2160         }
2161         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
2162         if (res < 0) {
2163                 tls_show_errors(MSG_INFO, __func__,
2164                                 "Handshake failed - BIO_read");
2165                 if (BIO_reset(conn->ssl_out) < 0) {
2166                         tls_show_errors(MSG_INFO, __func__,
2167                                         "BIO_reset failed");
2168                 }
2169                 *out_len = 0;
2170                 return NULL;
2171         }
2172         *out_len = res;
2173         return out_data;
2174 }
2175
2176
2177 int tls_connection_encrypt(void *ssl_ctx, struct tls_connection *conn,
2178                            const u8 *in_data, size_t in_len,
2179                            u8 *out_data, size_t out_len)
2180 {
2181         int res;
2182
2183         if (conn == NULL)
2184                 return -1;
2185
2186         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2187         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2188             (res = BIO_reset(conn->ssl_out)) < 0) {
2189                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2190                 return res;
2191         }
2192         res = SSL_write(conn->ssl, in_data, in_len);
2193         if (res < 0) {
2194                 tls_show_errors(MSG_INFO, __func__,
2195                                 "Encryption failed - SSL_write");
2196                 return res;
2197         }
2198
2199         /* Read encrypted data to be sent to the server */
2200         res = BIO_read(conn->ssl_out, out_data, out_len);
2201         if (res < 0) {
2202                 tls_show_errors(MSG_INFO, __func__,
2203                                 "Encryption failed - BIO_read");
2204                 return res;
2205         }
2206
2207         return res;
2208 }
2209
2210
2211 int tls_connection_decrypt(void *ssl_ctx, struct tls_connection *conn,
2212                            const u8 *in_data, size_t in_len,
2213                            u8 *out_data, size_t out_len)
2214 {
2215         int res;
2216
2217         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2218         res = BIO_write(conn->ssl_in, in_data, in_len);
2219         if (res < 0) {
2220                 tls_show_errors(MSG_INFO, __func__,
2221                                 "Decryption failed - BIO_write");
2222                 return res;
2223         }
2224         if (BIO_reset(conn->ssl_out) < 0) {
2225                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2226                 return res;
2227         }
2228
2229         /* Read decrypted data for further processing */
2230         res = SSL_read(conn->ssl, out_data, out_len);
2231         if (res < 0) {
2232                 tls_show_errors(MSG_INFO, __func__,
2233                                 "Decryption failed - SSL_read");
2234                 return res;
2235         }
2236
2237         return res;
2238 }
2239
2240
2241 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2242 {
2243         return conn ? conn->ssl->hit : 0;
2244 }
2245
2246
2247 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2248                                    u8 *ciphers)
2249 {
2250         char buf[100], *pos, *end;
2251         u8 *c;
2252         int ret;
2253
2254         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2255                 return -1;
2256
2257         buf[0] = '\0';
2258         pos = buf;
2259         end = pos + sizeof(buf);
2260
2261         c = ciphers;
2262         while (*c != TLS_CIPHER_NONE) {
2263                 const char *suite;
2264
2265                 switch (*c) {
2266                 case TLS_CIPHER_RC4_SHA:
2267                         suite = "RC4-SHA";
2268                         break;
2269                 case TLS_CIPHER_AES128_SHA:
2270                         suite = "AES128-SHA";
2271                         break;
2272                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2273                         suite = "DHE-RSA-AES128-SHA";
2274                         break;
2275                 case TLS_CIPHER_ANON_DH_AES128_SHA:
2276                         suite = "ADH-AES128-SHA";
2277                         break;
2278                 default:
2279                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2280                                    "cipher selection: %d", *c);
2281                         return -1;
2282                 }
2283                 ret = os_snprintf(pos, end - pos, ":%s", suite);
2284                 if (ret < 0 || ret >= end - pos)
2285                         break;
2286                 pos += ret;
2287
2288                 c++;
2289         }
2290
2291         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2292
2293         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2294                 tls_show_errors(MSG_INFO, __func__,
2295                                 "Cipher suite configuration failed");
2296                 return -1;
2297         }
2298
2299         return 0;
2300 }
2301
2302
2303 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2304                    char *buf, size_t buflen)
2305 {
2306         const char *name;
2307         if (conn == NULL || conn->ssl == NULL)
2308                 return -1;
2309
2310         name = SSL_get_cipher(conn->ssl);
2311         if (name == NULL)
2312                 return -1;
2313
2314         os_strlcpy(buf, name, buflen);
2315         return 0;
2316 }
2317
2318
2319 int tls_connection_enable_workaround(void *ssl_ctx,
2320                                      struct tls_connection *conn)
2321 {
2322         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2323
2324         return 0;
2325 }
2326
2327
2328 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2329 /* ClientHello TLS extensions require a patch to openssl, so this function is
2330  * commented out unless explicitly needed for EAP-FAST in order to be able to
2331  * build this file with unmodified openssl. */
2332 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2333                                     int ext_type, const u8 *data,
2334                                     size_t data_len)
2335 {
2336         if (conn == NULL || conn->ssl == NULL)
2337                 return -1;
2338
2339         if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2340                                     data_len) != 1)
2341                 return -1;
2342
2343         return 0;
2344 }
2345 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2346
2347
2348 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2349 {
2350         if (conn == NULL)
2351                 return -1;
2352         return conn->failed;
2353 }
2354
2355
2356 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2357 {
2358         if (conn == NULL)
2359                 return -1;
2360         return conn->read_alerts;
2361 }
2362
2363
2364 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2365 {
2366         if (conn == NULL)
2367                 return -1;
2368         return conn->write_alerts;
2369 }
2370
2371
2372 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2373                               const struct tls_connection_params *params)
2374 {
2375         int ret;
2376         unsigned long err;
2377
2378         if (conn == NULL)
2379                 return -1;
2380
2381         while ((err = ERR_get_error())) {
2382                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2383                            __func__, ERR_error_string(err, NULL));
2384         }
2385
2386         if (params->engine) {
2387                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2388                 ret = tls_engine_init(conn, params->engine_id, params->pin,
2389                                       params->key_id, params->cert_id,
2390                                       params->ca_cert_id);
2391                 if (ret)
2392                         return ret;
2393         }
2394         if (tls_connection_set_subject_match(conn,
2395                                              params->subject_match,
2396                                              params->altsubject_match))
2397                 return -1;
2398
2399         if (params->engine && params->ca_cert_id) {
2400                 if (tls_connection_engine_ca_cert(tls_ctx, conn,
2401                                                   params->ca_cert_id))
2402                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2403         } else if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2404                                           params->ca_cert_blob,
2405                                           params->ca_cert_blob_len,
2406                                           params->ca_path))
2407                 return -1;
2408
2409         if (params->engine && params->cert_id) {
2410                 if (tls_connection_engine_client_cert(conn, params->cert_id))
2411                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2412         } else if (tls_connection_client_cert(conn, params->client_cert,
2413                                               params->client_cert_blob,
2414                                               params->client_cert_blob_len))
2415                 return -1;
2416
2417         if (params->engine && params->key_id) {
2418                 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
2419                 if (tls_connection_engine_private_key(conn))
2420                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2421         } else if (tls_connection_private_key(tls_ctx, conn,
2422                                               params->private_key,
2423                                               params->private_key_passwd,
2424                                               params->private_key_blob,
2425                                               params->private_key_blob_len)) {
2426                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2427                            params->private_key);
2428                 return -1;
2429         }
2430
2431         if (tls_connection_dh(conn, params->dh_file)) {
2432                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2433                            params->dh_file);
2434                 return -1;
2435         }
2436
2437         tls_get_errors(tls_ctx);
2438
2439         return 0;
2440 }
2441
2442
2443 int tls_global_set_params(void *tls_ctx,
2444                           const struct tls_connection_params *params)
2445 {
2446         SSL_CTX *ssl_ctx = tls_ctx;
2447         unsigned long err;
2448
2449         while ((err = ERR_get_error())) {
2450                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2451                            __func__, ERR_error_string(err, NULL));
2452         }
2453
2454         if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2455                 return -1;
2456
2457         if (tls_global_client_cert(ssl_ctx, params->client_cert))
2458                 return -1;
2459
2460         if (tls_global_private_key(ssl_ctx, params->private_key,
2461                                    params->private_key_passwd))
2462                 return -1;
2463
2464         if (tls_global_dh(ssl_ctx, params->dh_file)) {
2465                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2466                            params->dh_file);
2467                 return -1;
2468         }
2469
2470         return 0;
2471 }
2472
2473
2474 int tls_connection_get_keyblock_size(void *tls_ctx,
2475                                      struct tls_connection *conn)
2476 {
2477         const EVP_CIPHER *c;
2478         const EVP_MD *h;
2479
2480         if (conn == NULL || conn->ssl == NULL ||
2481             conn->ssl->enc_read_ctx == NULL ||
2482             conn->ssl->enc_read_ctx->cipher == NULL ||
2483             conn->ssl->read_hash == NULL)
2484                 return -1;
2485
2486         c = conn->ssl->enc_read_ctx->cipher;
2487 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2488         h = EVP_MD_CTX_md(conn->ssl->read_hash);
2489 #else
2490         h = conn->ssl->read_hash;
2491 #endif
2492
2493         return 2 * (EVP_CIPHER_key_length(c) +
2494                     EVP_MD_size(h) +
2495                     EVP_CIPHER_iv_length(c));
2496 }
2497
2498
2499 unsigned int tls_capabilities(void *tls_ctx)
2500 {
2501         return 0;
2502 }
2503
2504
2505 int tls_connection_set_ia(void *tls_ctx, struct tls_connection *conn,
2506                           int tls_ia)
2507 {
2508         return -1;
2509 }
2510
2511
2512 int tls_connection_ia_send_phase_finished(void *tls_ctx,
2513                                           struct tls_connection *conn,
2514                                           int final,
2515                                           u8 *out_data, size_t out_len)
2516 {
2517         return -1;
2518 }
2519
2520
2521 int tls_connection_ia_final_phase_finished(void *tls_ctx,
2522                                            struct tls_connection *conn)
2523 {
2524         return -1;
2525 }
2526
2527
2528 int tls_connection_ia_permute_inner_secret(void *tls_ctx,
2529                                            struct tls_connection *conn,
2530                                            const u8 *key, size_t key_len)
2531 {
2532         return -1;
2533 }
2534
2535
2536 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2537 /* Pre-shared secred requires a patch to openssl, so this function is
2538  * commented out unless explicitly needed for EAP-FAST in order to be able to
2539  * build this file with unmodified openssl. */
2540
2541 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2542                            STACK_OF(SSL_CIPHER) *peer_ciphers,
2543                            SSL_CIPHER **cipher, void *arg)
2544 {
2545         struct tls_connection *conn = arg;
2546         int ret;
2547
2548         if (conn == NULL || conn->session_ticket_cb == NULL)
2549                 return 0;
2550
2551         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2552                                       conn->session_ticket,
2553                                       conn->session_ticket_len,
2554                                       s->s3->client_random,
2555                                       s->s3->server_random, secret);
2556         os_free(conn->session_ticket);
2557         conn->session_ticket = NULL;
2558
2559         if (ret <= 0)
2560                 return 0;
2561
2562         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2563         return 1;
2564 }
2565
2566
2567 #ifdef SSL_OP_NO_TICKET
2568 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2569                              unsigned char *data, int len, void *arg)
2570 {
2571         struct tls_connection *conn = arg;
2572
2573         if (conn == NULL || conn->session_ticket_cb == NULL)
2574                 return;
2575
2576         wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2577                    type, len);
2578
2579         if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2580                 os_free(conn->session_ticket);
2581                 conn->session_ticket = NULL;
2582
2583                 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2584                             "extension", data, len);
2585                 conn->session_ticket = os_malloc(len);
2586                 if (conn->session_ticket == NULL)
2587                         return;
2588
2589                 os_memcpy(conn->session_ticket, data, len);
2590                 conn->session_ticket_len = len;
2591         }
2592 }
2593 #else /* SSL_OP_NO_TICKET */
2594 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2595 {
2596         struct tls_connection *conn = arg;
2597
2598         if (conn == NULL || conn->session_ticket_cb == NULL)
2599                 return 0;
2600
2601         wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2602                    ext->type, ext->length);
2603
2604         os_free(conn->session_ticket);
2605         conn->session_ticket = NULL;
2606
2607         if (ext->type == 35) {
2608                 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2609                             "extension", ext->data, ext->length);
2610                 conn->session_ticket = os_malloc(ext->length);
2611                 if (conn->session_ticket == NULL)
2612                         return SSL_AD_INTERNAL_ERROR;
2613
2614                 os_memcpy(conn->session_ticket, ext->data, ext->length);
2615                 conn->session_ticket_len = ext->length;
2616         }
2617
2618         return 0;
2619 }
2620 #endif /* SSL_OP_NO_TICKET */
2621 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2622
2623
2624 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2625                                          struct tls_connection *conn,
2626                                          tls_session_ticket_cb cb,
2627                                          void *ctx)
2628 {
2629 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2630         conn->session_ticket_cb = cb;
2631         conn->session_ticket_cb_ctx = ctx;
2632
2633         if (cb) {
2634                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2635                                               conn) != 1)
2636                         return -1;
2637 #ifdef SSL_OP_NO_TICKET
2638                 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2639                 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2640 #else /* SSL_OP_NO_TICKET */
2641                 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2642                                                conn) != 1)
2643                         return -1;
2644 #endif /* SSL_OP_NO_TICKET */
2645         } else {
2646                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2647                         return -1;
2648 #ifdef SSL_OP_NO_TICKET
2649                 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2650                 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2651 #else /* SSL_OP_NO_TICKET */
2652                 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2653                         return -1;
2654 #endif /* SSL_OP_NO_TICKET */
2655         }
2656
2657         return 0;
2658 #else /* EAP_FAST || EAP_FAST_DYNAMIC */
2659         return -1;
2660 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2661 }