OSDN Git Service

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