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