]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/wpa_supplicant/tls_openssl.c
merge fix for boot-time hang on centos' xen
[FreeBSD/FreeBSD.git] / contrib / wpa_supplicant / tls_openssl.c
1 /*
2  * WPA Supplicant / SSL/TLS interface functions for openssl
3  * Copyright (c) 2004-2006, Jouni Malinen <jkmaline@cc.hut.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 <stdlib.h>
16 #include <stdio.h>
17 #include <string.h>
18
19 #ifndef CONFIG_SMARTCARD
20 #ifndef OPENSSL_NO_ENGINE
21 #define OPENSSL_NO_ENGINE
22 #endif
23 #endif
24
25 #include <openssl/ssl.h>
26 #include <openssl/err.h>
27 #include <openssl/pkcs12.h>
28 #include <openssl/x509v3.h>
29 #ifndef OPENSSL_NO_ENGINE
30 #include <openssl/engine.h>
31 #endif /* OPENSSL_NO_ENGINE */
32
33 #include "common.h"
34 #include "tls.h"
35
36 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
37 #define OPENSSL_d2i_TYPE const unsigned char **
38 #else
39 #define OPENSSL_d2i_TYPE unsigned char **
40 #endif
41
42 static int tls_openssl_ref_count = 0;
43
44 struct tls_connection {
45         SSL *ssl;
46         BIO *ssl_in, *ssl_out;
47 #ifndef OPENSSL_NO_ENGINE
48         ENGINE *engine;        /* functional reference to the engine */
49         EVP_PKEY *private_key; /* the private key if using engine */
50 #endif /* OPENSSL_NO_ENGINE */
51         char *subject_match, *altsubject_match;
52         int read_alerts, write_alerts, failed;
53
54         u8 *pre_shared_secret;
55         size_t pre_shared_secret_len;
56 };
57
58
59 #ifdef CONFIG_NO_STDOUT_DEBUG
60
61 static void _tls_show_errors(void)
62 {
63         unsigned long err;
64
65         while ((err = ERR_get_error())) {
66                 /* Just ignore the errors, since stdout is disabled */
67         }
68 }
69 #define tls_show_errors(l, f, t) _tls_show_errors()
70
71 #else /* CONFIG_NO_STDOUT_DEBUG */
72
73 static void tls_show_errors(int level, const char *func, const char *txt)
74 {
75         unsigned long err;
76
77         wpa_printf(level, "OpenSSL: %s - %s %s",
78                    func, txt, ERR_error_string(ERR_get_error(), NULL));
79
80         while ((err = ERR_get_error())) {
81                 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
82                            ERR_error_string(err, NULL));
83         }
84 }
85
86 #endif /* CONFIG_NO_STDOUT_DEBUG */
87
88
89 #ifdef CONFIG_NATIVE_WINDOWS
90
91 /* Windows CryptoAPI and access to certificate stores */
92 #include <wincrypt.h>
93
94 #ifdef __MINGW32_VERSION
95 /*
96  * MinGW does not yet include all the needed definitions for CryptoAPI, so
97  * define here whatever extra is needed.
98  */
99 #define CALG_SSL3_SHAMD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
100 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
101 #define CERT_STORE_READONLY_FLAG 0x00008000
102 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
103 #define CRYPT_ACQUIRE_COMPARE_KEY_FLAG 0x00000004
104
105 static BOOL WINAPI
106 (*CryptAcquireCertificatePrivateKey)(PCCERT_CONTEXT pCert, DWORD dwFlags,
107                                      void *pvReserved, HCRYPTPROV *phCryptProv,
108                                      DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
109 = NULL; /* to be loaded from crypt32.dll */
110
111 static PCCERT_CONTEXT WINAPI
112 (*CertEnumCertificatesInStore)(HCERTSTORE hCertStore,
113                                PCCERT_CONTEXT pPrevCertContext)
114 = NULL; /* to be loaded from crypt32.dll */
115
116 static int mingw_load_crypto_func(void)
117 {
118         HINSTANCE dll;
119
120         /* MinGW does not yet have full CryptoAPI support, so load the needed
121          * function here. */
122
123         if (CryptAcquireCertificatePrivateKey)
124                 return 0;
125
126         dll = LoadLibrary("crypt32");
127         if (dll == NULL) {
128                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not load crypt32 "
129                            "library");
130                 return -1;
131         }
132
133         CryptAcquireCertificatePrivateKey = GetProcAddress(
134                 dll, "CryptAcquireCertificatePrivateKey");
135         if (CryptAcquireCertificatePrivateKey == NULL) {
136                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
137                            "CryptAcquireCertificatePrivateKey() address from "
138                            "crypt32 library");
139                 return -1;
140         }
141
142         CertEnumCertificatesInStore = (void *) GetProcAddress(
143                 dll, "CertEnumCertificatesInStore");
144         if (CertEnumCertificatesInStore == NULL) {
145                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
146                            "CertEnumCertificatesInStore() address from "
147                            "crypt32 library");
148                 return -1;
149         }
150
151         return 0;
152 }
153
154 #else /* __MINGW32_VERSION */
155
156 static int mingw_load_crypto_func(void)
157 {
158         return 0;
159 }
160
161 #endif /* __MINGW32_VERSION */
162
163
164 struct cryptoapi_rsa_data {
165         const CERT_CONTEXT *cert;
166         HCRYPTPROV crypt_prov;
167         DWORD key_spec;
168         BOOL free_crypt_prov;
169 };
170
171
172 static void cryptoapi_error(const char *msg)
173 {
174         wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
175                    msg, (unsigned int) GetLastError());
176 }
177
178
179 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
180                                  unsigned char *to, RSA *rsa, int padding)
181 {
182         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
183         return 0;
184 }
185
186
187 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
188                                  unsigned char *to, RSA *rsa, int padding)
189 {
190         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
191         return 0;
192 }
193
194
195 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
196                                   unsigned char *to, RSA *rsa, int padding)
197 {
198         struct cryptoapi_rsa_data *priv =
199                 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
200         HCRYPTHASH hash;
201         DWORD hash_size, len, i;
202         unsigned char *buf = NULL;
203         int ret = 0;
204
205         if (priv == NULL) {
206                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
207                        ERR_R_PASSED_NULL_PARAMETER);
208                 return 0;
209         }
210
211         if (padding != RSA_PKCS1_PADDING) {
212                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
213                        RSA_R_UNKNOWN_PADDING_TYPE);
214                 return 0;
215         }
216
217         if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
218                 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
219                            __func__);
220                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
221                        RSA_R_INVALID_MESSAGE_LENGTH);
222                 return 0;
223         }
224
225         if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
226         {
227                 cryptoapi_error("CryptCreateHash failed");
228                 return 0;
229         }
230
231         len = sizeof(hash_size);
232         if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
233                                0)) {
234                 cryptoapi_error("CryptGetHashParam failed");
235                 goto err;
236         }
237
238         if (hash_size != flen) {
239                 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
240                            (unsigned) hash_size, flen);
241                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
242                        RSA_R_INVALID_MESSAGE_LENGTH);
243                 goto err;
244         }
245         if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
246                 cryptoapi_error("CryptSetHashParam failed");
247                 goto err;
248         }
249
250         len = RSA_size(rsa);
251         buf = malloc(len);
252         if (buf == NULL) {
253                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
254                 goto err;
255         }
256
257         if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
258                 cryptoapi_error("CryptSignHash failed");
259                 goto err;
260         }
261
262         for (i = 0; i < len; i++)
263                 to[i] = buf[len - i - 1];
264         ret = len;
265
266 err:
267         free(buf);
268         CryptDestroyHash(hash);
269
270         return ret;
271 }
272
273
274 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
275                                   unsigned char *to, RSA *rsa, int padding)
276 {
277         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
278         return 0;
279 }
280
281
282 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
283 {
284         if (priv == NULL)
285                 return;
286         if (priv->crypt_prov && priv->free_crypt_prov)
287                 CryptReleaseContext(priv->crypt_prov, 0);
288         if (priv->cert)
289                 CertFreeCertificateContext(priv->cert);
290         free(priv);
291 }
292
293
294 static int cryptoapi_finish(RSA *rsa)
295 {
296         cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
297         free((void *) rsa->meth);
298         rsa->meth = NULL;
299         return 1;
300 }
301
302
303 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
304 {
305         HCERTSTORE cs;
306         const CERT_CONTEXT *ret = NULL;
307
308         cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
309                            store | CERT_STORE_OPEN_EXISTING_FLAG |
310                            CERT_STORE_READONLY_FLAG, L"MY");
311         if (cs == NULL) {
312                 cryptoapi_error("Failed to open 'My system store'");
313                 return NULL;
314         }
315
316         if (strncmp(name, "cert://", 7) == 0) {
317                 unsigned short wbuf[255];
318                 MultiByteToWideChar(CP_ACP, 0, name + 7, -1,
319                                     wbuf, sizeof(wbuf));
320                 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
321                                                  PKCS_7_ASN_ENCODING,
322                                                  0, CERT_FIND_SUBJECT_STR,
323                                                  wbuf, NULL);
324         } else if (strncmp(name, "hash://", 7) == 0) {
325                 CRYPT_HASH_BLOB blob;
326                 int len;
327                 const char *hash = name + 7;
328                 unsigned char *buf;
329
330                 len = strlen(hash) / 2;
331                 buf = malloc(len);
332                 if (buf && hexstr2bin(hash, buf, len) == 0) {
333                         blob.cbData = len;
334                         blob.pbData = buf;
335                         ret = CertFindCertificateInStore(cs,
336                                                          X509_ASN_ENCODING |
337                                                          PKCS_7_ASN_ENCODING,
338                                                          0, CERT_FIND_HASH,
339                                                          &blob, NULL);
340                 }
341                 free(buf);
342         }
343
344         CertCloseStore(cs, 0);
345
346         return ret;
347 }
348
349
350 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
351 {
352         X509 *cert = NULL;
353         RSA *rsa = NULL, *pub_rsa;
354         struct cryptoapi_rsa_data *priv;
355         RSA_METHOD *rsa_meth;
356
357         if (name == NULL ||
358             (strncmp(name, "cert://", 7) != 0 &&
359              strncmp(name, "hash://", 7) != 0))
360                 return -1;
361
362         priv = malloc(sizeof(*priv));
363         rsa_meth = malloc(sizeof(*rsa_meth));
364         if (priv == NULL || rsa_meth == NULL) {
365                 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
366                            "for CryptoAPI RSA method");
367                 free(priv);
368                 free(rsa_meth);
369                 return -1;
370         }
371         memset(priv, 0, sizeof(*priv));
372         memset(rsa_meth, 0, sizeof(*rsa_meth));
373
374         priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
375         if (priv->cert == NULL) {
376                 priv->cert = cryptoapi_find_cert(
377                         name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
378         }
379         if (priv->cert == NULL) {
380                 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
381                            "'%s'", name);
382                 goto err;
383         }
384
385         cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
386                         priv->cert->cbCertEncoded);
387         if (cert == NULL) {
388                 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
389                            "encoding");
390                 goto err;
391         }
392
393         if (mingw_load_crypto_func())
394                 goto err;
395
396         if (!CryptAcquireCertificatePrivateKey(priv->cert,
397                                                CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
398                                                NULL, &priv->crypt_prov,
399                                                &priv->key_spec,
400                                                &priv->free_crypt_prov)) {
401                 cryptoapi_error("Failed to acquire a private key for the "
402                                 "certificate");
403                 goto err;
404         }
405
406         rsa_meth->name = "Microsoft CryptoAPI RSA Method";
407         rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
408         rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
409         rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
410         rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
411         rsa_meth->finish = cryptoapi_finish;
412         rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
413         rsa_meth->app_data = (char *) priv;
414
415         rsa = RSA_new();
416         if (rsa == NULL) {
417                 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
418                        ERR_R_MALLOC_FAILURE);
419                 goto err;
420         }
421
422         if (!SSL_use_certificate(ssl, cert))
423                 goto err;
424         pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
425         X509_free(cert);
426         cert = NULL;
427
428         rsa->n = BN_dup(pub_rsa->n);
429         rsa->e = BN_dup(pub_rsa->e);
430         if (!RSA_set_method(rsa, rsa_meth))
431                 goto err;
432
433         if (!SSL_use_RSAPrivateKey(ssl, rsa))
434                 goto err;
435         RSA_free(rsa);
436
437         return 0;
438
439 err:
440         if (cert)
441                 X509_free(cert);
442         if (rsa)
443                 RSA_free(rsa);
444         else {
445                 free(rsa_meth);
446                 cryptoapi_free_data(priv);
447         }
448         return -1;
449 }
450
451
452 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
453 {
454         HCERTSTORE cs;
455         PCCERT_CONTEXT ctx = NULL;
456         X509 *cert;
457         char buf[128];
458
459         if (mingw_load_crypto_func())
460                 return -1;
461
462         if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
463                 return -1;
464
465         cs = CertOpenSystemStore(0, name + 13);
466         if (cs == NULL) {
467                 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
468                            "'%s': error=%d", __func__, name + 13,
469                            (int) GetLastError());
470                 return -1;
471         }
472
473         while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
474                 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
475                                 ctx->cbCertEncoded);
476                 if (cert == NULL) {
477                         wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
478                                    "X509 DER encoding for CA cert");
479                         continue;
480                 }
481
482                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
483                                   sizeof(buf));
484                 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
485                            "system certificate store: subject='%s'", buf);
486
487                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
488                         tls_show_errors(MSG_WARNING, __func__,
489                                         "Failed to add ca_cert to OpenSSL "
490                                         "certificate store");
491                 }
492
493                 X509_free(cert);
494         }
495
496         if (!CertCloseStore(cs, 0)) {
497                 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
498                            "'%s': error=%d", __func__, name + 13,
499                            (int) GetLastError());
500         }
501
502         return 0;
503 }
504
505
506 #else /* CONFIG_NATIVE_WINDOWS */
507
508 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
509 {
510         return -1;
511 }
512
513 #endif /* CONFIG_NATIVE_WINDOWS */
514
515
516 static void ssl_info_cb(const SSL *ssl, int where, int ret)
517 {
518         const char *str;
519         int w;
520
521         wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
522         w = where & ~SSL_ST_MASK;
523         if (w & SSL_ST_CONNECT)
524                 str = "SSL_connect";
525         else if (w & SSL_ST_ACCEPT)
526                 str = "SSL_accept";
527         else
528                 str = "undefined";
529
530         if (where & SSL_CB_LOOP) {
531                 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
532                            str, SSL_state_string_long(ssl));
533         } else if (where & SSL_CB_ALERT) {
534                 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
535                            where & SSL_CB_READ ?
536                            "read (remote end reported an error)" :
537                            "write (local SSL3 detected an error)",
538                            SSL_alert_type_string_long(ret),
539                            SSL_alert_desc_string_long(ret));
540                 if ((ret >> 8) == SSL3_AL_FATAL) {
541                         struct tls_connection *conn =
542                                 SSL_get_app_data((SSL *) ssl);
543                         if (where & SSL_CB_READ)
544                                 conn->read_alerts++;
545                         else
546                                 conn->write_alerts++;
547                 }
548         } else if (where & SSL_CB_EXIT && ret <= 0) {
549                 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
550                            str, ret == 0 ? "failed" : "error",
551                            SSL_state_string_long(ssl));
552         }
553 }
554
555
556 #ifndef OPENSSL_NO_ENGINE
557 /**
558  * tls_engine_load_dynamic_generic - load any openssl engine
559  * @pre: an array of commands and values that load an engine initialized
560  *       in the engine specific function
561  * @post: an array of commands and values that initialize an already loaded
562  *        engine (or %NULL if not required)
563  * @id: the engine id of the engine to load (only required if post is not %NULL
564  *
565  * This function is a generic function that loads any openssl engine.
566  *
567  * Returns: 0 on success, -1 on failure
568  */
569 static int tls_engine_load_dynamic_generic(const char *pre[],
570                                            const char *post[], const char *id)
571 {
572         ENGINE *engine;
573         const char *dynamic_id = "dynamic";
574
575         engine = ENGINE_by_id(id);
576         if (engine) {
577                 ENGINE_free(engine);
578                 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
579                            "available", id);
580                 return 0;
581         }
582         ERR_clear_error();
583
584         engine = ENGINE_by_id(dynamic_id);
585         if (engine == NULL) {
586                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
587                            dynamic_id,
588                            ERR_error_string(ERR_get_error(), NULL));
589                 return -1;
590         }
591
592         /* Perform the pre commands. This will load the engine. */
593         while (pre && pre[0]) {
594                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
595                 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
596                         wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
597                                    "%s %s [%s]", pre[0], pre[1],
598                                    ERR_error_string(ERR_get_error(), NULL));
599                         ENGINE_free(engine);
600                         return -1;
601                 }
602                 pre += 2;
603         }
604
605         /*
606          * Free the reference to the "dynamic" engine. The loaded engine can
607          * now be looked up using ENGINE_by_id().
608          */
609         ENGINE_free(engine);
610
611         engine = ENGINE_by_id(id);
612         if (engine == NULL) {
613                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
614                            id, ERR_error_string(ERR_get_error(), NULL));
615                 return -1;
616         }
617
618         while (post && post[0]) {
619                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
620                 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
621                         wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
622                                 " %s %s [%s]", post[0], post[1],
623                                    ERR_error_string(ERR_get_error(), NULL));
624                         ENGINE_remove(engine);
625                         ENGINE_free(engine);
626                         return -1;
627                 }
628                 post += 2;
629         }
630         ENGINE_free(engine);
631
632         return 0;
633 }
634
635
636 /**
637  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
638  * @pkcs11_so_path: pksc11_so_path from the configuration
639  * @pcks11_module_path: pkcs11_module_path from the configuration
640  */
641 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
642                                           const char *pkcs11_module_path)
643 {
644         char *engine_id = "pkcs11";
645         const char *pre_cmd[] = {
646                 "SO_PATH", pkcs11_so_path,
647                 "ID", engine_id,
648                 "LIST_ADD", "1",
649                 /* "NO_VCHECK", "1", */
650                 "LOAD", NULL,
651                 NULL, NULL
652         };
653         const char *post_cmd[] = {
654                 "MODULE_PATH", pkcs11_module_path,
655                 NULL, NULL
656         };
657
658         if (!pkcs11_so_path || !pkcs11_module_path)
659                 return 0;
660
661         wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
662                    pkcs11_so_path);
663
664         return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
665 }
666
667
668 /**
669  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
670  * @opensc_so_path: opensc_so_path from the configuration
671  */
672 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
673 {
674         char *engine_id = "opensc";
675         const char *pre_cmd[] = {
676                 "SO_PATH", opensc_so_path,
677                 "ID", engine_id,
678                 "LIST_ADD", "1",
679                 "LOAD", NULL,
680                 NULL, NULL
681         };
682
683         if (!opensc_so_path)
684                 return 0;
685
686         wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
687                    opensc_so_path);
688
689         return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
690 }
691 #endif /* OPENSSL_NO_ENGINE */
692
693
694 void * tls_init(const struct tls_config *conf)
695 {
696         SSL_CTX *ssl;
697
698         if (tls_openssl_ref_count == 0) {
699                 SSL_load_error_strings();
700                 SSL_library_init();
701                 /* TODO: if /dev/urandom is available, PRNG is seeded
702                  * automatically. If this is not the case, random data should
703                  * be added here. */
704
705 #ifdef PKCS12_FUNCS
706                 PKCS12_PBE_add();
707 #endif  /* PKCS12_FUNCS */
708         }
709         tls_openssl_ref_count++;
710
711         ssl = SSL_CTX_new(TLSv1_method());
712         if (ssl == NULL)
713                 return NULL;
714
715         SSL_CTX_set_info_callback(ssl, ssl_info_cb);
716
717 #ifndef OPENSSL_NO_ENGINE
718         if (conf &&
719             (conf->opensc_engine_path || conf->pkcs11_engine_path ||
720              conf->pkcs11_module_path)) {
721                 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
722                 ERR_load_ENGINE_strings();
723                 ENGINE_load_dynamic();
724
725                 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
726                     tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
727                                                    conf->pkcs11_module_path)) {
728                         tls_deinit(ssl);
729                         return NULL;
730                 }
731         }
732 #endif /* OPENSSL_NO_ENGINE */
733
734         return ssl;
735 }
736
737
738 void tls_deinit(void *ssl_ctx)
739 {
740         SSL_CTX *ssl = ssl_ctx;
741         SSL_CTX_free(ssl);
742
743         tls_openssl_ref_count--;
744         if (tls_openssl_ref_count == 0) {
745 #ifndef OPENSSL_NO_ENGINE
746                 ENGINE_cleanup();
747 #endif /* OPENSSL_NO_ENGINE */
748                 ERR_free_strings();
749                 EVP_cleanup();
750         }
751 }
752
753
754 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
755                            const char *pin, const char *key_id)
756 {
757 #ifndef OPENSSL_NO_ENGINE
758         int ret = -1;
759         if (engine_id == NULL) {
760                 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
761                 return -1;
762         }
763         if (pin == NULL) {
764                 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
765                 return -1;
766         }
767         if (key_id == NULL) {
768                 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
769                 return -1;
770         }
771
772         ERR_clear_error();
773         conn->engine = ENGINE_by_id(engine_id);
774         if (!conn->engine) {
775                 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
776                            engine_id, ERR_error_string(ERR_get_error(), NULL));
777                 goto err;
778         }
779         if (ENGINE_init(conn->engine) != 1) {
780                 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
781                            "(engine: %s) [%s]", engine_id,
782                            ERR_error_string(ERR_get_error(), NULL));
783                 goto err;
784         }
785         wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
786
787         if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
788                 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
789                            ERR_error_string(ERR_get_error(), NULL));
790                 goto err;
791         }
792         conn->private_key = ENGINE_load_private_key(conn->engine,
793                                                     key_id, NULL, NULL);
794         if (!conn->private_key) {
795                 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
796                                 " '%s' [%s]", key_id,
797                            ERR_error_string(ERR_get_error(), NULL));
798                 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
799                 goto err;
800         }
801         return 0;
802
803 err:
804         if (conn->engine) {
805                 ENGINE_free(conn->engine);
806                 conn->engine = NULL;
807         }
808
809         if (conn->private_key) {
810                 EVP_PKEY_free(conn->private_key);
811                 conn->private_key = NULL;
812         }
813
814         return ret;
815 #else /* OPENSSL_NO_ENGINE */
816         return 0;
817 #endif /* OPENSSL_NO_ENGINE */
818 }
819
820
821 static void tls_engine_deinit(struct tls_connection *conn)
822 {
823 #ifndef OPENSSL_NO_ENGINE
824         wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
825         if (conn->private_key) {
826                 EVP_PKEY_free(conn->private_key);
827                 conn->private_key = NULL;
828         }
829         if (conn->engine) {
830                 ENGINE_finish(conn->engine);
831                 conn->engine = NULL;
832         }
833 #endif /* OPENSSL_NO_ENGINE */
834 }
835
836
837 int tls_get_errors(void *ssl_ctx)
838 {
839         int count = 0;
840         unsigned long err;
841
842         while ((err = ERR_get_error())) {
843                 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
844                            ERR_error_string(err, NULL));
845                 count++;
846         }
847
848         return count;
849 }
850
851 struct tls_connection * tls_connection_init(void *ssl_ctx)
852 {
853         SSL_CTX *ssl = ssl_ctx;
854         struct tls_connection *conn;
855
856         conn = malloc(sizeof(*conn));
857         if (conn == NULL)
858                 return NULL;
859         memset(conn, 0, sizeof(*conn));
860         conn->ssl = SSL_new(ssl);
861         if (conn->ssl == NULL) {
862                 tls_show_errors(MSG_INFO, __func__,
863                                 "Failed to initialize new SSL connection");
864                 free(conn);
865                 return NULL;
866         }
867
868         SSL_set_app_data(conn->ssl, conn);
869         SSL_set_options(conn->ssl,
870                         SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
871                         SSL_OP_SINGLE_DH_USE);
872
873         conn->ssl_in = BIO_new(BIO_s_mem());
874         if (!conn->ssl_in) {
875                 tls_show_errors(MSG_INFO, __func__,
876                                 "Failed to create a new BIO for ssl_in");
877                 SSL_free(conn->ssl);
878                 free(conn);
879                 return NULL;
880         }
881
882         conn->ssl_out = BIO_new(BIO_s_mem());
883         if (!conn->ssl_out) {
884                 tls_show_errors(MSG_INFO, __func__,
885                                 "Failed to create a new BIO for ssl_out");
886                 SSL_free(conn->ssl);
887                 BIO_free(conn->ssl_in);
888                 free(conn);
889                 return NULL;
890         }
891
892         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
893
894         return conn;
895 }
896
897
898 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
899 {
900         if (conn == NULL)
901                 return;
902         free(conn->pre_shared_secret);
903         SSL_free(conn->ssl);
904         tls_engine_deinit(conn);
905         free(conn->subject_match);
906         free(conn->altsubject_match);
907         free(conn);
908 }
909
910
911 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
912 {
913         return conn ? SSL_is_init_finished(conn->ssl) : 0;
914 }
915
916
917 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
918 {
919         if (conn == NULL)
920                 return -1;
921
922         /* Shutdown previous TLS connection without notifying the peer
923          * because the connection was already terminated in practice
924          * and "close notify" shutdown alert would confuse AS. */
925         SSL_set_quiet_shutdown(conn->ssl, 1);
926         SSL_shutdown(conn->ssl);
927         return 0;
928 }
929
930
931 static int tls_match_altsubject(X509 *cert, const char *match)
932 {
933         GENERAL_NAME *gen;
934         char *field, *tmp;
935         void *ext;
936         int i, found = 0;
937         size_t len;
938
939         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
940
941         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
942                 gen = sk_GENERAL_NAME_value(ext, i);
943                 switch (gen->type) {
944                 case GEN_EMAIL:
945                         field = "EMAIL";
946                         break;
947                 case GEN_DNS:
948                         field = "DNS";
949                         break;
950                 case GEN_URI:
951                         field = "URI";
952                         break;
953                 default:
954                         field = NULL;
955                         wpa_printf(MSG_DEBUG, "TLS: altSubjectName: "
956                                    "unsupported type=%d", gen->type);
957                         break;
958                 }
959
960                 if (!field)
961                         continue;
962
963                 wpa_printf(MSG_DEBUG, "TLS: altSubjectName: %s:%s",
964                            field, gen->d.ia5->data);
965                 len = strlen(field) + 1 + strlen((char *) gen->d.ia5->data) +
966                         1;
967                 tmp = malloc(len);
968                 if (tmp == NULL)
969                         continue;
970                 snprintf(tmp, len, "%s:%s", field, gen->d.ia5->data);
971                 if (strstr(tmp, match))
972                         found++;
973                 free(tmp);
974         }
975
976         return found;
977 }
978
979
980 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
981 {
982         char buf[256];
983         X509 *err_cert;
984         int err, depth;
985         SSL *ssl;
986         struct tls_connection *conn;
987         char *match, *altmatch;
988
989         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
990         err = X509_STORE_CTX_get_error(x509_ctx);
991         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
992         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
993                                          SSL_get_ex_data_X509_STORE_CTX_idx());
994         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
995
996         conn = SSL_get_app_data(ssl);
997         match = conn ? conn->subject_match : NULL;
998         altmatch = conn ? conn->altsubject_match : NULL;
999
1000         if (!preverify_ok) {
1001                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1002                            " error %d (%s) depth %d for '%s'", err,
1003                            X509_verify_cert_error_string(err), depth, buf);
1004         } else {
1005                 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - "
1006                            "preverify_ok=%d err=%d (%s) depth=%d buf='%s'",
1007                            preverify_ok, err,
1008                            X509_verify_cert_error_string(err), depth, buf);
1009                 if (depth == 0 && match && strstr(buf, match) == NULL) {
1010                         wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1011                                    "match with '%s'", buf, match);
1012                         preverify_ok = 0;
1013                 } else if (depth == 0 && altmatch &&
1014                            !tls_match_altsubject(err_cert, altmatch)) {
1015                         wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1016                                    "'%s' not found", altmatch);
1017                         preverify_ok = 0;
1018                 }
1019         }
1020
1021         return preverify_ok;
1022 }
1023
1024
1025 #ifndef OPENSSL_NO_STDIO
1026 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1027 {
1028         SSL_CTX *ssl_ctx = _ssl_ctx;
1029         X509_LOOKUP *lookup;
1030         int ret = 0;
1031
1032         lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1033                                        X509_LOOKUP_file());
1034         if (lookup == NULL) {
1035                 tls_show_errors(MSG_WARNING, __func__,
1036                                 "Failed add lookup for X509 store");
1037                 return -1;
1038         }
1039
1040         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1041                 unsigned long err = ERR_peek_error();
1042                 tls_show_errors(MSG_WARNING, __func__,
1043                                 "Failed load CA in DER format");
1044                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1045                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1046                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1047                                    "cert already in hash table error",
1048                                    __func__);
1049                 } else
1050                         ret = -1;
1051         }
1052
1053         return ret;
1054 }
1055 #endif /* OPENSSL_NO_STDIO */
1056
1057
1058 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1059                                   const char *ca_cert, const u8 *ca_cert_blob,
1060                                   size_t ca_cert_blob_len, const char *ca_path)
1061 {
1062         SSL_CTX *ssl_ctx = _ssl_ctx;
1063
1064         if (ca_cert_blob) {
1065                 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1066                                       ca_cert_blob_len);
1067                 if (cert == NULL) {
1068                         tls_show_errors(MSG_WARNING, __func__,
1069                                         "Failed to parse ca_cert_blob");
1070                         return -1;
1071                 }
1072
1073                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1074                         tls_show_errors(MSG_WARNING, __func__,
1075                                         "Failed to add ca_cert_blob to "
1076                                         "certificate store");
1077                         X509_free(cert);
1078                         return -1;
1079                 }
1080                 X509_free(cert);
1081                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1082                            "to certificate store", __func__);
1083                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1084                 return 0;
1085         }
1086
1087 #ifdef CONFIG_NATIVE_WINDOWS
1088         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1089             0) {
1090                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1091                            "system certificate store");
1092                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1093                 return 0;
1094         }
1095 #endif /* CONFIG_NATIVE_WINDOWS */
1096
1097         if (ca_cert || ca_path) {
1098 #ifndef OPENSSL_NO_STDIO
1099                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1100                     1) {
1101                         tls_show_errors(MSG_WARNING, __func__,
1102                                         "Failed to load root certificates");
1103                         if (ca_cert &&
1104                             tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1105                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1106                                            "DER format CA certificate",
1107                                            __func__);
1108                         } else
1109                                 return -1;
1110                 } else {
1111                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1112                                    "certificate(s) loaded");
1113                         tls_get_errors(ssl_ctx);
1114                 }
1115                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1116 #else /* OPENSSL_NO_STDIO */
1117                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1118                            __func__);
1119                 return -1;
1120 #endif /* OPENSSL_NO_STDIO */
1121         } else {
1122                 /* No ca_cert configured - do not try to verify server
1123                  * certificate */
1124                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1125         }
1126
1127         return 0;
1128 }
1129
1130
1131 int tls_global_ca_cert(void *_ssl_ctx, const char *ca_cert)
1132 {
1133         SSL_CTX *ssl_ctx = _ssl_ctx;
1134         if (ca_cert) {
1135                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1136                 {
1137                         tls_show_errors(MSG_WARNING, __func__,
1138                                         "Failed to load root certificates");
1139                         return -1;
1140                 }
1141
1142                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1143                            "certificate(s) loaded");
1144
1145 #ifndef OPENSSL_NO_STDIO
1146                 /* Add the same CAs to the client certificate requests */
1147                 SSL_CTX_set_client_CA_list(ssl_ctx,
1148                                            SSL_load_client_CA_file(ca_cert));
1149 #endif /* OPENSSL_NO_STDIO */
1150         }
1151
1152         return 0;
1153 }
1154
1155
1156 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1157 {
1158         int flags;
1159
1160         if (check_crl) {
1161                 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1162                 if (cs == NULL) {
1163                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
1164                                         "certificate store when enabling "
1165                                         "check_crl");
1166                         return -1;
1167                 }
1168                 flags = X509_V_FLAG_CRL_CHECK;
1169                 if (check_crl == 2)
1170                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
1171                 X509_STORE_set_flags(cs, flags);
1172         }
1173         return 0;
1174 }
1175
1176
1177 static int tls_connection_set_subject_match(void *ssl_ctx,
1178                                             struct tls_connection *conn,
1179                                             const char *subject_match,
1180                                             const char *altsubject_match)
1181 {
1182         free(conn->subject_match);
1183         conn->subject_match = NULL;
1184         if (subject_match) {
1185                 conn->subject_match = strdup(subject_match);
1186                 if (conn->subject_match == NULL)
1187                         return -1;
1188         }
1189
1190         free(conn->altsubject_match);
1191         conn->altsubject_match = NULL;
1192         if (altsubject_match) {
1193                 conn->altsubject_match = strdup(altsubject_match);
1194                 if (conn->altsubject_match == NULL)
1195                         return -1;
1196         }
1197
1198         return 0;
1199 }
1200
1201
1202 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1203                               int verify_peer)
1204 {
1205         if (conn == NULL)
1206                 return -1;
1207
1208         if (verify_peer) {
1209                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1210                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1211                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1212         } else {
1213                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1214         }
1215
1216         SSL_set_accept_state(conn->ssl);
1217
1218         return 0;
1219 }
1220
1221
1222 static int tls_connection_client_cert(void *ssl_ctx,
1223                                       struct tls_connection *conn,
1224                                       const char *client_cert,
1225                                       const u8 *client_cert_blob,
1226                                       size_t client_cert_blob_len)
1227 {
1228         if (client_cert == NULL && client_cert_blob == NULL)
1229                 return 0;
1230
1231         if (client_cert_blob &&
1232             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1233                                      client_cert_blob_len) == 1) {
1234                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1235                            "OK");
1236                 return 0;
1237         } else if (client_cert_blob) {
1238                 tls_show_errors(MSG_DEBUG, __func__,
1239                                 "SSL_use_certificate_ASN1 failed");
1240         }
1241
1242         if (client_cert == NULL)
1243                 return -1;
1244
1245 #ifndef OPENSSL_NO_STDIO
1246         if (SSL_use_certificate_file(conn->ssl, client_cert,
1247                                      SSL_FILETYPE_ASN1) == 1) {
1248                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1249                            " --> OK");
1250                 return 0;
1251         } else {
1252                 tls_show_errors(MSG_DEBUG, __func__,
1253                                 "SSL_use_certificate_file (DER) failed");
1254         }
1255
1256         if (SSL_use_certificate_file(conn->ssl, client_cert,
1257                                      SSL_FILETYPE_PEM) == 1) {
1258                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1259                            " --> OK");
1260                 return 0;
1261         } else {
1262                 tls_show_errors(MSG_DEBUG, __func__,
1263                                 "SSL_use_certificate_file (PEM) failed");
1264         }
1265 #else /* OPENSSL_NO_STDIO */
1266         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1267 #endif /* OPENSSL_NO_STDIO */
1268
1269         return -1;
1270 }
1271
1272
1273 int tls_global_client_cert(void *_ssl_ctx, const char *client_cert)
1274 {
1275 #ifndef OPENSSL_NO_STDIO
1276         SSL_CTX *ssl_ctx = _ssl_ctx;
1277         if (client_cert == NULL)
1278                 return 0;
1279
1280         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1281                                          SSL_FILETYPE_ASN1) != 1 &&
1282             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1283                                          SSL_FILETYPE_PEM) != 1) {
1284                 tls_show_errors(MSG_INFO, __func__,
1285                                 "Failed to load client certificate");
1286                 return -1;
1287         }
1288         return 0;
1289 #else /* OPENSSL_NO_STDIO */
1290         if (client_cert == NULL)
1291                 return 0;
1292         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1293         return -1;
1294 #endif /* OPENSSL_NO_STDIO */
1295 }
1296
1297
1298 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1299 {
1300         if (password == NULL) {
1301                 return 0;
1302         }
1303         strncpy(buf, (char *) password, size);
1304         buf[size - 1] = '\0';
1305         return strlen(buf);
1306 }
1307
1308
1309 #ifdef PKCS12_FUNCS
1310 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1311                             const char *passwd)
1312 {
1313         EVP_PKEY *pkey;
1314         X509 *cert;
1315         STACK_OF(X509) *certs;
1316         int res = 0;
1317         char buf[256];
1318
1319         pkey = NULL;
1320         cert = NULL;
1321         certs = NULL;
1322         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1323                 tls_show_errors(MSG_DEBUG, __func__,
1324                                 "Failed to parse PKCS12 file");
1325                 return -1;
1326         }
1327         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1328
1329         if (cert) {
1330                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1331                                   sizeof(buf));
1332                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1333                            "subject='%s'", buf);
1334                 if (ssl) {
1335                         if (SSL_use_certificate(ssl, cert) != 1)
1336                                 res = -1;
1337                 } else {
1338                         if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1339                                 res = -1;
1340                 }
1341                 X509_free(cert);
1342         }
1343
1344         if (pkey) {
1345                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1346                 if (ssl) {
1347                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
1348                                 res = -1;
1349                 } else {
1350                         if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1351                                 res = -1;
1352                 }
1353                 EVP_PKEY_free(pkey);
1354         }
1355
1356         if (certs) {
1357                 while ((cert = sk_X509_pop(certs)) != NULL) {
1358                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
1359                                           sizeof(buf));
1360                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1361                                    " from PKCS12: subject='%s'", buf);
1362                         /*
1363                          * There is no SSL equivalent for the chain cert - so
1364                          * always add it to the context...
1365                          */
1366                         if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1367                                 res = -1;
1368                                 break;
1369                         }
1370                 }
1371                 sk_X509_free(certs);
1372         }
1373
1374         PKCS12_free(p12);
1375
1376         if (res < 0)
1377                 tls_get_errors(ssl_ctx);
1378
1379         return res;
1380 }
1381 #endif  /* PKCS12_FUNCS */
1382
1383
1384 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1385                            const char *passwd)
1386 {
1387 #ifdef PKCS12_FUNCS
1388         FILE *f;
1389         PKCS12 *p12;
1390
1391         f = fopen(private_key, "r");
1392         if (f == NULL)
1393                 return -1;
1394
1395         p12 = d2i_PKCS12_fp(f, NULL);
1396         fclose(f);
1397
1398         if (p12 == NULL) {
1399                 tls_show_errors(MSG_INFO, __func__,
1400                                 "Failed to use PKCS#12 file");
1401                 return -1;
1402         }
1403
1404         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1405
1406 #else /* PKCS12_FUNCS */
1407         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1408                    "p12/pfx files");
1409         return -1;
1410 #endif  /* PKCS12_FUNCS */
1411 }
1412
1413
1414 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1415                                 const u8 *blob, size_t len, const char *passwd)
1416 {
1417 #ifdef PKCS12_FUNCS
1418         PKCS12 *p12;
1419
1420         p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1421         if (p12 == NULL) {
1422                 tls_show_errors(MSG_INFO, __func__,
1423                                 "Failed to use PKCS#12 blob");
1424                 return -1;
1425         }
1426
1427         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1428
1429 #else /* PKCS12_FUNCS */
1430         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1431                    "p12/pfx blobs");
1432         return -1;
1433 #endif  /* PKCS12_FUNCS */
1434 }
1435
1436
1437 static int tls_connection_engine_private_key(void *_ssl_ctx,
1438                                              struct tls_connection *conn)
1439 {
1440 #ifndef OPENSSL_NO_ENGINE
1441         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1442                 tls_show_errors(MSG_ERROR, __func__,
1443                                 "ENGINE: cannot use private key for TLS");
1444                 return -1;
1445         }
1446         if (!SSL_check_private_key(conn->ssl)) {
1447                 tls_show_errors(MSG_INFO, __func__,
1448                                 "Private key failed verification");
1449                 return -1;
1450         }
1451         return 0;
1452 #else /* OPENSSL_NO_ENGINE */
1453         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1454                    "engine support was not compiled in");
1455         return -1;
1456 #endif /* OPENSSL_NO_ENGINE */
1457 }
1458
1459
1460 static int tls_connection_private_key(void *_ssl_ctx,
1461                                       struct tls_connection *conn,
1462                                       const char *private_key,
1463                                       const char *private_key_passwd,
1464                                       const u8 *private_key_blob,
1465                                       size_t private_key_blob_len)
1466 {
1467         SSL_CTX *ssl_ctx = _ssl_ctx;
1468         char *passwd;
1469         int ok;
1470
1471         if (private_key == NULL && private_key_blob == NULL)
1472                 return 0;
1473
1474         if (private_key_passwd) {
1475                 passwd = strdup(private_key_passwd);
1476                 if (passwd == NULL)
1477                         return -1;
1478         } else
1479                 passwd = NULL;
1480
1481         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1482         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1483
1484         ok = 0;
1485         while (private_key_blob) {
1486                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1487                                             (u8 *) private_key_blob,
1488                                             private_key_blob_len) == 1) {
1489                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1490                                    "ASN1(EVP_PKEY_RSA) --> OK");
1491                         ok = 1;
1492                         break;
1493                 } else {
1494                         tls_show_errors(MSG_DEBUG, __func__,
1495                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
1496                                         " failed");
1497                 }
1498
1499                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1500                                             (u8 *) private_key_blob,
1501                                             private_key_blob_len) == 1) {
1502                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1503                                    "ASN1(EVP_PKEY_DSA) --> OK");
1504                         ok = 1;
1505                         break;
1506                 } else {
1507                         tls_show_errors(MSG_DEBUG, __func__,
1508                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
1509                                         " failed");
1510                 }
1511
1512                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1513                                                (u8 *) private_key_blob,
1514                                                private_key_blob_len) == 1) {
1515                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1516                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
1517                         ok = 1;
1518                         break;
1519                 } else {
1520                         tls_show_errors(MSG_DEBUG, __func__,
1521                                         "SSL_use_RSAPrivateKey_ASN1 failed");
1522                 }
1523
1524                 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1525                                          private_key_blob_len, passwd) == 0) {
1526                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1527                                    "OK");
1528                         ok = 1;
1529                         break;
1530                 }
1531
1532                 break;
1533         }
1534
1535         while (!ok && private_key) {
1536 #ifndef OPENSSL_NO_STDIO
1537                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1538                                             SSL_FILETYPE_ASN1) == 1) {
1539                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1540                                    "SSL_use_PrivateKey_File (DER) --> OK");
1541                         ok = 1;
1542                         break;
1543                 } else {
1544                         tls_show_errors(MSG_DEBUG, __func__,
1545                                         "SSL_use_PrivateKey_File (DER) "
1546                                         "failed");
1547                 }
1548
1549                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1550                                             SSL_FILETYPE_PEM) == 1) {
1551                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1552                                    "SSL_use_PrivateKey_File (PEM) --> OK");
1553                         ok = 1;
1554                         break;
1555                 } else {
1556                         tls_show_errors(MSG_DEBUG, __func__,
1557                                         "SSL_use_PrivateKey_File (PEM) "
1558                                         "failed");
1559                 }
1560 #else /* OPENSSL_NO_STDIO */
1561                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1562                            __func__);
1563 #endif /* OPENSSL_NO_STDIO */
1564
1565                 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
1566                     == 0) {
1567                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
1568                                    "--> OK");
1569                         ok = 1;
1570                         break;
1571                 }
1572
1573                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
1574                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
1575                                    "access certificate store --> OK");
1576                         ok = 1;
1577                         break;
1578                 }
1579
1580                 break;
1581         }
1582
1583         if (!ok) {
1584                 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
1585                 free(passwd);
1586                 ERR_clear_error();
1587                 return -1;
1588         }
1589         ERR_clear_error();
1590         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1591         free(passwd);
1592         
1593         if (!SSL_check_private_key(conn->ssl)) {
1594                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
1595                                 "verification");
1596                 return -1;
1597         }
1598
1599         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
1600         return 0;
1601 }
1602
1603
1604 int tls_global_private_key(void *_ssl_ctx, const char *private_key,
1605                            const char *private_key_passwd)
1606 {
1607         SSL_CTX *ssl_ctx = _ssl_ctx;
1608         char *passwd;
1609
1610         if (private_key == NULL)
1611                 return 0;
1612
1613         if (private_key_passwd) {
1614                 passwd = strdup(private_key_passwd);
1615                 if (passwd == NULL)
1616                         return -1;
1617         } else
1618                 passwd = NULL;
1619
1620         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1621         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1622         if (
1623 #ifndef OPENSSL_NO_STDIO
1624             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1625                                         SSL_FILETYPE_ASN1) != 1 &&
1626             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1627                                         SSL_FILETYPE_PEM) != 1 &&
1628 #endif /* OPENSSL_NO_STDIO */
1629             tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
1630                 tls_show_errors(MSG_INFO, __func__,
1631                                 "Failed to load private key");
1632                 free(passwd);
1633                 ERR_clear_error();
1634                 return -1;
1635         }
1636         free(passwd);
1637         ERR_clear_error();
1638         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1639         
1640         if (!SSL_CTX_check_private_key(ssl_ctx)) {
1641                 tls_show_errors(MSG_INFO, __func__,
1642                                 "Private key failed verification");
1643                 return -1;
1644         }
1645
1646         return 0;
1647 }
1648
1649
1650 static int tls_connection_dh(void *ssl_ctx, struct tls_connection *conn,
1651                       const char *dh_file)
1652 {
1653 #ifdef OPENSSL_NO_DH
1654         if (dh_file == NULL)
1655                 return 0;
1656         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1657                    "dh_file specified");
1658         return -1;
1659 #else /* OPENSSL_NO_DH */
1660         DH *dh;
1661         BIO *bio;
1662
1663         /* TODO: add support for dh_blob */
1664         if (dh_file == NULL)
1665                 return 0;
1666         if (conn == NULL)
1667                 return -1;
1668
1669         bio = BIO_new_file(dh_file, "r");
1670         if (bio == NULL) {
1671                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1672                            dh_file, ERR_error_string(ERR_get_error(), NULL));
1673                 return -1;
1674         }
1675         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1676         BIO_free(bio);
1677 #ifndef OPENSSL_NO_DSA
1678         while (dh == NULL) {
1679                 DSA *dsa;
1680                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1681                            " trying to parse as DSA params", dh_file,
1682                            ERR_error_string(ERR_get_error(), NULL));
1683                 bio = BIO_new_file(dh_file, "r");
1684                 if (bio == NULL)
1685                         break;
1686                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1687                 BIO_free(bio);
1688                 if (!dsa) {
1689                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1690                                    "'%s': %s", dh_file,
1691                                    ERR_error_string(ERR_get_error(), NULL));
1692                         break;
1693                 }
1694
1695                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1696                 dh = DSA_dup_DH(dsa);
1697                 DSA_free(dsa);
1698                 if (dh == NULL) {
1699                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1700                                    "params into DH params");
1701                         break;
1702                 }
1703                 break;
1704         }
1705 #endif /* !OPENSSL_NO_DSA */
1706         if (dh == NULL) {
1707                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1708                            "'%s'", dh_file);
1709                 return -1;
1710         }
1711
1712         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
1713                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1714                            "%s", dh_file,
1715                            ERR_error_string(ERR_get_error(), NULL));
1716                 DH_free(dh);
1717                 return -1;
1718         }
1719         DH_free(dh);
1720         return 0;
1721 #endif /* OPENSSL_NO_DH */
1722 }
1723
1724
1725 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
1726                             struct tls_keys *keys)
1727 {
1728         SSL *ssl;
1729
1730         if (conn == NULL || keys == NULL)
1731                 return -1;
1732         ssl = conn->ssl;
1733         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
1734                 return -1;
1735
1736         memset(keys, 0, sizeof(*keys));
1737         keys->master_key = ssl->session->master_key;
1738         keys->master_key_len = ssl->session->master_key_length;
1739         keys->client_random = ssl->s3->client_random;
1740         keys->client_random_len = SSL3_RANDOM_SIZE;
1741         keys->server_random = ssl->s3->server_random;
1742         keys->server_random_len = SSL3_RANDOM_SIZE;
1743
1744         return 0;
1745 }
1746
1747
1748 u8 * tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
1749                               const u8 *in_data, size_t in_len,
1750                               size_t *out_len)
1751 {
1752         int res;
1753         u8 *out_data;
1754
1755         /*
1756          * Give TLS handshake data from the server (if available) to OpenSSL
1757          * for processing.
1758          */
1759         if (in_data &&
1760             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
1761                 tls_show_errors(MSG_INFO, __func__,
1762                                 "Handshake failed - BIO_write");
1763                 return NULL;
1764         }
1765
1766         /* Initiate TLS handshake or continue the existing handshake */
1767         res = SSL_connect(conn->ssl);
1768         if (res != 1) {
1769                 int err = SSL_get_error(conn->ssl, res);
1770                 if (err == SSL_ERROR_WANT_READ)
1771                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
1772                                    "more data");
1773                 else if (err == SSL_ERROR_WANT_WRITE)
1774                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
1775                                    "write");
1776                 else {
1777                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
1778                         conn->failed++;
1779                 }
1780         }
1781
1782         /* Get the TLS handshake data to be sent to the server */
1783         res = BIO_ctrl_pending(conn->ssl_out);
1784         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
1785         out_data = malloc(res == 0 ? 1 : res);
1786         if (out_data == NULL) {
1787                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
1788                            "handshake output (%d bytes)", res);
1789                 if (BIO_reset(conn->ssl_out) < 0) {
1790                         tls_show_errors(MSG_INFO, __func__,
1791                                         "BIO_reset failed");
1792                 }
1793                 *out_len = 0;
1794                 return NULL;
1795         }
1796         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
1797         if (res < 0) {
1798                 tls_show_errors(MSG_INFO, __func__,
1799                                 "Handshake failed - BIO_read");
1800                 if (BIO_reset(conn->ssl_out) < 0) {
1801                         tls_show_errors(MSG_INFO, __func__,
1802                                         "BIO_reset failed");
1803                 }
1804                 *out_len = 0;
1805                 return NULL;
1806         }
1807         *out_len = res;
1808         return out_data;
1809 }
1810
1811
1812 u8 * tls_connection_server_handshake(void *ssl_ctx,
1813                                      struct tls_connection *conn,
1814                                      const u8 *in_data, size_t in_len,
1815                                      size_t *out_len)
1816 {
1817         int res;
1818         u8 *out_data;
1819         char buf[10];
1820
1821         if (in_data &&
1822             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
1823                 tls_show_errors(MSG_INFO, __func__,
1824                                 "Handshake failed - BIO_write");
1825                 return NULL;
1826         }
1827
1828         res = SSL_read(conn->ssl, buf, sizeof(buf));
1829         if (res >= 0) {
1830                 wpa_printf(MSG_DEBUG, "SSL: Unexpected data from SSL_read "
1831                            "(res=%d)", res);
1832         }
1833
1834         res = BIO_ctrl_pending(conn->ssl_out);
1835         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
1836         out_data = malloc(res == 0 ? 1 : res);
1837         if (out_data == NULL) {
1838                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
1839                            "handshake output (%d bytes)", res);
1840                 if (BIO_reset(conn->ssl_out) < 0) {
1841                         tls_show_errors(MSG_INFO, __func__,
1842                                         "BIO_reset failed");
1843                 }
1844                 *out_len = 0;
1845                 return NULL;
1846         }
1847         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
1848         if (res < 0) {
1849                 tls_show_errors(MSG_INFO, __func__,
1850                                 "Handshake failed - BIO_read");
1851                 if (BIO_reset(conn->ssl_out) < 0) {
1852                         tls_show_errors(MSG_INFO, __func__,
1853                                         "BIO_reset failed");
1854                 }
1855                 *out_len = 0;
1856                 return NULL;
1857         }
1858         *out_len = res;
1859         return out_data;
1860 }
1861
1862
1863 int tls_connection_encrypt(void *ssl_ctx, struct tls_connection *conn,
1864                            const u8 *in_data, size_t in_len,
1865                            u8 *out_data, size_t out_len)
1866 {
1867         int res;
1868
1869         if (conn == NULL)
1870                 return -1;
1871
1872         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
1873         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
1874             (res = BIO_reset(conn->ssl_out)) < 0) {
1875                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
1876                 return res;
1877         }
1878         res = SSL_write(conn->ssl, in_data, in_len);
1879         if (res < 0) {
1880                 tls_show_errors(MSG_INFO, __func__,
1881                                 "Encryption failed - SSL_write");
1882                 return res;
1883         }
1884
1885         /* Read encrypted data to be sent to the server */
1886         res = BIO_read(conn->ssl_out, out_data, out_len);
1887         if (res < 0) {
1888                 tls_show_errors(MSG_INFO, __func__,
1889                                 "Encryption failed - BIO_read");
1890                 return res;
1891         }
1892
1893         return res;
1894 }
1895
1896
1897 int tls_connection_decrypt(void *ssl_ctx, struct tls_connection *conn,
1898                            const u8 *in_data, size_t in_len,
1899                            u8 *out_data, size_t out_len)
1900 {
1901         int res;
1902
1903         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
1904         res = BIO_write(conn->ssl_in, in_data, in_len);
1905         if (res < 0) {
1906                 tls_show_errors(MSG_INFO, __func__,
1907                                 "Decryption failed - BIO_write");
1908                 return res;
1909         }
1910         if (BIO_reset(conn->ssl_out) < 0) {
1911                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
1912                 return res;
1913         }
1914
1915         /* Read decrypted data for further processing */
1916         res = SSL_read(conn->ssl, out_data, out_len);
1917         if (res < 0) {
1918                 tls_show_errors(MSG_INFO, __func__,
1919                                 "Decryption failed - SSL_read");
1920                 return res;
1921         }
1922
1923         return res;
1924 }
1925
1926
1927 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
1928 {
1929         return conn ? conn->ssl->hit : 0;
1930 }
1931
1932
1933 #ifdef EAP_FAST
1934 /* Pre-shared secred requires a patch to openssl, so this function is
1935  * commented out unless explicitly needed for EAP-FAST in order to be able to
1936  * build this file with unmodified openssl. */
1937
1938 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
1939                            STACK_OF(SSL_CIPHER) *peer_ciphers,
1940                            SSL_CIPHER **cipher, void *arg)
1941 {
1942         struct tls_connection *conn = arg;
1943
1944         if (conn == NULL || conn->pre_shared_secret == 0)
1945                 return 0;
1946
1947         memcpy(secret, conn->pre_shared_secret, conn->pre_shared_secret_len);
1948         *secret_len = conn->pre_shared_secret_len;
1949
1950         return 1;
1951 }
1952
1953
1954 int tls_connection_set_master_key(void *ssl_ctx, struct tls_connection *conn,
1955                                   const u8 *key, size_t key_len)
1956 {
1957         if (conn == NULL || key_len > SSL_MAX_MASTER_KEY_LENGTH)
1958                 return -1;
1959
1960         free(conn->pre_shared_secret);
1961         conn->pre_shared_secret = NULL;
1962         conn->pre_shared_secret_len = 0;
1963
1964         if (key) {
1965                 conn->pre_shared_secret = malloc(key_len);
1966                 if (conn->pre_shared_secret) {
1967                         memcpy(conn->pre_shared_secret, key, key_len);
1968                         conn->pre_shared_secret_len = key_len;
1969                 }
1970                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
1971                                               conn) != 1)
1972                         return -1;
1973         } else {
1974                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
1975                         return -1;
1976         }
1977
1978         return 0;
1979 }
1980 #endif /* EAP_FAST */
1981
1982
1983 int tls_connection_set_anon_dh(void *ssl_ctx, struct tls_connection *conn)
1984 {
1985         if (conn == NULL || conn->ssl == NULL)
1986                 return -1;
1987
1988         if (SSL_set_cipher_list(conn->ssl, "ADH-AES128-SHA") != 1) {
1989                 tls_show_errors(MSG_INFO, __func__,
1990                                 "Anon DH configuration failed");
1991                 return -1;
1992         }
1993
1994         return 0;
1995 }
1996
1997
1998 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
1999                    char *buf, size_t buflen)
2000 {
2001         const char *name;
2002         if (conn == NULL || conn->ssl == NULL)
2003                 return -1;
2004
2005         name = SSL_get_cipher(conn->ssl);
2006         if (name == NULL)
2007                 return -1;
2008
2009         snprintf(buf, buflen, "%s", name);
2010         return 0;
2011 }
2012
2013
2014 int tls_connection_enable_workaround(void *ssl_ctx,
2015                                      struct tls_connection *conn)
2016 {
2017         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2018
2019         return 0;
2020 }
2021
2022
2023 #ifdef EAP_FAST
2024 /* ClientHello TLS extensions require a patch to openssl, so this function is
2025  * commented out unless explicitly needed for EAP-FAST in order to be able to
2026  * build this file with unmodified openssl. */
2027 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2028                                     int ext_type, const u8 *data,
2029                                     size_t data_len)
2030 {
2031         if (conn == NULL || conn->ssl == NULL)
2032                 return -1;
2033
2034         if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2035                                     data_len) != 1)
2036                 return -1;
2037
2038         return 0;
2039 }
2040 #endif /* EAP_FAST */
2041
2042
2043 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2044 {
2045         if (conn == NULL)
2046                 return -1;
2047         return conn->failed;
2048 }
2049
2050
2051 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2052 {
2053         if (conn == NULL)
2054                 return -1;
2055         return conn->read_alerts;
2056 }
2057
2058
2059 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2060 {
2061         if (conn == NULL)
2062                 return -1;
2063         return conn->write_alerts;
2064 }
2065
2066
2067 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2068                               const struct tls_connection_params *params)
2069 {
2070         int ret;
2071         unsigned long err;
2072
2073         if (conn == NULL)
2074                 return -1;
2075
2076         while ((err = ERR_get_error())) {
2077                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2078                            __func__, ERR_error_string(err, NULL));
2079         }
2080
2081         if (tls_connection_set_subject_match(tls_ctx, conn,
2082                                              params->subject_match,
2083                                              params->altsubject_match))
2084                 return -1;
2085         if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2086                                    params->ca_cert_blob,
2087                                    params->ca_cert_blob_len,
2088                                    params->ca_path))
2089                 return -1;
2090         if (tls_connection_client_cert(tls_ctx, conn, params->client_cert,
2091                                        params->client_cert_blob,
2092                                        params->client_cert_blob_len))
2093                 return -1;
2094
2095         if (params->engine) {
2096                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2097                 ret = tls_engine_init(conn, params->engine_id, params->pin,
2098                                       params->key_id);
2099                 if (ret)
2100                         return ret;
2101                 if (tls_connection_engine_private_key(tls_ctx, conn))
2102                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2103         } else if (tls_connection_private_key(tls_ctx, conn,
2104                                               params->private_key,
2105                                               params->private_key_passwd,
2106                                               params->private_key_blob,
2107                                               params->private_key_blob_len)) {
2108                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2109                            params->private_key);
2110                 return -1;
2111         }
2112
2113         if (tls_connection_dh(tls_ctx, conn, params->dh_file)) {
2114                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2115                            params->dh_file);
2116                 return -1;
2117         }
2118
2119         tls_get_errors(tls_ctx);
2120
2121         return 0;
2122 }
2123
2124
2125 int tls_connection_get_keyblock_size(void *tls_ctx,
2126                                      struct tls_connection *conn)
2127 {
2128         const EVP_CIPHER *c;
2129         const EVP_MD *h;
2130
2131         if (conn == NULL || conn->ssl == NULL ||
2132             conn->ssl->enc_read_ctx == NULL ||
2133             conn->ssl->enc_read_ctx->cipher == NULL ||
2134             conn->ssl->read_hash == NULL)
2135                 return -1;
2136
2137         c = conn->ssl->enc_read_ctx->cipher;
2138         h = conn->ssl->read_hash;
2139
2140         return 2 * (EVP_CIPHER_key_length(c) +
2141                     EVP_MD_size(h) +
2142                     EVP_CIPHER_iv_length(c));
2143 }