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