Replace Windows APIs that are banned in Windows Store apps

CryptGenRandom and lstrlenW are not permitted in Windows Store apps,
meaning apps that use mbedTLS can't ship in the Windows Store.
Instead, use BCryptGenRandom and wcslen, respectively, which are
permitted.

Also make sure conversions between size_t, ULONG, and int are
always done safely; on a 64-bit platform, these types are different
sizes.

Also suppress macro redefinition warning for intsafe.h:

Visual Studio 2010 and earlier generates C4005 when including both
<intsafe.h> and <stdint.h> because a number of <TYPE>_MAX constants
are redefined. This is fixed in later versions of Visual Studio.
The constants are guaranteed to be the same between both files,
however, so we can safely suppress the warning when including
intsafe.h.

Signed-off-by: Kevin Kane <kkane@microsoft.com>
This commit is contained in:
Kevin Kane 2016-12-15 09:27:16 -08:00 committed by Minos Galanakis
parent 87fe99627f
commit 0ec1e68548
9 changed files with 73 additions and 12 deletions

View file

@ -50,26 +50,41 @@
#include <windows.h>
#if _WIN32_WINNT >= 0x0501 /* _WIN32_WINNT_WINXP */
#include <wincrypt.h>
#include <bcrypt.h>
#if _MSC_VER <= 1600
/* Visual Studio 2010 and earlier issue a warning when both <stdint.h> and <intsafe.h> are included, as they
* redefine a number of <TYPE>_MAX constants. These constants are guaranteed to be the same, though, so
* we suppress the warning when including intsafe.h.
*/
#pragma warning( push )
#pragma warning( disable : 4005 )
#endif
#include <intsafe.h>
#if _MSC_VER <= 1600
#pragma warning( pop )
#endif
int mbedtls_platform_entropy_poll(void *data, unsigned char *output, size_t len,
size_t *olen)
{
HCRYPTPROV provider;
ULONG len_as_ulong = 0;
((void) data);
*olen = 0;
if (CryptAcquireContext(&provider, NULL, NULL,
PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) {
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
/*
* BCryptGenRandom takes ULONG for size, which is smaller than size_t on 64-bit platforms.
* Ensure len's value can be safely converted into a ULONG.
*/
if ( FAILED( SizeTToULong( len, &len_as_ulong ) ) )
{
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
if (CryptGenRandom(provider, (DWORD) len, output) == FALSE) {
CryptReleaseContext(provider, 0);
return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
if ( !BCRYPT_SUCCESS( BCryptGenRandom( NULL, output, len_as_ulong, BCRYPT_USE_SYSTEM_PREFERRED_RNG ) ) )
{
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
CryptReleaseContext(provider, 0);
*olen = len;
return 0;