Re-initialize hostapd/wpa_supplicant git repository based on 0.6.3 release
[wpasupplicant] / 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
881         conn = os_zalloc(sizeof(*conn));
882         if (conn == NULL)
883                 return NULL;
884         conn->ssl = SSL_new(ssl);
885         if (conn->ssl == NULL) {
886                 tls_show_errors(MSG_INFO, __func__,
887                                 "Failed to initialize new SSL connection");
888                 os_free(conn);
889                 return NULL;
890         }
891
892         SSL_set_app_data(conn->ssl, conn);
893         SSL_set_options(conn->ssl,
894                         SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
895                         SSL_OP_SINGLE_DH_USE);
896
897         conn->ssl_in = BIO_new(BIO_s_mem());
898         if (!conn->ssl_in) {
899                 tls_show_errors(MSG_INFO, __func__,
900                                 "Failed to create a new BIO for ssl_in");
901                 SSL_free(conn->ssl);
902                 os_free(conn);
903                 return NULL;
904         }
905
906         conn->ssl_out = BIO_new(BIO_s_mem());
907         if (!conn->ssl_out) {
908                 tls_show_errors(MSG_INFO, __func__,
909                                 "Failed to create a new BIO for ssl_out");
910                 SSL_free(conn->ssl);
911                 BIO_free(conn->ssl_in);
912                 os_free(conn);
913                 return NULL;
914         }
915
916         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
917
918         return conn;
919 }
920
921
922 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
923 {
924         if (conn == NULL)
925                 return;
926         SSL_free(conn->ssl);
927         tls_engine_deinit(conn);
928         os_free(conn->subject_match);
929         os_free(conn->altsubject_match);
930         os_free(conn->session_ticket);
931         os_free(conn);
932 }
933
934
935 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
936 {
937         return conn ? SSL_is_init_finished(conn->ssl) : 0;
938 }
939
940
941 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
942 {
943         if (conn == NULL)
944                 return -1;
945
946         /* Shutdown previous TLS connection without notifying the peer
947          * because the connection was already terminated in practice
948          * and "close notify" shutdown alert would confuse AS. */
949         SSL_set_quiet_shutdown(conn->ssl, 1);
950         SSL_shutdown(conn->ssl);
951         return 0;
952 }
953
954
955 static int tls_match_altsubject_component(X509 *cert, int type,
956                                           const char *value, size_t len)
957 {
958         GENERAL_NAME *gen;
959         void *ext;
960         int i, found = 0;
961
962         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
963
964         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
965                 gen = sk_GENERAL_NAME_value(ext, i);
966                 if (gen->type != type)
967                         continue;
968                 if (os_strlen((char *) gen->d.ia5->data) == len &&
969                     os_memcmp(value, gen->d.ia5->data, len) == 0)
970                         found++;
971         }
972
973         return found;
974 }
975
976
977 static int tls_match_altsubject(X509 *cert, const char *match)
978 {
979         int type;
980         const char *pos, *end;
981         size_t len;
982
983         pos = match;
984         do {
985                 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
986                         type = GEN_EMAIL;
987                         pos += 6;
988                 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
989                         type = GEN_DNS;
990                         pos += 4;
991                 } else if (os_strncmp(pos, "URI:", 4) == 0) {
992                         type = GEN_URI;
993                         pos += 4;
994                 } else {
995                         wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
996                                    "match '%s'", pos);
997                         return 0;
998                 }
999                 end = os_strchr(pos, ';');
1000                 while (end) {
1001                         if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
1002                             os_strncmp(end + 1, "DNS:", 4) == 0 ||
1003                             os_strncmp(end + 1, "URI:", 4) == 0)
1004                                 break;
1005                         end = os_strchr(end + 1, ';');
1006                 }
1007                 if (end)
1008                         len = end - pos;
1009                 else
1010                         len = os_strlen(pos);
1011                 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
1012                         return 1;
1013                 pos = end + 1;
1014         } while (end);
1015
1016         return 0;
1017 }
1018
1019
1020 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
1021 {
1022         char buf[256];
1023         X509 *err_cert;
1024         int err, depth;
1025         SSL *ssl;
1026         struct tls_connection *conn;
1027         char *match, *altmatch;
1028
1029         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
1030         err = X509_STORE_CTX_get_error(x509_ctx);
1031         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
1032         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
1033                                          SSL_get_ex_data_X509_STORE_CTX_idx());
1034         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
1035
1036         conn = SSL_get_app_data(ssl);
1037         match = conn ? conn->subject_match : NULL;
1038         altmatch = conn ? conn->altsubject_match : NULL;
1039
1040         if (!preverify_ok) {
1041                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
1042                            " error %d (%s) depth %d for '%s'", err,
1043                            X509_verify_cert_error_string(err), depth, buf);
1044         } else {
1045                 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - "
1046                            "preverify_ok=%d err=%d (%s) depth=%d buf='%s'",
1047                            preverify_ok, err,
1048                            X509_verify_cert_error_string(err), depth, buf);
1049                 if (depth == 0 && match && os_strstr(buf, match) == NULL) {
1050                         wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
1051                                    "match with '%s'", buf, match);
1052                         preverify_ok = 0;
1053                 } else if (depth == 0 && altmatch &&
1054                            !tls_match_altsubject(err_cert, altmatch)) {
1055                         wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
1056                                    "'%s' not found", altmatch);
1057                         preverify_ok = 0;
1058                 }
1059         }
1060
1061         return preverify_ok;
1062 }
1063
1064
1065 #ifndef OPENSSL_NO_STDIO
1066 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
1067 {
1068         SSL_CTX *ssl_ctx = _ssl_ctx;
1069         X509_LOOKUP *lookup;
1070         int ret = 0;
1071
1072         lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
1073                                        X509_LOOKUP_file());
1074         if (lookup == NULL) {
1075                 tls_show_errors(MSG_WARNING, __func__,
1076                                 "Failed add lookup for X509 store");
1077                 return -1;
1078         }
1079
1080         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
1081                 unsigned long err = ERR_peek_error();
1082                 tls_show_errors(MSG_WARNING, __func__,
1083                                 "Failed load CA in DER format");
1084                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1085                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1086                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1087                                    "cert already in hash table error",
1088                                    __func__);
1089                 } else
1090                         ret = -1;
1091         }
1092
1093         return ret;
1094 }
1095 #endif /* OPENSSL_NO_STDIO */
1096
1097
1098 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
1099                                   const char *ca_cert, const u8 *ca_cert_blob,
1100                                   size_t ca_cert_blob_len, const char *ca_path)
1101 {
1102         SSL_CTX *ssl_ctx = _ssl_ctx;
1103
1104         /*
1105          * Remove previously configured trusted CA certificates before adding
1106          * new ones.
1107          */
1108         X509_STORE_free(ssl_ctx->cert_store);
1109         ssl_ctx->cert_store = X509_STORE_new();
1110         if (ssl_ctx->cert_store == NULL) {
1111                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
1112                            "certificate store", __func__);
1113                 return -1;
1114         }
1115
1116         if (ca_cert_blob) {
1117                 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
1118                                       ca_cert_blob_len);
1119                 if (cert == NULL) {
1120                         tls_show_errors(MSG_WARNING, __func__,
1121                                         "Failed to parse ca_cert_blob");
1122                         return -1;
1123                 }
1124
1125                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
1126                         unsigned long err = ERR_peek_error();
1127                         tls_show_errors(MSG_WARNING, __func__,
1128                                         "Failed to add ca_cert_blob to "
1129                                         "certificate store");
1130                         if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
1131                             ERR_GET_REASON(err) ==
1132                             X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1133                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
1134                                            "cert already in hash table error",
1135                                            __func__);
1136                         } else {
1137                                 X509_free(cert);
1138                                 return -1;
1139                         }
1140                 }
1141                 X509_free(cert);
1142                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
1143                            "to certificate store", __func__);
1144                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1145                 return 0;
1146         }
1147
1148 #ifdef CONFIG_NATIVE_WINDOWS
1149         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
1150             0) {
1151                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
1152                            "system certificate store");
1153                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1154                 return 0;
1155         }
1156 #endif /* CONFIG_NATIVE_WINDOWS */
1157
1158         if (ca_cert || ca_path) {
1159 #ifndef OPENSSL_NO_STDIO
1160                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
1161                     1) {
1162                         tls_show_errors(MSG_WARNING, __func__,
1163                                         "Failed to load root certificates");
1164                         if (ca_cert &&
1165                             tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
1166                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
1167                                            "DER format CA certificate",
1168                                            __func__);
1169                         } else
1170                                 return -1;
1171                 } else {
1172                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1173                                    "certificate(s) loaded");
1174                         tls_get_errors(ssl_ctx);
1175                 }
1176                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
1177 #else /* OPENSSL_NO_STDIO */
1178                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1179                            __func__);
1180                 return -1;
1181 #endif /* OPENSSL_NO_STDIO */
1182         } else {
1183                 /* No ca_cert configured - do not try to verify server
1184                  * certificate */
1185                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1186         }
1187
1188         return 0;
1189 }
1190
1191
1192 static int tls_global_ca_cert(SSL_CTX *ssl_ctx, const char *ca_cert)
1193 {
1194         if (ca_cert) {
1195                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
1196                 {
1197                         tls_show_errors(MSG_WARNING, __func__,
1198                                         "Failed to load root certificates");
1199                         return -1;
1200                 }
1201
1202                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
1203                            "certificate(s) loaded");
1204
1205 #ifndef OPENSSL_NO_STDIO
1206                 /* Add the same CAs to the client certificate requests */
1207                 SSL_CTX_set_client_CA_list(ssl_ctx,
1208                                            SSL_load_client_CA_file(ca_cert));
1209 #endif /* OPENSSL_NO_STDIO */
1210         }
1211
1212         return 0;
1213 }
1214
1215
1216 int tls_global_set_verify(void *ssl_ctx, int check_crl)
1217 {
1218         int flags;
1219
1220         if (check_crl) {
1221                 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
1222                 if (cs == NULL) {
1223                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
1224                                         "certificate store when enabling "
1225                                         "check_crl");
1226                         return -1;
1227                 }
1228                 flags = X509_V_FLAG_CRL_CHECK;
1229                 if (check_crl == 2)
1230                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
1231                 X509_STORE_set_flags(cs, flags);
1232         }
1233         return 0;
1234 }
1235
1236
1237 static int tls_connection_set_subject_match(struct tls_connection *conn,
1238                                             const char *subject_match,
1239                                             const char *altsubject_match)
1240 {
1241         os_free(conn->subject_match);
1242         conn->subject_match = NULL;
1243         if (subject_match) {
1244                 conn->subject_match = os_strdup(subject_match);
1245                 if (conn->subject_match == NULL)
1246                         return -1;
1247         }
1248
1249         os_free(conn->altsubject_match);
1250         conn->altsubject_match = NULL;
1251         if (altsubject_match) {
1252                 conn->altsubject_match = os_strdup(altsubject_match);
1253                 if (conn->altsubject_match == NULL)
1254                         return -1;
1255         }
1256
1257         return 0;
1258 }
1259
1260
1261 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
1262                               int verify_peer)
1263 {
1264         if (conn == NULL)
1265                 return -1;
1266
1267         if (verify_peer) {
1268                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
1269                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
1270                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
1271         } else {
1272                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
1273         }
1274
1275         SSL_set_accept_state(conn->ssl);
1276
1277         return 0;
1278 }
1279
1280
1281 static int tls_connection_client_cert(struct tls_connection *conn,
1282                                       const char *client_cert,
1283                                       const u8 *client_cert_blob,
1284                                       size_t client_cert_blob_len)
1285 {
1286         if (client_cert == NULL && client_cert_blob == NULL)
1287                 return 0;
1288
1289         if (client_cert_blob &&
1290             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
1291                                      client_cert_blob_len) == 1) {
1292                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
1293                            "OK");
1294                 return 0;
1295         } else if (client_cert_blob) {
1296                 tls_show_errors(MSG_DEBUG, __func__,
1297                                 "SSL_use_certificate_ASN1 failed");
1298         }
1299
1300         if (client_cert == NULL)
1301                 return -1;
1302
1303 #ifndef OPENSSL_NO_STDIO
1304         if (SSL_use_certificate_file(conn->ssl, client_cert,
1305                                      SSL_FILETYPE_ASN1) == 1) {
1306                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
1307                            " --> OK");
1308                 return 0;
1309         } else {
1310                 tls_show_errors(MSG_DEBUG, __func__,
1311                                 "SSL_use_certificate_file (DER) failed");
1312         }
1313
1314         if (SSL_use_certificate_file(conn->ssl, client_cert,
1315                                      SSL_FILETYPE_PEM) == 1) {
1316                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
1317                            " --> OK");
1318                 return 0;
1319         } else {
1320                 tls_show_errors(MSG_DEBUG, __func__,
1321                                 "SSL_use_certificate_file (PEM) failed");
1322         }
1323 #else /* OPENSSL_NO_STDIO */
1324         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1325 #endif /* OPENSSL_NO_STDIO */
1326
1327         return -1;
1328 }
1329
1330
1331 static int tls_global_client_cert(SSL_CTX *ssl_ctx, const char *client_cert)
1332 {
1333 #ifndef OPENSSL_NO_STDIO
1334         if (client_cert == NULL)
1335                 return 0;
1336
1337         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1338                                          SSL_FILETYPE_ASN1) != 1 &&
1339             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
1340                                          SSL_FILETYPE_PEM) != 1) {
1341                 tls_show_errors(MSG_INFO, __func__,
1342                                 "Failed to load client certificate");
1343                 return -1;
1344         }
1345         return 0;
1346 #else /* OPENSSL_NO_STDIO */
1347         if (client_cert == NULL)
1348                 return 0;
1349         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
1350         return -1;
1351 #endif /* OPENSSL_NO_STDIO */
1352 }
1353
1354
1355 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
1356 {
1357         if (password == NULL) {
1358                 return 0;
1359         }
1360         os_strlcpy(buf, (char *) password, size);
1361         return os_strlen(buf);
1362 }
1363
1364
1365 #ifdef PKCS12_FUNCS
1366 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
1367                             const char *passwd)
1368 {
1369         EVP_PKEY *pkey;
1370         X509 *cert;
1371         STACK_OF(X509) *certs;
1372         int res = 0;
1373         char buf[256];
1374
1375         pkey = NULL;
1376         cert = NULL;
1377         certs = NULL;
1378         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
1379                 tls_show_errors(MSG_DEBUG, __func__,
1380                                 "Failed to parse PKCS12 file");
1381                 PKCS12_free(p12);
1382                 return -1;
1383         }
1384         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
1385
1386         if (cert) {
1387                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
1388                                   sizeof(buf));
1389                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
1390                            "subject='%s'", buf);
1391                 if (ssl) {
1392                         if (SSL_use_certificate(ssl, cert) != 1)
1393                                 res = -1;
1394                 } else {
1395                         if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
1396                                 res = -1;
1397                 }
1398                 X509_free(cert);
1399         }
1400
1401         if (pkey) {
1402                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
1403                 if (ssl) {
1404                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
1405                                 res = -1;
1406                 } else {
1407                         if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
1408                                 res = -1;
1409                 }
1410                 EVP_PKEY_free(pkey);
1411         }
1412
1413         if (certs) {
1414                 while ((cert = sk_X509_pop(certs)) != NULL) {
1415                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
1416                                           sizeof(buf));
1417                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
1418                                    " from PKCS12: subject='%s'", buf);
1419                         /*
1420                          * There is no SSL equivalent for the chain cert - so
1421                          * always add it to the context...
1422                          */
1423                         if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
1424                                 res = -1;
1425                                 break;
1426                         }
1427                 }
1428                 sk_X509_free(certs);
1429         }
1430
1431         PKCS12_free(p12);
1432
1433         if (res < 0)
1434                 tls_get_errors(ssl_ctx);
1435
1436         return res;
1437 }
1438 #endif  /* PKCS12_FUNCS */
1439
1440
1441 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
1442                            const char *passwd)
1443 {
1444 #ifdef PKCS12_FUNCS
1445         FILE *f;
1446         PKCS12 *p12;
1447
1448         f = fopen(private_key, "rb");
1449         if (f == NULL)
1450                 return -1;
1451
1452         p12 = d2i_PKCS12_fp(f, NULL);
1453         fclose(f);
1454
1455         if (p12 == NULL) {
1456                 tls_show_errors(MSG_INFO, __func__,
1457                                 "Failed to use PKCS#12 file");
1458                 return -1;
1459         }
1460
1461         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1462
1463 #else /* PKCS12_FUNCS */
1464         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
1465                    "p12/pfx files");
1466         return -1;
1467 #endif  /* PKCS12_FUNCS */
1468 }
1469
1470
1471 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
1472                                 const u8 *blob, size_t len, const char *passwd)
1473 {
1474 #ifdef PKCS12_FUNCS
1475         PKCS12 *p12;
1476
1477         p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
1478         if (p12 == NULL) {
1479                 tls_show_errors(MSG_INFO, __func__,
1480                                 "Failed to use PKCS#12 blob");
1481                 return -1;
1482         }
1483
1484         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
1485
1486 #else /* PKCS12_FUNCS */
1487         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
1488                    "p12/pfx blobs");
1489         return -1;
1490 #endif  /* PKCS12_FUNCS */
1491 }
1492
1493
1494 static int tls_connection_engine_private_key(struct tls_connection *conn)
1495 {
1496 #ifndef OPENSSL_NO_ENGINE
1497         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
1498                 tls_show_errors(MSG_ERROR, __func__,
1499                                 "ENGINE: cannot use private key for TLS");
1500                 return -1;
1501         }
1502         if (!SSL_check_private_key(conn->ssl)) {
1503                 tls_show_errors(MSG_INFO, __func__,
1504                                 "Private key failed verification");
1505                 return -1;
1506         }
1507         return 0;
1508 #else /* OPENSSL_NO_ENGINE */
1509         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
1510                    "engine support was not compiled in");
1511         return -1;
1512 #endif /* OPENSSL_NO_ENGINE */
1513 }
1514
1515
1516 static int tls_connection_private_key(void *_ssl_ctx,
1517                                       struct tls_connection *conn,
1518                                       const char *private_key,
1519                                       const char *private_key_passwd,
1520                                       const u8 *private_key_blob,
1521                                       size_t private_key_blob_len)
1522 {
1523         SSL_CTX *ssl_ctx = _ssl_ctx;
1524         char *passwd;
1525         int ok;
1526
1527         if (private_key == NULL && private_key_blob == NULL)
1528                 return 0;
1529
1530         if (private_key_passwd) {
1531                 passwd = os_strdup(private_key_passwd);
1532                 if (passwd == NULL)
1533                         return -1;
1534         } else
1535                 passwd = NULL;
1536
1537         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1538         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1539
1540         ok = 0;
1541         while (private_key_blob) {
1542                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
1543                                             (u8 *) private_key_blob,
1544                                             private_key_blob_len) == 1) {
1545                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1546                                    "ASN1(EVP_PKEY_RSA) --> OK");
1547                         ok = 1;
1548                         break;
1549                 } else {
1550                         tls_show_errors(MSG_DEBUG, __func__,
1551                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
1552                                         " failed");
1553                 }
1554
1555                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
1556                                             (u8 *) private_key_blob,
1557                                             private_key_blob_len) == 1) {
1558                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
1559                                    "ASN1(EVP_PKEY_DSA) --> OK");
1560                         ok = 1;
1561                         break;
1562                 } else {
1563                         tls_show_errors(MSG_DEBUG, __func__,
1564                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
1565                                         " failed");
1566                 }
1567
1568                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
1569                                                (u8 *) private_key_blob,
1570                                                private_key_blob_len) == 1) {
1571                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1572                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
1573                         ok = 1;
1574                         break;
1575                 } else {
1576                         tls_show_errors(MSG_DEBUG, __func__,
1577                                         "SSL_use_RSAPrivateKey_ASN1 failed");
1578                 }
1579
1580                 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
1581                                          private_key_blob_len, passwd) == 0) {
1582                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
1583                                    "OK");
1584                         ok = 1;
1585                         break;
1586                 }
1587
1588                 break;
1589         }
1590
1591         while (!ok && private_key) {
1592 #ifndef OPENSSL_NO_STDIO
1593                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1594                                             SSL_FILETYPE_ASN1) == 1) {
1595                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1596                                    "SSL_use_PrivateKey_File (DER) --> OK");
1597                         ok = 1;
1598                         break;
1599                 } else {
1600                         tls_show_errors(MSG_DEBUG, __func__,
1601                                         "SSL_use_PrivateKey_File (DER) "
1602                                         "failed");
1603                 }
1604
1605                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
1606                                             SSL_FILETYPE_PEM) == 1) {
1607                         wpa_printf(MSG_DEBUG, "OpenSSL: "
1608                                    "SSL_use_PrivateKey_File (PEM) --> OK");
1609                         ok = 1;
1610                         break;
1611                 } else {
1612                         tls_show_errors(MSG_DEBUG, __func__,
1613                                         "SSL_use_PrivateKey_File (PEM) "
1614                                         "failed");
1615                 }
1616 #else /* OPENSSL_NO_STDIO */
1617                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
1618                            __func__);
1619 #endif /* OPENSSL_NO_STDIO */
1620
1621                 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
1622                     == 0) {
1623                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
1624                                    "--> OK");
1625                         ok = 1;
1626                         break;
1627                 }
1628
1629                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
1630                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
1631                                    "access certificate store --> OK");
1632                         ok = 1;
1633                         break;
1634                 }
1635
1636                 break;
1637         }
1638
1639         if (!ok) {
1640                 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
1641                 os_free(passwd);
1642                 ERR_clear_error();
1643                 return -1;
1644         }
1645         ERR_clear_error();
1646         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1647         os_free(passwd);
1648         
1649         if (!SSL_check_private_key(conn->ssl)) {
1650                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
1651                                 "verification");
1652                 return -1;
1653         }
1654
1655         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
1656         return 0;
1657 }
1658
1659
1660 static int tls_global_private_key(SSL_CTX *ssl_ctx, const char *private_key,
1661                                   const char *private_key_passwd)
1662 {
1663         char *passwd;
1664
1665         if (private_key == NULL)
1666                 return 0;
1667
1668         if (private_key_passwd) {
1669                 passwd = os_strdup(private_key_passwd);
1670                 if (passwd == NULL)
1671                         return -1;
1672         } else
1673                 passwd = NULL;
1674
1675         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
1676         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
1677         if (
1678 #ifndef OPENSSL_NO_STDIO
1679             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1680                                         SSL_FILETYPE_ASN1) != 1 &&
1681             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
1682                                         SSL_FILETYPE_PEM) != 1 &&
1683 #endif /* OPENSSL_NO_STDIO */
1684             tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
1685                 tls_show_errors(MSG_INFO, __func__,
1686                                 "Failed to load private key");
1687                 os_free(passwd);
1688                 ERR_clear_error();
1689                 return -1;
1690         }
1691         os_free(passwd);
1692         ERR_clear_error();
1693         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
1694         
1695         if (!SSL_CTX_check_private_key(ssl_ctx)) {
1696                 tls_show_errors(MSG_INFO, __func__,
1697                                 "Private key failed verification");
1698                 return -1;
1699         }
1700
1701         return 0;
1702 }
1703
1704
1705 static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
1706 {
1707 #ifdef OPENSSL_NO_DH
1708         if (dh_file == NULL)
1709                 return 0;
1710         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1711                    "dh_file specified");
1712         return -1;
1713 #else /* OPENSSL_NO_DH */
1714         DH *dh;
1715         BIO *bio;
1716
1717         /* TODO: add support for dh_blob */
1718         if (dh_file == NULL)
1719                 return 0;
1720         if (conn == NULL)
1721                 return -1;
1722
1723         bio = BIO_new_file(dh_file, "r");
1724         if (bio == NULL) {
1725                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1726                            dh_file, ERR_error_string(ERR_get_error(), NULL));
1727                 return -1;
1728         }
1729         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1730         BIO_free(bio);
1731 #ifndef OPENSSL_NO_DSA
1732         while (dh == NULL) {
1733                 DSA *dsa;
1734                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1735                            " trying to parse as DSA params", dh_file,
1736                            ERR_error_string(ERR_get_error(), NULL));
1737                 bio = BIO_new_file(dh_file, "r");
1738                 if (bio == NULL)
1739                         break;
1740                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1741                 BIO_free(bio);
1742                 if (!dsa) {
1743                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1744                                    "'%s': %s", dh_file,
1745                                    ERR_error_string(ERR_get_error(), NULL));
1746                         break;
1747                 }
1748
1749                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1750                 dh = DSA_dup_DH(dsa);
1751                 DSA_free(dsa);
1752                 if (dh == NULL) {
1753                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1754                                    "params into DH params");
1755                         break;
1756                 }
1757                 break;
1758         }
1759 #endif /* !OPENSSL_NO_DSA */
1760         if (dh == NULL) {
1761                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1762                            "'%s'", dh_file);
1763                 return -1;
1764         }
1765
1766         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
1767                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1768                            "%s", dh_file,
1769                            ERR_error_string(ERR_get_error(), NULL));
1770                 DH_free(dh);
1771                 return -1;
1772         }
1773         DH_free(dh);
1774         return 0;
1775 #endif /* OPENSSL_NO_DH */
1776 }
1777
1778
1779 static int tls_global_dh(SSL_CTX *ssl_ctx, const char *dh_file)
1780 {
1781 #ifdef OPENSSL_NO_DH
1782         if (dh_file == NULL)
1783                 return 0;
1784         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
1785                    "dh_file specified");
1786         return -1;
1787 #else /* OPENSSL_NO_DH */
1788         DH *dh;
1789         BIO *bio;
1790
1791         /* TODO: add support for dh_blob */
1792         if (dh_file == NULL)
1793                 return 0;
1794         if (ssl_ctx == NULL)
1795                 return -1;
1796
1797         bio = BIO_new_file(dh_file, "r");
1798         if (bio == NULL) {
1799                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
1800                            dh_file, ERR_error_string(ERR_get_error(), NULL));
1801                 return -1;
1802         }
1803         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1804         BIO_free(bio);
1805 #ifndef OPENSSL_NO_DSA
1806         while (dh == NULL) {
1807                 DSA *dsa;
1808                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
1809                            " trying to parse as DSA params", dh_file,
1810                            ERR_error_string(ERR_get_error(), NULL));
1811                 bio = BIO_new_file(dh_file, "r");
1812                 if (bio == NULL)
1813                         break;
1814                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
1815                 BIO_free(bio);
1816                 if (!dsa) {
1817                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
1818                                    "'%s': %s", dh_file,
1819                                    ERR_error_string(ERR_get_error(), NULL));
1820                         break;
1821                 }
1822
1823                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
1824                 dh = DSA_dup_DH(dsa);
1825                 DSA_free(dsa);
1826                 if (dh == NULL) {
1827                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
1828                                    "params into DH params");
1829                         break;
1830                 }
1831                 break;
1832         }
1833 #endif /* !OPENSSL_NO_DSA */
1834         if (dh == NULL) {
1835                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
1836                            "'%s'", dh_file);
1837                 return -1;
1838         }
1839
1840         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
1841                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
1842                            "%s", dh_file,
1843                            ERR_error_string(ERR_get_error(), NULL));
1844                 DH_free(dh);
1845                 return -1;
1846         }
1847         DH_free(dh);
1848         return 0;
1849 #endif /* OPENSSL_NO_DH */
1850 }
1851
1852
1853 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
1854                             struct tls_keys *keys)
1855 {
1856         SSL *ssl;
1857
1858         if (conn == NULL || keys == NULL)
1859                 return -1;
1860         ssl = conn->ssl;
1861         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
1862                 return -1;
1863
1864         os_memset(keys, 0, sizeof(*keys));
1865         keys->master_key = ssl->session->master_key;
1866         keys->master_key_len = ssl->session->master_key_length;
1867         keys->client_random = ssl->s3->client_random;
1868         keys->client_random_len = SSL3_RANDOM_SIZE;
1869         keys->server_random = ssl->s3->server_random;
1870         keys->server_random_len = SSL3_RANDOM_SIZE;
1871
1872         return 0;
1873 }
1874
1875
1876 int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
1877                        const char *label, int server_random_first,
1878                        u8 *out, size_t out_len)
1879 {
1880         return -1;
1881 }
1882
1883
1884 u8 * tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
1885                               const u8 *in_data, size_t in_len,
1886                               size_t *out_len, u8 **appl_data,
1887                               size_t *appl_data_len)
1888 {
1889         int res;
1890         u8 *out_data;
1891
1892         if (appl_data)
1893                 *appl_data = NULL;
1894
1895         /*
1896          * Give TLS handshake data from the server (if available) to OpenSSL
1897          * for processing.
1898          */
1899         if (in_data &&
1900             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
1901                 tls_show_errors(MSG_INFO, __func__,
1902                                 "Handshake failed - BIO_write");
1903                 return NULL;
1904         }
1905
1906         /* Initiate TLS handshake or continue the existing handshake */
1907         res = SSL_connect(conn->ssl);
1908         if (res != 1) {
1909                 int err = SSL_get_error(conn->ssl, res);
1910                 if (err == SSL_ERROR_WANT_READ)
1911                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
1912                                    "more data");
1913                 else if (err == SSL_ERROR_WANT_WRITE)
1914                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
1915                                    "write");
1916                 else {
1917                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
1918                         conn->failed++;
1919                 }
1920         }
1921
1922         /* Get the TLS handshake data to be sent to the server */
1923         res = BIO_ctrl_pending(conn->ssl_out);
1924         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
1925         out_data = os_malloc(res == 0 ? 1 : res);
1926         if (out_data == NULL) {
1927                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
1928                            "handshake output (%d bytes)", res);
1929                 if (BIO_reset(conn->ssl_out) < 0) {
1930                         tls_show_errors(MSG_INFO, __func__,
1931                                         "BIO_reset failed");
1932                 }
1933                 *out_len = 0;
1934                 return NULL;
1935         }
1936         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
1937         if (res < 0) {
1938                 tls_show_errors(MSG_INFO, __func__,
1939                                 "Handshake failed - BIO_read");
1940                 if (BIO_reset(conn->ssl_out) < 0) {
1941                         tls_show_errors(MSG_INFO, __func__,
1942                                         "BIO_reset failed");
1943                 }
1944                 *out_len = 0;
1945                 return NULL;
1946         }
1947         *out_len = res;
1948
1949         if (SSL_is_init_finished(conn->ssl) && appl_data) {
1950                 *appl_data = os_malloc(in_len);
1951                 if (*appl_data) {
1952                         res = SSL_read(conn->ssl, *appl_data, in_len);
1953                         if (res < 0) {
1954                                 tls_show_errors(MSG_INFO, __func__,
1955                                                 "Failed to read possible "
1956                                                 "Application Data");
1957                                 os_free(*appl_data);
1958                                 *appl_data = NULL;
1959                         } else {
1960                                 *appl_data_len = res;
1961                                 wpa_hexdump_key(MSG_MSGDUMP, "SSL: Application"
1962                                                 " Data in Finish message",
1963                                                 *appl_data, *appl_data_len);
1964                         }
1965                 }
1966         }
1967
1968         return out_data;
1969 }
1970
1971
1972 u8 * tls_connection_server_handshake(void *ssl_ctx,
1973                                      struct tls_connection *conn,
1974                                      const u8 *in_data, size_t in_len,
1975                                      size_t *out_len)
1976 {
1977         int res;
1978         u8 *out_data;
1979         char buf[10];
1980
1981         if (in_data &&
1982             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
1983                 tls_show_errors(MSG_INFO, __func__,
1984                                 "Handshake failed - BIO_write");
1985                 return NULL;
1986         }
1987
1988         res = SSL_read(conn->ssl, buf, sizeof(buf));
1989         if (res >= 0) {
1990                 wpa_printf(MSG_DEBUG, "SSL: Unexpected data from SSL_read "
1991                            "(res=%d)", res);
1992         }
1993
1994         res = BIO_ctrl_pending(conn->ssl_out);
1995         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
1996         out_data = os_malloc(res == 0 ? 1 : res);
1997         if (out_data == NULL) {
1998                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
1999                            "handshake output (%d bytes)", res);
2000                 if (BIO_reset(conn->ssl_out) < 0) {
2001                         tls_show_errors(MSG_INFO, __func__,
2002                                         "BIO_reset failed");
2003                 }
2004                 *out_len = 0;
2005                 return NULL;
2006         }
2007         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
2008         if (res < 0) {
2009                 tls_show_errors(MSG_INFO, __func__,
2010                                 "Handshake failed - BIO_read");
2011                 if (BIO_reset(conn->ssl_out) < 0) {
2012                         tls_show_errors(MSG_INFO, __func__,
2013                                         "BIO_reset failed");
2014                 }
2015                 *out_len = 0;
2016                 return NULL;
2017         }
2018         *out_len = res;
2019         return out_data;
2020 }
2021
2022
2023 int tls_connection_encrypt(void *ssl_ctx, struct tls_connection *conn,
2024                            const u8 *in_data, size_t in_len,
2025                            u8 *out_data, size_t out_len)
2026 {
2027         int res;
2028
2029         if (conn == NULL)
2030                 return -1;
2031
2032         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
2033         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
2034             (res = BIO_reset(conn->ssl_out)) < 0) {
2035                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2036                 return res;
2037         }
2038         res = SSL_write(conn->ssl, in_data, in_len);
2039         if (res < 0) {
2040                 tls_show_errors(MSG_INFO, __func__,
2041                                 "Encryption failed - SSL_write");
2042                 return res;
2043         }
2044
2045         /* Read encrypted data to be sent to the server */
2046         res = BIO_read(conn->ssl_out, out_data, out_len);
2047         if (res < 0) {
2048                 tls_show_errors(MSG_INFO, __func__,
2049                                 "Encryption failed - BIO_read");
2050                 return res;
2051         }
2052
2053         return res;
2054 }
2055
2056
2057 int tls_connection_decrypt(void *ssl_ctx, struct tls_connection *conn,
2058                            const u8 *in_data, size_t in_len,
2059                            u8 *out_data, size_t out_len)
2060 {
2061         int res;
2062
2063         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
2064         res = BIO_write(conn->ssl_in, in_data, in_len);
2065         if (res < 0) {
2066                 tls_show_errors(MSG_INFO, __func__,
2067                                 "Decryption failed - BIO_write");
2068                 return res;
2069         }
2070         if (BIO_reset(conn->ssl_out) < 0) {
2071                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
2072                 return res;
2073         }
2074
2075         /* Read decrypted data for further processing */
2076         res = SSL_read(conn->ssl, out_data, out_len);
2077         if (res < 0) {
2078                 tls_show_errors(MSG_INFO, __func__,
2079                                 "Decryption failed - SSL_read");
2080                 return res;
2081         }
2082
2083         return res;
2084 }
2085
2086
2087 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
2088 {
2089         return conn ? conn->ssl->hit : 0;
2090 }
2091
2092
2093 int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
2094                                    u8 *ciphers)
2095 {
2096         char buf[100], *pos, *end;
2097         u8 *c;
2098         int ret;
2099
2100         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
2101                 return -1;
2102
2103         buf[0] = '\0';
2104         pos = buf;
2105         end = pos + sizeof(buf);
2106
2107         c = ciphers;
2108         while (*c != TLS_CIPHER_NONE) {
2109                 const char *suite;
2110
2111                 switch (*c) {
2112                 case TLS_CIPHER_RC4_SHA:
2113                         suite = "RC4-SHA";
2114                         break;
2115                 case TLS_CIPHER_AES128_SHA:
2116                         suite = "AES128-SHA";
2117                         break;
2118                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
2119                         suite = "DHE-RSA-AES128-SHA";
2120                         break;
2121                 case TLS_CIPHER_ANON_DH_AES128_SHA:
2122                         suite = "ADH-AES128-SHA";
2123                         break;
2124                 default:
2125                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
2126                                    "cipher selection: %d", *c);
2127                         return -1;
2128                 }
2129                 ret = os_snprintf(pos, end - pos, ":%s", suite);
2130                 if (ret < 0 || ret >= end - pos)
2131                         break;
2132                 pos += ret;
2133
2134                 c++;
2135         }
2136
2137         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
2138
2139         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
2140                 tls_show_errors(MSG_INFO, __func__,
2141                                 "Cipher suite configuration failed");
2142                 return -1;
2143         }
2144
2145         return 0;
2146 }
2147
2148
2149 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
2150                    char *buf, size_t buflen)
2151 {
2152         const char *name;
2153         if (conn == NULL || conn->ssl == NULL)
2154                 return -1;
2155
2156         name = SSL_get_cipher(conn->ssl);
2157         if (name == NULL)
2158                 return -1;
2159
2160         os_strlcpy(buf, name, buflen);
2161         return 0;
2162 }
2163
2164
2165 int tls_connection_enable_workaround(void *ssl_ctx,
2166                                      struct tls_connection *conn)
2167 {
2168         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
2169
2170         return 0;
2171 }
2172
2173
2174 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2175 /* ClientHello TLS extensions require a patch to openssl, so this function is
2176  * commented out unless explicitly needed for EAP-FAST in order to be able to
2177  * build this file with unmodified openssl. */
2178 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
2179                                     int ext_type, const u8 *data,
2180                                     size_t data_len)
2181 {
2182         if (conn == NULL || conn->ssl == NULL)
2183                 return -1;
2184
2185         if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
2186                                     data_len) != 1)
2187                 return -1;
2188
2189         return 0;
2190 }
2191 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2192
2193
2194 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
2195 {
2196         if (conn == NULL)
2197                 return -1;
2198         return conn->failed;
2199 }
2200
2201
2202 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
2203 {
2204         if (conn == NULL)
2205                 return -1;
2206         return conn->read_alerts;
2207 }
2208
2209
2210 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
2211 {
2212         if (conn == NULL)
2213                 return -1;
2214         return conn->write_alerts;
2215 }
2216
2217
2218 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
2219                               const struct tls_connection_params *params)
2220 {
2221         int ret;
2222         unsigned long err;
2223
2224         if (conn == NULL)
2225                 return -1;
2226
2227         while ((err = ERR_get_error())) {
2228                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2229                            __func__, ERR_error_string(err, NULL));
2230         }
2231
2232         if (tls_connection_set_subject_match(conn,
2233                                              params->subject_match,
2234                                              params->altsubject_match))
2235                 return -1;
2236         if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
2237                                    params->ca_cert_blob,
2238                                    params->ca_cert_blob_len,
2239                                    params->ca_path))
2240                 return -1;
2241         if (tls_connection_client_cert(conn, params->client_cert,
2242                                        params->client_cert_blob,
2243                                        params->client_cert_blob_len))
2244                 return -1;
2245
2246         if (params->engine) {
2247                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
2248                 ret = tls_engine_init(conn, params->engine_id, params->pin,
2249                                       params->key_id);
2250                 if (ret)
2251                         return ret;
2252                 if (tls_connection_engine_private_key(conn))
2253                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
2254         } else if (tls_connection_private_key(tls_ctx, conn,
2255                                               params->private_key,
2256                                               params->private_key_passwd,
2257                                               params->private_key_blob,
2258                                               params->private_key_blob_len)) {
2259                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
2260                            params->private_key);
2261                 return -1;
2262         }
2263
2264         if (tls_connection_dh(conn, params->dh_file)) {
2265                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2266                            params->dh_file);
2267                 return -1;
2268         }
2269
2270         tls_get_errors(tls_ctx);
2271
2272         return 0;
2273 }
2274
2275
2276 int tls_global_set_params(void *tls_ctx,
2277                           const struct tls_connection_params *params)
2278 {
2279         SSL_CTX *ssl_ctx = tls_ctx;
2280         unsigned long err;
2281
2282         while ((err = ERR_get_error())) {
2283                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
2284                            __func__, ERR_error_string(err, NULL));
2285         }
2286
2287         if (tls_global_ca_cert(ssl_ctx, params->ca_cert))
2288                 return -1;
2289
2290         if (tls_global_client_cert(ssl_ctx, params->client_cert))
2291                 return -1;
2292
2293         if (tls_global_private_key(ssl_ctx, params->private_key,
2294                                    params->private_key_passwd))
2295                 return -1;
2296
2297         if (tls_global_dh(ssl_ctx, params->dh_file)) {
2298                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
2299                            params->dh_file);
2300                 return -1;
2301         }
2302
2303         return 0;
2304 }
2305
2306
2307 int tls_connection_get_keyblock_size(void *tls_ctx,
2308                                      struct tls_connection *conn)
2309 {
2310         const EVP_CIPHER *c;
2311         const EVP_MD *h;
2312
2313         if (conn == NULL || conn->ssl == NULL ||
2314             conn->ssl->enc_read_ctx == NULL ||
2315             conn->ssl->enc_read_ctx->cipher == NULL ||
2316             conn->ssl->read_hash == NULL)
2317                 return -1;
2318
2319         c = conn->ssl->enc_read_ctx->cipher;
2320 #if OPENSSL_VERSION_NUMBER >= 0x00909000L
2321         h = EVP_MD_CTX_md(conn->ssl->read_hash);
2322 #else
2323         h = conn->ssl->read_hash;
2324 #endif
2325
2326         return 2 * (EVP_CIPHER_key_length(c) +
2327                     EVP_MD_size(h) +
2328                     EVP_CIPHER_iv_length(c));
2329 }
2330
2331
2332 unsigned int tls_capabilities(void *tls_ctx)
2333 {
2334         return 0;
2335 }
2336
2337
2338 int tls_connection_set_ia(void *tls_ctx, struct tls_connection *conn,
2339                           int tls_ia)
2340 {
2341         return -1;
2342 }
2343
2344
2345 int tls_connection_ia_send_phase_finished(void *tls_ctx,
2346                                           struct tls_connection *conn,
2347                                           int final,
2348                                           u8 *out_data, size_t out_len)
2349 {
2350         return -1;
2351 }
2352
2353
2354 int tls_connection_ia_final_phase_finished(void *tls_ctx,
2355                                            struct tls_connection *conn)
2356 {
2357         return -1;
2358 }
2359
2360
2361 int tls_connection_ia_permute_inner_secret(void *tls_ctx,
2362                                            struct tls_connection *conn,
2363                                            const u8 *key, size_t key_len)
2364 {
2365         return -1;
2366 }
2367
2368
2369 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2370 /* Pre-shared secred requires a patch to openssl, so this function is
2371  * commented out unless explicitly needed for EAP-FAST in order to be able to
2372  * build this file with unmodified openssl. */
2373
2374 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
2375                            STACK_OF(SSL_CIPHER) *peer_ciphers,
2376                            SSL_CIPHER **cipher, void *arg)
2377 {
2378         struct tls_connection *conn = arg;
2379         int ret;
2380
2381         if (conn == NULL || conn->session_ticket_cb == NULL)
2382                 return 0;
2383
2384         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
2385                                       conn->session_ticket,
2386                                       conn->session_ticket_len,
2387                                       s->s3->client_random,
2388                                       s->s3->server_random, secret);
2389         os_free(conn->session_ticket);
2390         conn->session_ticket = NULL;
2391
2392         if (ret <= 0)
2393                 return 0;
2394
2395         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
2396         return 1;
2397 }
2398
2399
2400 #ifdef SSL_OP_NO_TICKET
2401 static void tls_hello_ext_cb(SSL *s, int client_server, int type,
2402                              unsigned char *data, int len, void *arg)
2403 {
2404         struct tls_connection *conn = arg;
2405
2406         if (conn == NULL || conn->session_ticket_cb == NULL)
2407                 return;
2408
2409         wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2410                    type, len);
2411
2412         if (type == TLSEXT_TYPE_session_ticket && !client_server) {
2413                 os_free(conn->session_ticket);
2414                 conn->session_ticket = NULL;
2415
2416                 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2417                             "extension", data, len);
2418                 conn->session_ticket = os_malloc(len);
2419                 if (conn->session_ticket == NULL)
2420                         return;
2421
2422                 os_memcpy(conn->session_ticket, data, len);
2423                 conn->session_ticket_len = len;
2424         }
2425 }
2426 #else /* SSL_OP_NO_TICKET */
2427 static int tls_hello_ext_cb(SSL *s, TLS_EXTENSION *ext, void *arg)
2428 {
2429         struct tls_connection *conn = arg;
2430
2431         if (conn == NULL || conn->session_ticket_cb == NULL)
2432                 return 0;
2433
2434         wpa_printf(MSG_DEBUG, "OpenSSL: %s: type=%d length=%d", __func__,
2435                    ext->type, ext->length);
2436
2437         os_free(conn->session_ticket);
2438         conn->session_ticket = NULL;
2439
2440         if (ext->type == 35) {
2441                 wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
2442                             "extension", ext->data, ext->length);
2443                 conn->session_ticket = os_malloc(ext->length);
2444                 if (conn->session_ticket == NULL)
2445                         return SSL_AD_INTERNAL_ERROR;
2446
2447                 os_memcpy(conn->session_ticket, ext->data, ext->length);
2448                 conn->session_ticket_len = ext->length;
2449         }
2450
2451         return 0;
2452 }
2453 #endif /* SSL_OP_NO_TICKET */
2454 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2455
2456
2457 int tls_connection_set_session_ticket_cb(void *tls_ctx,
2458                                          struct tls_connection *conn,
2459                                          tls_session_ticket_cb cb,
2460                                          void *ctx)
2461 {
2462 #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC)
2463         conn->session_ticket_cb = cb;
2464         conn->session_ticket_cb_ctx = ctx;
2465
2466         if (cb) {
2467                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
2468                                               conn) != 1)
2469                         return -1;
2470 #ifdef SSL_OP_NO_TICKET
2471                 SSL_set_tlsext_debug_callback(conn->ssl, tls_hello_ext_cb);
2472                 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2473 #else /* SSL_OP_NO_TICKET */
2474                 if (SSL_set_hello_extension_cb(conn->ssl, tls_hello_ext_cb,
2475                                                conn) != 1)
2476                         return -1;
2477 #endif /* SSL_OP_NO_TICKET */
2478         } else {
2479                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
2480                         return -1;
2481 #ifdef SSL_OP_NO_TICKET
2482                 SSL_set_tlsext_debug_callback(conn->ssl, NULL);
2483                 SSL_set_tlsext_debug_arg(conn->ssl, conn);
2484 #else /* SSL_OP_NO_TICKET */
2485                 if (SSL_set_hello_extension_cb(conn->ssl, NULL, NULL) != 1)
2486                         return -1;
2487 #endif /* SSL_OP_NO_TICKET */
2488         }
2489
2490         return 0;
2491 #else /* EAP_FAST || EAP_FAST_DYNAMIC */
2492         return -1;
2493 #endif /* EAP_FAST || EAP_FAST_DYNAMIC */
2494 }