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