OSDN Git Service

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