tls_openssl.c

Go to the documentation of this file.
00001 
00016 #include <stdlib.h>
00017 #include <stdio.h>
00018 #include <string.h>
00019 
00020 #ifndef CONFIG_SMARTCARD
00021 #ifndef OPENSSL_NO_ENGINE
00022 #define OPENSSL_NO_ENGINE
00023 #endif
00024 #endif
00025 
00026 #include <openssl/ssl.h>
00027 #include <openssl/err.h>
00028 #include <openssl/pkcs12.h>
00029 #include <openssl/x509v3.h>
00030 #ifndef OPENSSL_NO_ENGINE
00031 #include <openssl/engine.h>
00032 #endif /* OPENSSL_NO_ENGINE */
00033 
00034 #include "common.h"
00035 #include "tls.h"
00036 
00037 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
00038 #define OPENSSL_d2i_TYPE const unsigned char **
00039 #else
00040 #define OPENSSL_d2i_TYPE unsigned char **
00041 #endif
00042 
00043 static int tls_openssl_ref_count = 0;
00044 
00045 struct tls_connection {
00046         SSL *ssl;
00047         BIO *ssl_in, *ssl_out;
00048 #ifndef OPENSSL_NO_ENGINE
00049         ENGINE *engine;        /* functional reference to the engine */
00050         EVP_PKEY *private_key; /* the private key if using engine */
00051 #endif /* OPENSSL_NO_ENGINE */
00052         char *subject_match, *altsubject_match;
00053         int read_alerts, write_alerts, failed;
00054 
00055         u8 *pre_shared_secret;
00056         size_t pre_shared_secret_len;
00057 };
00058 
00059 
00060 #ifdef CONFIG_NO_STDOUT_DEBUG
00061 
00062 static void _tls_show_errors(void)
00063 {
00064         unsigned long err;
00065 
00066         while ((err = ERR_get_error())) {
00067                 /* Just ignore the errors, since stdout is disabled */
00068         }
00069 }
00070 #define tls_show_errors(l, f, t) _tls_show_errors()
00071 
00072 #else /* CONFIG_NO_STDOUT_DEBUG */
00073 
00074 static void tls_show_errors(int level, const char *func, const char *txt)
00075 {
00076         unsigned long err;
00077 
00078         wpa_printf(level, "OpenSSL: %s - %s %s",
00079                    func, txt, ERR_error_string(ERR_get_error(), NULL));
00080 
00081         while ((err = ERR_get_error())) {
00082                 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
00083                            ERR_error_string(err, NULL));
00084         }
00085 }
00086 
00087 #endif /* CONFIG_NO_STDOUT_DEBUG */
00088 
00089 
00090 #ifdef CONFIG_NATIVE_WINDOWS
00091 
00092 /* Windows CryptoAPI and access to certificate stores */
00093 #include <wincrypt.h>
00094 
00095 #ifdef __MINGW32_VERSION
00096 /*
00097  * MinGW does not yet include all the needed definitions for CryptoAPI, so
00098  * define here whatever extra is needed.
00099  */
00100 #define CALG_SSL3_SHAMD5 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SSL3SHAMD5)
00101 #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
00102 #define CERT_STORE_READONLY_FLAG 0x00008000
00103 #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
00104 #define CRYPT_ACQUIRE_COMPARE_KEY_FLAG 0x00000004
00105 
00106 static BOOL WINAPI
00107 (*CryptAcquireCertificatePrivateKey)(PCCERT_CONTEXT pCert, DWORD dwFlags,
00108                                      void *pvReserved, HCRYPTPROV *phCryptProv,
00109                                      DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
00110 = NULL; /* to be loaded from crypt32.dll */
00111 
00112 static PCCERT_CONTEXT WINAPI
00113 (*CertEnumCertificatesInStore)(HCERTSTORE hCertStore,
00114                                PCCERT_CONTEXT pPrevCertContext)
00115 = NULL; /* to be loaded from crypt32.dll */
00116 
00117 static int mingw_load_crypto_func(void)
00118 {
00119         HINSTANCE dll;
00120 
00121         /* MinGW does not yet have full CryptoAPI support, so load the needed
00122          * function here. */
00123 
00124         if (CryptAcquireCertificatePrivateKey)
00125                 return 0;
00126 
00127         dll = LoadLibrary("crypt32");
00128         if (dll == NULL) {
00129                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not load crypt32 "
00130                            "library");
00131                 return -1;
00132         }
00133 
00134         CryptAcquireCertificatePrivateKey = GetProcAddress(
00135                 dll, "CryptAcquireCertificatePrivateKey");
00136         if (CryptAcquireCertificatePrivateKey == NULL) {
00137                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
00138                            "CryptAcquireCertificatePrivateKey() address from "
00139                            "crypt32 library");
00140                 return -1;
00141         }
00142 
00143         CertEnumCertificatesInStore = (void *) GetProcAddress(
00144                 dll, "CertEnumCertificatesInStore");
00145         if (CertEnumCertificatesInStore == NULL) {
00146                 wpa_printf(MSG_DEBUG, "CryptoAPI: Could not get "
00147                            "CertEnumCertificatesInStore() address from "
00148                            "crypt32 library");
00149                 return -1;
00150         }
00151 
00152         return 0;
00153 }
00154 
00155 #else /* __MINGW32_VERSION */
00156 
00157 static int mingw_load_crypto_func(void)
00158 {
00159         return 0;
00160 }
00161 
00162 #endif /* __MINGW32_VERSION */
00163 
00164 
00165 struct cryptoapi_rsa_data {
00166         const CERT_CONTEXT *cert;
00167         HCRYPTPROV crypt_prov;
00168         DWORD key_spec;
00169         BOOL free_crypt_prov;
00170 };
00171 
00172 
00173 static void cryptoapi_error(const char *msg)
00174 {
00175         wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
00176                    msg, (unsigned int) GetLastError());
00177 }
00178 
00179 
00180 static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
00181                                  unsigned char *to, RSA *rsa, int padding)
00182 {
00183         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
00184         return 0;
00185 }
00186 
00187 
00188 static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
00189                                  unsigned char *to, RSA *rsa, int padding)
00190 {
00191         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
00192         return 0;
00193 }
00194 
00195 
00196 static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
00197                                   unsigned char *to, RSA *rsa, int padding)
00198 {
00199         struct cryptoapi_rsa_data *priv =
00200                 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
00201         HCRYPTHASH hash;
00202         DWORD hash_size, len, i;
00203         unsigned char *buf = NULL;
00204         int ret = 0;
00205 
00206         if (priv == NULL) {
00207                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
00208                        ERR_R_PASSED_NULL_PARAMETER);
00209                 return 0;
00210         }
00211 
00212         if (padding != RSA_PKCS1_PADDING) {
00213                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
00214                        RSA_R_UNKNOWN_PADDING_TYPE);
00215                 return 0;
00216         }
00217 
00218         if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
00219                 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
00220                            __func__);
00221                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
00222                        RSA_R_INVALID_MESSAGE_LENGTH);
00223                 return 0;
00224         }
00225 
00226         if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
00227         {
00228                 cryptoapi_error("CryptCreateHash failed");
00229                 return 0;
00230         }
00231 
00232         len = sizeof(hash_size);
00233         if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
00234                                0)) {
00235                 cryptoapi_error("CryptGetHashParam failed");
00236                 goto err;
00237         }
00238 
00239         if (hash_size != flen) {
00240                 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
00241                            (unsigned) hash_size, flen);
00242                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
00243                        RSA_R_INVALID_MESSAGE_LENGTH);
00244                 goto err;
00245         }
00246         if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
00247                 cryptoapi_error("CryptSetHashParam failed");
00248                 goto err;
00249         }
00250 
00251         len = RSA_size(rsa);
00252         buf = malloc(len);
00253         if (buf == NULL) {
00254                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
00255                 goto err;
00256         }
00257 
00258         if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
00259                 cryptoapi_error("CryptSignHash failed");
00260                 goto err;
00261         }
00262 
00263         for (i = 0; i < len; i++)
00264                 to[i] = buf[len - i - 1];
00265         ret = len;
00266 
00267 err:
00268         free(buf);
00269         CryptDestroyHash(hash);
00270 
00271         return ret;
00272 }
00273 
00274 
00275 static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
00276                                   unsigned char *to, RSA *rsa, int padding)
00277 {
00278         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
00279         return 0;
00280 }
00281 
00282 
00283 static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
00284 {
00285         if (priv == NULL)
00286                 return;
00287         if (priv->crypt_prov && priv->free_crypt_prov)
00288                 CryptReleaseContext(priv->crypt_prov, 0);
00289         if (priv->cert)
00290                 CertFreeCertificateContext(priv->cert);
00291         free(priv);
00292 }
00293 
00294 
00295 static int cryptoapi_finish(RSA *rsa)
00296 {
00297         cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
00298         free((void *) rsa->meth);
00299         rsa->meth = NULL;
00300         return 1;
00301 }
00302 
00303 
00304 static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
00305 {
00306         HCERTSTORE cs;
00307         const CERT_CONTEXT *ret = NULL;
00308 
00309         cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
00310                            store | CERT_STORE_OPEN_EXISTING_FLAG |
00311                            CERT_STORE_READONLY_FLAG, L"MY");
00312         if (cs == NULL) {
00313                 cryptoapi_error("Failed to open 'My system store'");
00314                 return NULL;
00315         }
00316 
00317         if (strncmp(name, "cert://", 7) == 0) {
00318                 unsigned short wbuf[255];
00319                 MultiByteToWideChar(CP_ACP, 0, name + 7, -1,
00320                                     wbuf, sizeof(wbuf));
00321                 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
00322                                                  PKCS_7_ASN_ENCODING,
00323                                                  0, CERT_FIND_SUBJECT_STR,
00324                                                  wbuf, NULL);
00325         } else if (strncmp(name, "hash://", 7) == 0) {
00326                 CRYPT_HASH_BLOB blob;
00327                 int len;
00328                 const char *hash = name + 7;
00329                 unsigned char *buf;
00330 
00331                 len = strlen(hash) / 2;
00332                 buf = malloc(len);
00333                 if (buf && hexstr2bin(hash, buf, len) == 0) {
00334                         blob.cbData = len;
00335                         blob.pbData = buf;
00336                         ret = CertFindCertificateInStore(cs,
00337                                                          X509_ASN_ENCODING |
00338                                                          PKCS_7_ASN_ENCODING,
00339                                                          0, CERT_FIND_HASH,
00340                                                          &blob, NULL);
00341                 }
00342                 free(buf);
00343         }
00344 
00345         CertCloseStore(cs, 0);
00346 
00347         return ret;
00348 }
00349 
00350 
00351 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
00352 {
00353         X509 *cert = NULL;
00354         RSA *rsa = NULL, *pub_rsa;
00355         struct cryptoapi_rsa_data *priv;
00356         RSA_METHOD *rsa_meth;
00357 
00358         if (name == NULL ||
00359             (strncmp(name, "cert://", 7) != 0 &&
00360              strncmp(name, "hash://", 7) != 0))
00361                 return -1;
00362 
00363         priv = malloc(sizeof(*priv));
00364         rsa_meth = malloc(sizeof(*rsa_meth));
00365         if (priv == NULL || rsa_meth == NULL) {
00366                 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
00367                            "for CryptoAPI RSA method");
00368                 free(priv);
00369                 free(rsa_meth);
00370                 return -1;
00371         }
00372         memset(priv, 0, sizeof(*priv));
00373         memset(rsa_meth, 0, sizeof(*rsa_meth));
00374 
00375         priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
00376         if (priv->cert == NULL) {
00377                 priv->cert = cryptoapi_find_cert(
00378                         name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
00379         }
00380         if (priv->cert == NULL) {
00381                 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
00382                            "'%s'", name);
00383                 goto err;
00384         }
00385 
00386         cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &priv->cert->pbCertEncoded,
00387                         priv->cert->cbCertEncoded);
00388         if (cert == NULL) {
00389                 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
00390                            "encoding");
00391                 goto err;
00392         }
00393 
00394         if (mingw_load_crypto_func())
00395                 goto err;
00396 
00397         if (!CryptAcquireCertificatePrivateKey(priv->cert,
00398                                                CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
00399                                                NULL, &priv->crypt_prov,
00400                                                &priv->key_spec,
00401                                                &priv->free_crypt_prov)) {
00402                 cryptoapi_error("Failed to acquire a private key for the "
00403                                 "certificate");
00404                 goto err;
00405         }
00406 
00407         rsa_meth->name = "Microsoft CryptoAPI RSA Method";
00408         rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
00409         rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
00410         rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
00411         rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
00412         rsa_meth->finish = cryptoapi_finish;
00413         rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
00414         rsa_meth->app_data = (char *) priv;
00415 
00416         rsa = RSA_new();
00417         if (rsa == NULL) {
00418                 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
00419                        ERR_R_MALLOC_FAILURE);
00420                 goto err;
00421         }
00422 
00423         if (!SSL_use_certificate(ssl, cert))
00424                 goto err;
00425         pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
00426         X509_free(cert);
00427         cert = NULL;
00428 
00429         rsa->n = BN_dup(pub_rsa->n);
00430         rsa->e = BN_dup(pub_rsa->e);
00431         if (!RSA_set_method(rsa, rsa_meth))
00432                 goto err;
00433 
00434         if (!SSL_use_RSAPrivateKey(ssl, rsa))
00435                 goto err;
00436         RSA_free(rsa);
00437 
00438         return 0;
00439 
00440 err:
00441         if (cert)
00442                 X509_free(cert);
00443         if (rsa)
00444                 RSA_free(rsa);
00445         else {
00446                 free(rsa_meth);
00447                 cryptoapi_free_data(priv);
00448         }
00449         return -1;
00450 }
00451 
00452 
00453 static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
00454 {
00455         HCERTSTORE cs;
00456         PCCERT_CONTEXT ctx = NULL;
00457         X509 *cert;
00458         char buf[128];
00459 
00460         if (mingw_load_crypto_func())
00461                 return -1;
00462 
00463         if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
00464                 return -1;
00465 
00466         cs = CertOpenSystemStore(0, name + 13);
00467         if (cs == NULL) {
00468                 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
00469                            "'%s': error=%d", __func__, name + 13,
00470                            (int) GetLastError());
00471                 return -1;
00472         }
00473 
00474         while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
00475                 cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ctx->pbCertEncoded,
00476                                 ctx->cbCertEncoded);
00477                 if (cert == NULL) {
00478                         wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
00479                                    "X509 DER encoding for CA cert");
00480                         continue;
00481                 }
00482 
00483                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
00484                                   sizeof(buf));
00485                 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
00486                            "system certificate store: subject='%s'", buf);
00487 
00488                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
00489                         tls_show_errors(MSG_WARNING, __func__,
00490                                         "Failed to add ca_cert to OpenSSL "
00491                                         "certificate store");
00492                 }
00493 
00494                 X509_free(cert);
00495         }
00496 
00497         if (!CertCloseStore(cs, 0)) {
00498                 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
00499                            "'%s': error=%d", __func__, name + 13,
00500                            (int) GetLastError());
00501         }
00502 
00503         return 0;
00504 }
00505 
00506 
00507 #else /* CONFIG_NATIVE_WINDOWS */
00508 
00509 static int tls_cryptoapi_cert(SSL *ssl, const char *name)
00510 {
00511         return -1;
00512 }
00513 
00514 #endif /* CONFIG_NATIVE_WINDOWS */
00515 
00516 
00517 static void ssl_info_cb(const SSL *ssl, int where, int ret)
00518 {
00519         const char *str;
00520         int w;
00521 
00522         wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
00523         w = where & ~SSL_ST_MASK;
00524         if (w & SSL_ST_CONNECT)
00525                 str = "SSL_connect";
00526         else if (w & SSL_ST_ACCEPT)
00527                 str = "SSL_accept";
00528         else
00529                 str = "undefined";
00530 
00531         if (where & SSL_CB_LOOP) {
00532                 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
00533                            str, SSL_state_string_long(ssl));
00534         } else if (where & SSL_CB_ALERT) {
00535                 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
00536                            where & SSL_CB_READ ?
00537                            "read (remote end reported an error)" :
00538                            "write (local SSL3 detected an error)",
00539                            SSL_alert_type_string_long(ret),
00540                            SSL_alert_desc_string_long(ret));
00541                 if ((ret >> 8) == SSL3_AL_FATAL) {
00542                         struct tls_connection *conn =
00543                                 SSL_get_app_data((SSL *) ssl);
00544                         if (where & SSL_CB_READ)
00545                                 conn->read_alerts++;
00546                         else
00547                                 conn->write_alerts++;
00548                 }
00549         } else if (where & SSL_CB_EXIT && ret <= 0) {
00550                 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
00551                            str, ret == 0 ? "failed" : "error",
00552                            SSL_state_string_long(ssl));
00553         }
00554 }
00555 
00556 
00557 #ifndef OPENSSL_NO_ENGINE
00558 
00571 static int tls_engine_load_dynamic_generic(const char *pre[],
00572                                            const char *post[], const char *id)
00573 {
00574         ENGINE *engine;
00575         const char *dynamic_id = "dynamic";
00576 
00577         engine = ENGINE_by_id(id);
00578         if (engine) {
00579                 ENGINE_free(engine);
00580                 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
00581                            "available", id);
00582                 return 0;
00583         }
00584         ERR_clear_error();
00585 
00586         engine = ENGINE_by_id(dynamic_id);
00587         if (engine == NULL) {
00588                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
00589                            dynamic_id,
00590                            ERR_error_string(ERR_get_error(), NULL));
00591                 return -1;
00592         }
00593 
00594         /* Perform the pre commands. This will load the engine. */
00595         while (pre && pre[0]) {
00596                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
00597                 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
00598                         wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
00599                                    "%s %s [%s]", pre[0], pre[1],
00600                                    ERR_error_string(ERR_get_error(), NULL));
00601                         ENGINE_free(engine);
00602                         return -1;
00603                 }
00604                 pre += 2;
00605         }
00606 
00607         /*
00608          * Free the reference to the "dynamic" engine. The loaded engine can
00609          * now be looked up using ENGINE_by_id().
00610          */
00611         ENGINE_free(engine);
00612 
00613         engine = ENGINE_by_id(id);
00614         if (engine == NULL) {
00615                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
00616                            id, ERR_error_string(ERR_get_error(), NULL));
00617                 return -1;
00618         }
00619 
00620         while (post && post[0]) {
00621                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
00622                 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
00623                         wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
00624                                 " %s %s [%s]", post[0], post[1],
00625                                    ERR_error_string(ERR_get_error(), NULL));
00626                         ENGINE_remove(engine);
00627                         ENGINE_free(engine);
00628                         return -1;
00629                 }
00630                 post += 2;
00631         }
00632         ENGINE_free(engine);
00633 
00634         return 0;
00635 }
00636 
00637 
00644 static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
00645                                           const char *pkcs11_module_path)
00646 {
00647         char *engine_id = "pkcs11";
00648         const char *pre_cmd[] = {
00649                 "SO_PATH", pkcs11_so_path,
00650                 "ID", engine_id,
00651                 "LIST_ADD", "1",
00652                 /* "NO_VCHECK", "1", */
00653                 "LOAD", NULL,
00654                 NULL, NULL
00655         };
00656         const char *post_cmd[] = {
00657                 "MODULE_PATH", pkcs11_module_path,
00658                 NULL, NULL
00659         };
00660 
00661         if (!pkcs11_so_path || !pkcs11_module_path)
00662                 return 0;
00663 
00664         wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
00665                    pkcs11_so_path);
00666 
00667         return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
00668 }
00669 
00670 
00676 static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
00677 {
00678         char *engine_id = "opensc";
00679         const char *pre_cmd[] = {
00680                 "SO_PATH", opensc_so_path,
00681                 "ID", engine_id,
00682                 "LIST_ADD", "1",
00683                 "LOAD", NULL,
00684                 NULL, NULL
00685         };
00686 
00687         if (!opensc_so_path)
00688                 return 0;
00689 
00690         wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
00691                    opensc_so_path);
00692 
00693         return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
00694 }
00695 #endif /* OPENSSL_NO_ENGINE */
00696 
00697 
00698 void * tls_init(const struct tls_config *conf)
00699 {
00700         SSL_CTX *ssl;
00701 
00702         if (tls_openssl_ref_count == 0) {
00703                 SSL_load_error_strings();
00704                 SSL_library_init();
00705                 /* TODO: if /dev/urandom is available, PRNG is seeded
00706                  * automatically. If this is not the case, random data should
00707                  * be added here. */
00708 
00709 #ifdef PKCS12_FUNCS
00710                 PKCS12_PBE_add();
00711 #endif  /* PKCS12_FUNCS */
00712         }
00713         tls_openssl_ref_count++;
00714 
00715         ssl = SSL_CTX_new(TLSv1_method());
00716         if (ssl == NULL)
00717                 return NULL;
00718 
00719         SSL_CTX_set_info_callback(ssl, ssl_info_cb);
00720 
00721 #ifndef OPENSSL_NO_ENGINE
00722         if (conf &&
00723             (conf->opensc_engine_path || conf->pkcs11_engine_path ||
00724              conf->pkcs11_module_path)) {
00725                 wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
00726                 ERR_load_ENGINE_strings();
00727                 ENGINE_load_dynamic();
00728 
00729                 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
00730                     tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
00731                                                    conf->pkcs11_module_path)) {
00732                         tls_deinit(ssl);
00733                         return NULL;
00734                 }
00735         }
00736 #endif /* OPENSSL_NO_ENGINE */
00737 
00738         return ssl;
00739 }
00740 
00741 
00742 void tls_deinit(void *ssl_ctx)
00743 {
00744         SSL_CTX *ssl = ssl_ctx;
00745         SSL_CTX_free(ssl);
00746 
00747         tls_openssl_ref_count--;
00748         if (tls_openssl_ref_count == 0) {
00749 #ifndef OPENSSL_NO_ENGINE
00750                 ENGINE_cleanup();
00751 #endif /* OPENSSL_NO_ENGINE */
00752                 ERR_free_strings();
00753                 EVP_cleanup();
00754         }
00755 }
00756 
00757 
00758 static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
00759                            const char *pin, const char *key_id)
00760 {
00761 #ifndef OPENSSL_NO_ENGINE
00762         int ret = -1;
00763         if (engine_id == NULL) {
00764                 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
00765                 return -1;
00766         }
00767         if (pin == NULL) {
00768                 wpa_printf(MSG_ERROR, "ENGINE: Smartcard PIN not set");
00769                 return -1;
00770         }
00771         if (key_id == NULL) {
00772                 wpa_printf(MSG_ERROR, "ENGINE: Key Id not set");
00773                 return -1;
00774         }
00775 
00776         ERR_clear_error();
00777         conn->engine = ENGINE_by_id(engine_id);
00778         if (!conn->engine) {
00779                 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
00780                            engine_id, ERR_error_string(ERR_get_error(), NULL));
00781                 goto err;
00782         }
00783         if (ENGINE_init(conn->engine) != 1) {
00784                 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
00785                            "(engine: %s) [%s]", engine_id,
00786                            ERR_error_string(ERR_get_error(), NULL));
00787                 goto err;
00788         }
00789         wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
00790 
00791         if (ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
00792                 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
00793                            ERR_error_string(ERR_get_error(), NULL));
00794                 goto err;
00795         }
00796         conn->private_key = ENGINE_load_private_key(conn->engine,
00797                                                     key_id, NULL, NULL);
00798         if (!conn->private_key) {
00799                 wpa_printf(MSG_ERROR, "ENGINE: cannot load private key with id"
00800                                 " '%s' [%s]", key_id,
00801                            ERR_error_string(ERR_get_error(), NULL));
00802                 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
00803                 goto err;
00804         }
00805         return 0;
00806 
00807 err:
00808         if (conn->engine) {
00809                 ENGINE_free(conn->engine);
00810                 conn->engine = NULL;
00811         }
00812 
00813         if (conn->private_key) {
00814                 EVP_PKEY_free(conn->private_key);
00815                 conn->private_key = NULL;
00816         }
00817 
00818         return ret;
00819 #else /* OPENSSL_NO_ENGINE */
00820         return 0;
00821 #endif /* OPENSSL_NO_ENGINE */
00822 }
00823 
00824 
00825 static void tls_engine_deinit(struct tls_connection *conn)
00826 {
00827 #ifndef OPENSSL_NO_ENGINE
00828         wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
00829         if (conn->private_key) {
00830                 EVP_PKEY_free(conn->private_key);
00831                 conn->private_key = NULL;
00832         }
00833         if (conn->engine) {
00834                 ENGINE_finish(conn->engine);
00835                 conn->engine = NULL;
00836         }
00837 #endif /* OPENSSL_NO_ENGINE */
00838 }
00839 
00840 
00841 int tls_get_errors(void *ssl_ctx)
00842 {
00843         int count = 0;
00844         unsigned long err;
00845 
00846         while ((err = ERR_get_error())) {
00847                 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
00848                            ERR_error_string(err, NULL));
00849                 count++;
00850         }
00851 
00852         return count;
00853 }
00854 
00855 struct tls_connection * tls_connection_init(void *ssl_ctx)
00856 {
00857         SSL_CTX *ssl = ssl_ctx;
00858         struct tls_connection *conn;
00859 
00860         conn = malloc(sizeof(*conn));
00861         if (conn == NULL)
00862                 return NULL;
00863         memset(conn, 0, sizeof(*conn));
00864         conn->ssl = SSL_new(ssl);
00865         if (conn->ssl == NULL) {
00866                 tls_show_errors(MSG_INFO, __func__,
00867                                 "Failed to initialize new SSL connection");
00868                 free(conn);
00869                 return NULL;
00870         }
00871 
00872         SSL_set_app_data(conn->ssl, conn);
00873         SSL_set_options(conn->ssl,
00874                         SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
00875                         SSL_OP_SINGLE_DH_USE);
00876 
00877         conn->ssl_in = BIO_new(BIO_s_mem());
00878         if (!conn->ssl_in) {
00879                 tls_show_errors(MSG_INFO, __func__,
00880                                 "Failed to create a new BIO for ssl_in");
00881                 SSL_free(conn->ssl);
00882                 free(conn);
00883                 return NULL;
00884         }
00885 
00886         conn->ssl_out = BIO_new(BIO_s_mem());
00887         if (!conn->ssl_out) {
00888                 tls_show_errors(MSG_INFO, __func__,
00889                                 "Failed to create a new BIO for ssl_out");
00890                 SSL_free(conn->ssl);
00891                 BIO_free(conn->ssl_in);
00892                 free(conn);
00893                 return NULL;
00894         }
00895 
00896         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
00897 
00898         return conn;
00899 }
00900 
00901 
00902 void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
00903 {
00904         if (conn == NULL)
00905                 return;
00906         free(conn->pre_shared_secret);
00907         SSL_free(conn->ssl);
00908         tls_engine_deinit(conn);
00909         free(conn->subject_match);
00910         free(conn->altsubject_match);
00911         free(conn);
00912 }
00913 
00914 
00915 int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
00916 {
00917         return conn ? SSL_is_init_finished(conn->ssl) : 0;
00918 }
00919 
00920 
00921 int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
00922 {
00923         if (conn == NULL)
00924                 return -1;
00925 
00926         /* Shutdown previous TLS connection without notifying the peer
00927          * because the connection was already terminated in practice
00928          * and "close notify" shutdown alert would confuse AS. */
00929         SSL_set_quiet_shutdown(conn->ssl, 1);
00930         SSL_shutdown(conn->ssl);
00931         return 0;
00932 }
00933 
00934 
00935 static int tls_match_altsubject(X509 *cert, const char *match)
00936 {
00937         GENERAL_NAME *gen;
00938         char *field, *tmp;
00939         void *ext;
00940         int i, found = 0;
00941         size_t len;
00942 
00943         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
00944 
00945         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
00946                 gen = sk_GENERAL_NAME_value(ext, i);
00947                 switch (gen->type) {
00948                 case GEN_EMAIL:
00949                         field = "EMAIL";
00950                         break;
00951                 case GEN_DNS:
00952                         field = "DNS";
00953                         break;
00954                 case GEN_URI:
00955                         field = "URI";
00956                         break;
00957                 default:
00958                         field = NULL;
00959                         wpa_printf(MSG_DEBUG, "TLS: altSubjectName: "
00960                                    "unsupported type=%d", gen->type);
00961                         break;
00962                 }
00963 
00964                 if (!field)
00965                         continue;
00966 
00967                 wpa_printf(MSG_DEBUG, "TLS: altSubjectName: %s:%s",
00968                            field, gen->d.ia5->data);
00969                 len = strlen(field) + 1 + strlen((char *) gen->d.ia5->data) +
00970                         1;
00971                 tmp = malloc(len);
00972                 if (tmp == NULL)
00973                         continue;
00974                 snprintf(tmp, len, "%s:%s", field, gen->d.ia5->data);
00975                 if (strstr(tmp, match))
00976                         found++;
00977                 free(tmp);
00978         }
00979 
00980         return found;
00981 }
00982 
00983 
00984 static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
00985 {
00986         char buf[256];
00987         X509 *err_cert;
00988         int err, depth;
00989         SSL *ssl;
00990         struct tls_connection *conn;
00991         char *match, *altmatch;
00992 
00993         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
00994         err = X509_STORE_CTX_get_error(x509_ctx);
00995         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
00996         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
00997                                          SSL_get_ex_data_X509_STORE_CTX_idx());
00998         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
00999 
01000         conn = SSL_get_app_data(ssl);
01001         match = conn ? conn->subject_match : NULL;
01002         altmatch = conn ? conn->altsubject_match : NULL;
01003 
01004         if (!preverify_ok) {
01005                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
01006                            " error %d (%s) depth %d for '%s'", err,
01007                            X509_verify_cert_error_string(err), depth, buf);
01008         } else {
01009                 wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - "
01010                            "preverify_ok=%d err=%d (%s) depth=%d buf='%s'",
01011                            preverify_ok, err,
01012                            X509_verify_cert_error_string(err), depth, buf);
01013                 if (depth == 0 && match && strstr(buf, match) == NULL) {
01014                         wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
01015                                    "match with '%s'", buf, match);
01016                         preverify_ok = 0;
01017                 } else if (depth == 0 && altmatch &&
01018                            !tls_match_altsubject(err_cert, altmatch)) {
01019                         wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
01020                                    "'%s' not found", altmatch);
01021                         preverify_ok = 0;
01022                 }
01023         }
01024 
01025         return preverify_ok;
01026 }
01027 
01028 
01029 #ifndef OPENSSL_NO_STDIO
01030 static int tls_load_ca_der(void *_ssl_ctx, const char *ca_cert)
01031 {
01032         SSL_CTX *ssl_ctx = _ssl_ctx;
01033         X509_LOOKUP *lookup;
01034         int ret = 0;
01035 
01036         lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
01037                                        X509_LOOKUP_file());
01038         if (lookup == NULL) {
01039                 tls_show_errors(MSG_WARNING, __func__,
01040                                 "Failed add lookup for X509 store");
01041                 return -1;
01042         }
01043 
01044         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
01045                 unsigned long err = ERR_peek_error();
01046                 tls_show_errors(MSG_WARNING, __func__,
01047                                 "Failed load CA in DER format");
01048                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
01049                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
01050                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
01051                                    "cert already in hash table error",
01052                                    __func__);
01053                 } else
01054                         ret = -1;
01055         }
01056 
01057         return ret;
01058 }
01059 #endif /* OPENSSL_NO_STDIO */
01060 
01061 
01062 static int tls_connection_ca_cert(void *_ssl_ctx, struct tls_connection *conn,
01063                                   const char *ca_cert, const u8 *ca_cert_blob,
01064                                   size_t ca_cert_blob_len, const char *ca_path)
01065 {
01066         SSL_CTX *ssl_ctx = _ssl_ctx;
01067 
01068         if (ca_cert_blob) {
01069                 X509 *cert = d2i_X509(NULL, (OPENSSL_d2i_TYPE) &ca_cert_blob,
01070                                       ca_cert_blob_len);
01071                 if (cert == NULL) {
01072                         tls_show_errors(MSG_WARNING, __func__,
01073                                         "Failed to parse ca_cert_blob");
01074                         return -1;
01075                 }
01076 
01077                 if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
01078                         tls_show_errors(MSG_WARNING, __func__,
01079                                         "Failed to add ca_cert_blob to "
01080                                         "certificate store");
01081                         X509_free(cert);
01082                         return -1;
01083                 }
01084                 X509_free(cert);
01085                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
01086                            "to certificate store", __func__);
01087                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
01088                 return 0;
01089         }
01090 
01091 #ifdef CONFIG_NATIVE_WINDOWS
01092         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
01093             0) {
01094                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
01095                            "system certificate store");
01096                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
01097                 return 0;
01098         }
01099 #endif /* CONFIG_NATIVE_WINDOWS */
01100 
01101         if (ca_cert || ca_path) {
01102 #ifndef OPENSSL_NO_STDIO
01103                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
01104                     1) {
01105                         tls_show_errors(MSG_WARNING, __func__,
01106                                         "Failed to load root certificates");
01107                         if (ca_cert &&
01108                             tls_load_ca_der(ssl_ctx, ca_cert) == 0) {
01109                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
01110                                            "DER format CA certificate",
01111                                            __func__);
01112                         } else
01113                                 return -1;
01114                 } else {
01115                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
01116                                    "certificate(s) loaded");
01117                         tls_get_errors(ssl_ctx);
01118                 }
01119                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
01120 #else /* OPENSSL_NO_STDIO */
01121                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
01122                            __func__);
01123                 return -1;
01124 #endif /* OPENSSL_NO_STDIO */
01125         } else {
01126                 /* No ca_cert configured - do not try to verify server
01127                  * certificate */
01128                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
01129         }
01130 
01131         return 0;
01132 }
01133 
01134 
01135 int tls_global_ca_cert(void *_ssl_ctx, const char *ca_cert)
01136 {
01137         SSL_CTX *ssl_ctx = _ssl_ctx;
01138         if (ca_cert) {
01139                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
01140                 {
01141                         tls_show_errors(MSG_WARNING, __func__,
01142                                         "Failed to load root certificates");
01143                         return -1;
01144                 }
01145 
01146                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
01147                            "certificate(s) loaded");
01148 
01149 #ifndef OPENSSL_NO_STDIO
01150                 /* Add the same CAs to the client certificate requests */
01151                 SSL_CTX_set_client_CA_list(ssl_ctx,
01152                                            SSL_load_client_CA_file(ca_cert));
01153 #endif /* OPENSSL_NO_STDIO */
01154         }
01155 
01156         return 0;
01157 }
01158 
01159 
01160 int tls_global_set_verify(void *ssl_ctx, int check_crl)
01161 {
01162         int flags;
01163 
01164         if (check_crl) {
01165                 X509_STORE *cs = SSL_CTX_get_cert_store(ssl_ctx);
01166                 if (cs == NULL) {
01167                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
01168                                         "certificate store when enabling "
01169                                         "check_crl");
01170                         return -1;
01171                 }
01172                 flags = X509_V_FLAG_CRL_CHECK;
01173                 if (check_crl == 2)
01174                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
01175                 X509_STORE_set_flags(cs, flags);
01176         }
01177         return 0;
01178 }
01179 
01180 
01181 static int tls_connection_set_subject_match(void *ssl_ctx,
01182                                             struct tls_connection *conn,
01183                                             const char *subject_match,
01184                                             const char *altsubject_match)
01185 {
01186         free(conn->subject_match);
01187         conn->subject_match = NULL;
01188         if (subject_match) {
01189                 conn->subject_match = strdup(subject_match);
01190                 if (conn->subject_match == NULL)
01191                         return -1;
01192         }
01193 
01194         free(conn->altsubject_match);
01195         conn->altsubject_match = NULL;
01196         if (altsubject_match) {
01197                 conn->altsubject_match = strdup(altsubject_match);
01198                 if (conn->altsubject_match == NULL)
01199                         return -1;
01200         }
01201 
01202         return 0;
01203 }
01204 
01205 
01206 int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
01207                               int verify_peer)
01208 {
01209         if (conn == NULL)
01210                 return -1;
01211 
01212         if (verify_peer) {
01213                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
01214                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
01215                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
01216         } else {
01217                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
01218         }
01219 
01220         SSL_set_accept_state(conn->ssl);
01221 
01222         return 0;
01223 }
01224 
01225 
01226 static int tls_connection_client_cert(void *ssl_ctx,
01227                                       struct tls_connection *conn,
01228                                       const char *client_cert,
01229                                       const u8 *client_cert_blob,
01230                                       size_t client_cert_blob_len)
01231 {
01232         if (client_cert == NULL && client_cert_blob == NULL)
01233                 return 0;
01234 
01235         if (client_cert_blob &&
01236             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
01237                                      client_cert_blob_len) == 1) {
01238                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
01239                            "OK");
01240                 return 0;
01241         } else if (client_cert_blob) {
01242                 tls_show_errors(MSG_DEBUG, __func__,
01243                                 "SSL_use_certificate_ASN1 failed");
01244         }
01245 
01246         if (client_cert == NULL)
01247                 return -1;
01248 
01249 #ifndef OPENSSL_NO_STDIO
01250         if (SSL_use_certificate_file(conn->ssl, client_cert,
01251                                      SSL_FILETYPE_ASN1) == 1) {
01252                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
01253                            " --> OK");
01254                 return 0;
01255         } else {
01256                 tls_show_errors(MSG_DEBUG, __func__,
01257                                 "SSL_use_certificate_file (DER) failed");
01258         }
01259 
01260         if (SSL_use_certificate_file(conn->ssl, client_cert,
01261                                      SSL_FILETYPE_PEM) == 1) {
01262                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
01263                            " --> OK");
01264                 return 0;
01265         } else {
01266                 tls_show_errors(MSG_DEBUG, __func__,
01267                                 "SSL_use_certificate_file (PEM) failed");
01268         }
01269 #else /* OPENSSL_NO_STDIO */
01270         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
01271 #endif /* OPENSSL_NO_STDIO */
01272 
01273         return -1;
01274 }
01275 
01276 
01277 int tls_global_client_cert(void *_ssl_ctx, const char *client_cert)
01278 {
01279 #ifndef OPENSSL_NO_STDIO
01280         SSL_CTX *ssl_ctx = _ssl_ctx;
01281         if (client_cert == NULL)
01282                 return 0;
01283 
01284         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
01285                                          SSL_FILETYPE_ASN1) != 1 &&
01286             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
01287                                          SSL_FILETYPE_PEM) != 1) {
01288                 tls_show_errors(MSG_INFO, __func__,
01289                                 "Failed to load client certificate");
01290                 return -1;
01291         }
01292         return 0;
01293 #else /* OPENSSL_NO_STDIO */
01294         if (client_cert == NULL)
01295                 return 0;
01296         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
01297         return -1;
01298 #endif /* OPENSSL_NO_STDIO */
01299 }
01300 
01301 
01302 static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
01303 {
01304         if (password == NULL) {
01305                 return 0;
01306         }
01307         strncpy(buf, (char *) password, size);
01308         buf[size - 1] = '\0';
01309         return strlen(buf);
01310 }
01311 
01312 
01313 #ifdef PKCS12_FUNCS
01314 static int tls_parse_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, PKCS12 *p12,
01315                             const char *passwd)
01316 {
01317         EVP_PKEY *pkey;
01318         X509 *cert;
01319         STACK_OF(X509) *certs;
01320         int res = 0;
01321         char buf[256];
01322 
01323         pkey = NULL;
01324         cert = NULL;
01325         certs = NULL;
01326         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
01327                 tls_show_errors(MSG_DEBUG, __func__,
01328                                 "Failed to parse PKCS12 file");
01329                 PKCS12_free(p12);
01330                 return -1;
01331         }
01332         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
01333 
01334         if (cert) {
01335                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
01336                                   sizeof(buf));
01337                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
01338                            "subject='%s'", buf);
01339                 if (ssl) {
01340                         if (SSL_use_certificate(ssl, cert) != 1)
01341                                 res = -1;
01342                 } else {
01343                         if (SSL_CTX_use_certificate(ssl_ctx, cert) != 1)
01344                                 res = -1;
01345                 }
01346                 X509_free(cert);
01347         }
01348 
01349         if (pkey) {
01350                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
01351                 if (ssl) {
01352                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
01353                                 res = -1;
01354                 } else {
01355                         if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) != 1)
01356                                 res = -1;
01357                 }
01358                 EVP_PKEY_free(pkey);
01359         }
01360 
01361         if (certs) {
01362                 while ((cert = sk_X509_pop(certs)) != NULL) {
01363                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
01364                                           sizeof(buf));
01365                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
01366                                    " from PKCS12: subject='%s'", buf);
01367                         /*
01368                          * There is no SSL equivalent for the chain cert - so
01369                          * always add it to the context...
01370                          */
01371                         if (SSL_CTX_add_extra_chain_cert(ssl_ctx, cert) != 1) {
01372                                 res = -1;
01373                                 break;
01374                         }
01375                 }
01376                 sk_X509_free(certs);
01377         }
01378 
01379         PKCS12_free(p12);
01380 
01381         if (res < 0)
01382                 tls_get_errors(ssl_ctx);
01383 
01384         return res;
01385 }
01386 #endif  /* PKCS12_FUNCS */
01387 
01388 
01389 static int tls_read_pkcs12(SSL_CTX *ssl_ctx, SSL *ssl, const char *private_key,
01390                            const char *passwd)
01391 {
01392 #ifdef PKCS12_FUNCS
01393         FILE *f;
01394         PKCS12 *p12;
01395 
01396         f = fopen(private_key, "r");
01397         if (f == NULL)
01398                 return -1;
01399 
01400         p12 = d2i_PKCS12_fp(f, NULL);
01401         fclose(f);
01402 
01403         if (p12 == NULL) {
01404                 tls_show_errors(MSG_INFO, __func__,
01405                                 "Failed to use PKCS#12 file");
01406                 return -1;
01407         }
01408 
01409         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
01410 
01411 #else /* PKCS12_FUNCS */
01412         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
01413                    "p12/pfx files");
01414         return -1;
01415 #endif  /* PKCS12_FUNCS */
01416 }
01417 
01418 
01419 static int tls_read_pkcs12_blob(SSL_CTX *ssl_ctx, SSL *ssl,
01420                                 const u8 *blob, size_t len, const char *passwd)
01421 {
01422 #ifdef PKCS12_FUNCS
01423         PKCS12 *p12;
01424 
01425         p12 = d2i_PKCS12(NULL, (OPENSSL_d2i_TYPE) &blob, len);
01426         if (p12 == NULL) {
01427                 tls_show_errors(MSG_INFO, __func__,
01428                                 "Failed to use PKCS#12 blob");
01429                 return -1;
01430         }
01431 
01432         return tls_parse_pkcs12(ssl_ctx, ssl, p12, passwd);
01433 
01434 #else /* PKCS12_FUNCS */
01435         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
01436                    "p12/pfx blobs");
01437         return -1;
01438 #endif  /* PKCS12_FUNCS */
01439 }
01440 
01441 
01442 static int tls_connection_engine_private_key(void *_ssl_ctx,
01443                                              struct tls_connection *conn)
01444 {
01445 #ifndef OPENSSL_NO_ENGINE
01446         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
01447                 tls_show_errors(MSG_ERROR, __func__,
01448                                 "ENGINE: cannot use private key for TLS");
01449                 return -1;
01450         }
01451         if (!SSL_check_private_key(conn->ssl)) {
01452                 tls_show_errors(MSG_INFO, __func__,
01453                                 "Private key failed verification");
01454                 return -1;
01455         }
01456         return 0;
01457 #else /* OPENSSL_NO_ENGINE */
01458         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
01459                    "engine support was not compiled in");
01460         return -1;
01461 #endif /* OPENSSL_NO_ENGINE */
01462 }
01463 
01464 
01465 static int tls_connection_private_key(void *_ssl_ctx,
01466                                       struct tls_connection *conn,
01467                                       const char *private_key,
01468                                       const char *private_key_passwd,
01469                                       const u8 *private_key_blob,
01470                                       size_t private_key_blob_len)
01471 {
01472         SSL_CTX *ssl_ctx = _ssl_ctx;
01473         char *passwd;
01474         int ok;
01475 
01476         if (private_key == NULL && private_key_blob == NULL)
01477                 return 0;
01478 
01479         if (private_key_passwd) {
01480                 passwd = strdup(private_key_passwd);
01481                 if (passwd == NULL)
01482                         return -1;
01483         } else
01484                 passwd = NULL;
01485 
01486         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
01487         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
01488 
01489         ok = 0;
01490         while (private_key_blob) {
01491                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
01492                                             (u8 *) private_key_blob,
01493                                             private_key_blob_len) == 1) {
01494                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
01495                                    "ASN1(EVP_PKEY_RSA) --> OK");
01496                         ok = 1;
01497                         break;
01498                 } else {
01499                         tls_show_errors(MSG_DEBUG, __func__,
01500                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA)"
01501                                         " failed");
01502                 }
01503 
01504                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
01505                                             (u8 *) private_key_blob,
01506                                             private_key_blob_len) == 1) {
01507                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
01508                                    "ASN1(EVP_PKEY_DSA) --> OK");
01509                         ok = 1;
01510                         break;
01511                 } else {
01512                         tls_show_errors(MSG_DEBUG, __func__,
01513                                         "SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA)"
01514                                         " failed");
01515                 }
01516 
01517                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
01518                                                (u8 *) private_key_blob,
01519                                                private_key_blob_len) == 1) {
01520                         wpa_printf(MSG_DEBUG, "OpenSSL: "
01521                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
01522                         ok = 1;
01523                         break;
01524                 } else {
01525                         tls_show_errors(MSG_DEBUG, __func__,
01526                                         "SSL_use_RSAPrivateKey_ASN1 failed");
01527                 }
01528 
01529                 if (tls_read_pkcs12_blob(ssl_ctx, conn->ssl, private_key_blob,
01530                                          private_key_blob_len, passwd) == 0) {
01531                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
01532                                    "OK");
01533                         ok = 1;
01534                         break;
01535                 }
01536 
01537                 break;
01538         }
01539 
01540         while (!ok && private_key) {
01541 #ifndef OPENSSL_NO_STDIO
01542                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
01543                                             SSL_FILETYPE_ASN1) == 1) {
01544                         wpa_printf(MSG_DEBUG, "OpenSSL: "
01545                                    "SSL_use_PrivateKey_File (DER) --> OK");
01546                         ok = 1;
01547                         break;
01548                 } else {
01549                         tls_show_errors(MSG_DEBUG, __func__,
01550                                         "SSL_use_PrivateKey_File (DER) "
01551                                         "failed");
01552                 }
01553 
01554                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
01555                                             SSL_FILETYPE_PEM) == 1) {
01556                         wpa_printf(MSG_DEBUG, "OpenSSL: "
01557                                    "SSL_use_PrivateKey_File (PEM) --> OK");
01558                         ok = 1;
01559                         break;
01560                 } else {
01561                         tls_show_errors(MSG_DEBUG, __func__,
01562                                         "SSL_use_PrivateKey_File (PEM) "
01563                                         "failed");
01564                 }
01565 #else /* OPENSSL_NO_STDIO */
01566                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
01567                            __func__);
01568 #endif /* OPENSSL_NO_STDIO */
01569 
01570                 if (tls_read_pkcs12(ssl_ctx, conn->ssl, private_key, passwd)
01571                     == 0) {
01572                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
01573                                    "--> OK");
01574                         ok = 1;
01575                         break;
01576                 }
01577 
01578                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
01579                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
01580                                    "access certificate store --> OK");
01581                         ok = 1;
01582                         break;
01583                 }
01584 
01585                 break;
01586         }
01587 
01588         if (!ok) {
01589                 wpa_printf(MSG_INFO, "OpenSSL: Failed to load private key");
01590                 free(passwd);
01591                 ERR_clear_error();
01592                 return -1;
01593         }
01594         ERR_clear_error();
01595         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
01596         free(passwd);
01597         
01598         if (!SSL_check_private_key(conn->ssl)) {
01599                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
01600                                 "verification");
01601                 return -1;
01602         }
01603 
01604         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
01605         return 0;
01606 }
01607 
01608 
01609 int tls_global_private_key(void *_ssl_ctx, const char *private_key,
01610                            const char *private_key_passwd)
01611 {
01612         SSL_CTX *ssl_ctx = _ssl_ctx;
01613         char *passwd;
01614 
01615         if (private_key == NULL)
01616                 return 0;
01617 
01618         if (private_key_passwd) {
01619                 passwd = strdup(private_key_passwd);
01620                 if (passwd == NULL)
01621                         return -1;
01622         } else
01623                 passwd = NULL;
01624 
01625         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
01626         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
01627         if (
01628 #ifndef OPENSSL_NO_STDIO
01629             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
01630                                         SSL_FILETYPE_ASN1) != 1 &&
01631             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
01632                                         SSL_FILETYPE_PEM) != 1 &&
01633 #endif /* OPENSSL_NO_STDIO */
01634             tls_read_pkcs12(ssl_ctx, NULL, private_key, passwd)) {
01635                 tls_show_errors(MSG_INFO, __func__,
01636                                 "Failed to load private key");
01637                 free(passwd);
01638                 ERR_clear_error();
01639                 return -1;
01640         }
01641         free(passwd);
01642         ERR_clear_error();
01643         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
01644         
01645         if (!SSL_CTX_check_private_key(ssl_ctx)) {
01646                 tls_show_errors(MSG_INFO, __func__,
01647                                 "Private key failed verification");
01648                 return -1;
01649         }
01650 
01651         return 0;
01652 }
01653 
01654 
01655 static int tls_connection_dh(void *ssl_ctx, struct tls_connection *conn,
01656                       const char *dh_file)
01657 {
01658 #ifdef OPENSSL_NO_DH
01659         if (dh_file == NULL)
01660                 return 0;
01661         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
01662                    "dh_file specified");
01663         return -1;
01664 #else /* OPENSSL_NO_DH */
01665         DH *dh;
01666         BIO *bio;
01667 
01668         /* TODO: add support for dh_blob */
01669         if (dh_file == NULL)
01670                 return 0;
01671         if (conn == NULL)
01672                 return -1;
01673 
01674         bio = BIO_new_file(dh_file, "r");
01675         if (bio == NULL) {
01676                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
01677                            dh_file, ERR_error_string(ERR_get_error(), NULL));
01678                 return -1;
01679         }
01680         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
01681         BIO_free(bio);
01682 #ifndef OPENSSL_NO_DSA
01683         while (dh == NULL) {
01684                 DSA *dsa;
01685                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
01686                            " trying to parse as DSA params", dh_file,
01687                            ERR_error_string(ERR_get_error(), NULL));
01688                 bio = BIO_new_file(dh_file, "r");
01689                 if (bio == NULL)
01690                         break;
01691                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
01692                 BIO_free(bio);
01693                 if (!dsa) {
01694                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
01695                                    "'%s': %s", dh_file,
01696                                    ERR_error_string(ERR_get_error(), NULL));
01697                         break;
01698                 }
01699 
01700                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
01701                 dh = DSA_dup_DH(dsa);
01702                 DSA_free(dsa);
01703                 if (dh == NULL) {
01704                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
01705                                    "params into DH params");
01706                         break;
01707                 }
01708                 break;
01709         }
01710 #endif /* !OPENSSL_NO_DSA */
01711         if (dh == NULL) {
01712                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
01713                            "'%s'", dh_file);
01714                 return -1;
01715         }
01716 
01717         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
01718                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
01719                            "%s", dh_file,
01720                            ERR_error_string(ERR_get_error(), NULL));
01721                 DH_free(dh);
01722                 return -1;
01723         }
01724         DH_free(dh);
01725         return 0;
01726 #endif /* OPENSSL_NO_DH */
01727 }
01728 
01729 
01730 int tls_connection_get_keys(void *ssl_ctx, struct tls_connection *conn,
01731                             struct tls_keys *keys)
01732 {
01733         SSL *ssl;
01734 
01735         if (conn == NULL || keys == NULL)
01736                 return -1;
01737         ssl = conn->ssl;
01738         if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
01739                 return -1;
01740 
01741         memset(keys, 0, sizeof(*keys));
01742         keys->master_key = ssl->session->master_key;
01743         keys->master_key_len = ssl->session->master_key_length;
01744         keys->client_random = ssl->s3->client_random;
01745         keys->client_random_len = SSL3_RANDOM_SIZE;
01746         keys->server_random = ssl->s3->server_random;
01747         keys->server_random_len = SSL3_RANDOM_SIZE;
01748 
01749         return 0;
01750 }
01751 
01752 
01753 u8 * tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
01754                               const u8 *in_data, size_t in_len,
01755                               size_t *out_len)
01756 {
01757         int res;
01758         u8 *out_data;
01759 
01760         /*
01761          * Give TLS handshake data from the server (if available) to OpenSSL
01762          * for processing.
01763          */
01764         if (in_data &&
01765             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
01766                 tls_show_errors(MSG_INFO, __func__,
01767                                 "Handshake failed - BIO_write");
01768                 return NULL;
01769         }
01770 
01771         /* Initiate TLS handshake or continue the existing handshake */
01772         res = SSL_connect(conn->ssl);
01773         if (res != 1) {
01774                 int err = SSL_get_error(conn->ssl, res);
01775                 if (err == SSL_ERROR_WANT_READ)
01776                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
01777                                    "more data");
01778                 else if (err == SSL_ERROR_WANT_WRITE)
01779                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
01780                                    "write");
01781                 else {
01782                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
01783                         conn->failed++;
01784                 }
01785         }
01786 
01787         /* Get the TLS handshake data to be sent to the server */
01788         res = BIO_ctrl_pending(conn->ssl_out);
01789         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
01790         out_data = malloc(res == 0 ? 1 : res);
01791         if (out_data == NULL) {
01792                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
01793                            "handshake output (%d bytes)", res);
01794                 if (BIO_reset(conn->ssl_out) < 0) {
01795                         tls_show_errors(MSG_INFO, __func__,
01796                                         "BIO_reset failed");
01797                 }
01798                 *out_len = 0;
01799                 return NULL;
01800         }
01801         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
01802         if (res < 0) {
01803                 tls_show_errors(MSG_INFO, __func__,
01804                                 "Handshake failed - BIO_read");
01805                 if (BIO_reset(conn->ssl_out) < 0) {
01806                         tls_show_errors(MSG_INFO, __func__,
01807                                         "BIO_reset failed");
01808                 }
01809                 *out_len = 0;
01810                 return NULL;
01811         }
01812         *out_len = res;
01813         return out_data;
01814 }
01815 
01816 
01817 u8 * tls_connection_server_handshake(void *ssl_ctx,
01818                                      struct tls_connection *conn,
01819                                      const u8 *in_data, size_t in_len,
01820                                      size_t *out_len)
01821 {
01822         int res;
01823         u8 *out_data;
01824         char buf[10];
01825 
01826         if (in_data &&
01827             BIO_write(conn->ssl_in, in_data, in_len) < 0) {
01828                 tls_show_errors(MSG_INFO, __func__,
01829                                 "Handshake failed - BIO_write");
01830                 return NULL;
01831         }
01832 
01833         res = SSL_read(conn->ssl, buf, sizeof(buf));
01834         if (res >= 0) {
01835                 wpa_printf(MSG_DEBUG, "SSL: Unexpected data from SSL_read "
01836                            "(res=%d)", res);
01837         }
01838 
01839         res = BIO_ctrl_pending(conn->ssl_out);
01840         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
01841         out_data = malloc(res == 0 ? 1 : res);
01842         if (out_data == NULL) {
01843                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
01844                            "handshake output (%d bytes)", res);
01845                 if (BIO_reset(conn->ssl_out) < 0) {
01846                         tls_show_errors(MSG_INFO, __func__,
01847                                         "BIO_reset failed");
01848                 }
01849                 *out_len = 0;
01850                 return NULL;
01851         }
01852         res = res == 0 ? 0 : BIO_read(conn->ssl_out, out_data, res);
01853         if (res < 0) {
01854                 tls_show_errors(MSG_INFO, __func__,
01855                                 "Handshake failed - BIO_read");
01856                 if (BIO_reset(conn->ssl_out) < 0) {
01857                         tls_show_errors(MSG_INFO, __func__,
01858                                         "BIO_reset failed");
01859                 }
01860                 *out_len = 0;
01861                 return NULL;
01862         }
01863         *out_len = res;
01864         return out_data;
01865 }
01866 
01867 
01868 int tls_connection_encrypt(void *ssl_ctx, struct tls_connection *conn,
01869                            const u8 *in_data, size_t in_len,
01870                            u8 *out_data, size_t out_len)
01871 {
01872         int res;
01873 
01874         if (conn == NULL)
01875                 return -1;
01876 
01877         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
01878         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
01879             (res = BIO_reset(conn->ssl_out)) < 0) {
01880                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
01881                 return res;
01882         }
01883         res = SSL_write(conn->ssl, in_data, in_len);
01884         if (res < 0) {
01885                 tls_show_errors(MSG_INFO, __func__,
01886                                 "Encryption failed - SSL_write");
01887                 return res;
01888         }
01889 
01890         /* Read encrypted data to be sent to the server */
01891         res = BIO_read(conn->ssl_out, out_data, out_len);
01892         if (res < 0) {
01893                 tls_show_errors(MSG_INFO, __func__,
01894                                 "Encryption failed - BIO_read");
01895                 return res;
01896         }
01897 
01898         return res;
01899 }
01900 
01901 
01902 int tls_connection_decrypt(void *ssl_ctx, struct tls_connection *conn,
01903                            const u8 *in_data, size_t in_len,
01904                            u8 *out_data, size_t out_len)
01905 {
01906         int res;
01907 
01908         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
01909         res = BIO_write(conn->ssl_in, in_data, in_len);
01910         if (res < 0) {
01911                 tls_show_errors(MSG_INFO, __func__,
01912                                 "Decryption failed - BIO_write");
01913                 return res;
01914         }
01915         if (BIO_reset(conn->ssl_out) < 0) {
01916                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
01917                 return res;
01918         }
01919 
01920         /* Read decrypted data for further processing */
01921         res = SSL_read(conn->ssl, out_data, out_len);
01922         if (res < 0) {
01923                 tls_show_errors(MSG_INFO, __func__,
01924                                 "Decryption failed - SSL_read");
01925                 return res;
01926         }
01927 
01928         return res;
01929 }
01930 
01931 
01932 int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
01933 {
01934         return conn ? conn->ssl->hit : 0;
01935 }
01936 
01937 
01938 #ifdef EAP_FAST
01939 /* Pre-shared secred requires a patch to openssl, so this function is
01940  * commented out unless explicitly needed for EAP-FAST in order to be able to
01941  * build this file with unmodified openssl. */
01942 
01943 static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
01944                            STACK_OF(SSL_CIPHER) *peer_ciphers,
01945                            SSL_CIPHER **cipher, void *arg)
01946 {
01947         struct tls_connection *conn = arg;
01948 
01949         if (conn == NULL || conn->pre_shared_secret == 0)
01950                 return 0;
01951 
01952         memcpy(secret, conn->pre_shared_secret, conn->pre_shared_secret_len);
01953         *secret_len = conn->pre_shared_secret_len;
01954 
01955         return 1;
01956 }
01957 
01958 
01959 int tls_connection_set_master_key(void *ssl_ctx, struct tls_connection *conn,
01960                                   const u8 *key, size_t key_len)
01961 {
01962         if (conn == NULL || key_len > SSL_MAX_MASTER_KEY_LENGTH)
01963                 return -1;
01964 
01965         free(conn->pre_shared_secret);
01966         conn->pre_shared_secret = NULL;
01967         conn->pre_shared_secret_len = 0;
01968 
01969         if (key) {
01970                 conn->pre_shared_secret = malloc(key_len);
01971                 if (conn->pre_shared_secret) {
01972                         memcpy(conn->pre_shared_secret, key, key_len);
01973                         conn->pre_shared_secret_len = key_len;
01974                 }
01975                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
01976                                               conn) != 1)
01977                         return -1;
01978         } else {
01979                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
01980                         return -1;
01981         }
01982 
01983         return 0;
01984 }
01985 #endif /* EAP_FAST */
01986 
01987 
01988 int tls_connection_set_anon_dh(void *ssl_ctx, struct tls_connection *conn)
01989 {
01990         if (conn == NULL || conn->ssl == NULL)
01991                 return -1;
01992 
01993         if (SSL_set_cipher_list(conn->ssl, "ADH-AES128-SHA") != 1) {
01994                 tls_show_errors(MSG_INFO, __func__,
01995                                 "Anon DH configuration failed");
01996                 return -1;
01997         }
01998 
01999         return 0;
02000 }
02001 
02002 
02003 int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
02004                    char *buf, size_t buflen)
02005 {
02006         const char *name;
02007         if (conn == NULL || conn->ssl == NULL)
02008                 return -1;
02009 
02010         name = SSL_get_cipher(conn->ssl);
02011         if (name == NULL)
02012                 return -1;
02013 
02014         snprintf(buf, buflen, "%s", name);
02015         return 0;
02016 }
02017 
02018 
02019 int tls_connection_enable_workaround(void *ssl_ctx,
02020                                      struct tls_connection *conn)
02021 {
02022         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
02023 
02024         return 0;
02025 }
02026 
02027 
02028 #ifdef EAP_FAST
02029 /* ClientHello TLS extensions require a patch to openssl, so this function is
02030  * commented out unless explicitly needed for EAP-FAST in order to be able to
02031  * build this file with unmodified openssl. */
02032 int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
02033                                     int ext_type, const u8 *data,
02034                                     size_t data_len)
02035 {
02036         if (conn == NULL || conn->ssl == NULL)
02037                 return -1;
02038 
02039         if (SSL_set_hello_extension(conn->ssl, ext_type, (void *) data,
02040                                     data_len) != 1)
02041                 return -1;
02042 
02043         return 0;
02044 }
02045 #endif /* EAP_FAST */
02046 
02047 
02048 int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
02049 {
02050         if (conn == NULL)
02051                 return -1;
02052         return conn->failed;
02053 }
02054 
02055 
02056 int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
02057 {
02058         if (conn == NULL)
02059                 return -1;
02060         return conn->read_alerts;
02061 }
02062 
02063 
02064 int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
02065 {
02066         if (conn == NULL)
02067                 return -1;
02068         return conn->write_alerts;
02069 }
02070 
02071 
02072 int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
02073                               const struct tls_connection_params *params)
02074 {
02075         int ret;
02076         unsigned long err;
02077 
02078         if (conn == NULL)
02079                 return -1;
02080 
02081         while ((err = ERR_get_error())) {
02082                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
02083                            __func__, ERR_error_string(err, NULL));
02084         }
02085 
02086         if (tls_connection_set_subject_match(tls_ctx, conn,
02087                                              params->subject_match,
02088                                              params->altsubject_match))
02089                 return -1;
02090         if (tls_connection_ca_cert(tls_ctx, conn, params->ca_cert,
02091                                    params->ca_cert_blob,
02092                                    params->ca_cert_blob_len,
02093                                    params->ca_path))
02094                 return -1;
02095         if (tls_connection_client_cert(tls_ctx, conn, params->client_cert,
02096                                        params->client_cert_blob,
02097                                        params->client_cert_blob_len))
02098                 return -1;
02099 
02100         if (params->engine) {
02101                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
02102                 ret = tls_engine_init(conn, params->engine_id, params->pin,
02103                                       params->key_id);
02104                 if (ret)
02105                         return ret;
02106                 if (tls_connection_engine_private_key(tls_ctx, conn))
02107                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
02108         } else if (tls_connection_private_key(tls_ctx, conn,
02109                                               params->private_key,
02110                                               params->private_key_passwd,
02111                                               params->private_key_blob,
02112                                               params->private_key_blob_len)) {
02113                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
02114                            params->private_key);
02115                 return -1;
02116         }
02117 
02118         if (tls_connection_dh(tls_ctx, conn, params->dh_file)) {
02119                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
02120                            params->dh_file);
02121                 return -1;
02122         }
02123 
02124         tls_get_errors(tls_ctx);
02125 
02126         return 0;
02127 }
02128 
02129 
02130 int tls_connection_get_keyblock_size(void *tls_ctx,
02131                                      struct tls_connection *conn)
02132 {
02133         const EVP_CIPHER *c;
02134         const EVP_MD *h;
02135 
02136         if (conn == NULL || conn->ssl == NULL ||
02137             conn->ssl->enc_read_ctx == NULL ||
02138             conn->ssl->enc_read_ctx->cipher == NULL ||
02139             conn->ssl->read_hash == NULL)
02140                 return -1;
02141 
02142         c = conn->ssl->enc_read_ctx->cipher;
02143         h = conn->ssl->read_hash;
02144 
02145         return 2 * (EVP_CIPHER_key_length(c) +
02146                     EVP_MD_size(h) +
02147                     EVP_CIPHER_iv_length(c));
02148 }
02149 

Generated on Sat May 6 21:13:39 2006 for wpa_supplicant by  doxygen 1.4.2