mbedtls: error on mbedtls_ctr_drbg_seed - c

I'm using mbedtls to run SSL server.
The function mbedtls_ctr_drbg_seed returned -34.
My code is below:
const char *pers = "ssl_server2";
mbedtls_havege_state hs;
mbedtls_ssl_session ssn;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
// One HTTPS Request Handling
memset( &ssn, 0, sizeof( mbedtls_ssl_session ) );
/*
* 4. Setup stuff
*/
mbedtls_ssl_init( &ssl );
mbedtls_ssl_config_init( &conf );
mbedtls_ctr_drbg_init( &ctr_drbg );
mbedtls_entropy_init( &entropy );
printf( " . Setting up the RNG and SSL data...." );
if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *) pers, sizeof( pers ) ) ) != 0 )
{
printf( " failed\n ! mbedtls_ctr_drbg_seed returned -0x%x\n", -ret );
goto ExitFunction;
}
else
printf( " mbedtls_ctr_drbg_seed returned 0x%x ok\n", ret );

As #Gilles rightfully said, the error you are receiving is probably -0x34, which is MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED. This error is returned when the function mbedtls_entropy_func() fails. Please check the the entropy source you are using is strong enough, meaning you have at least one entropy source which is strong, when added with mbedtls_entropy_add_source(). You should also verify that the entropy source you are using can collect enough entropy, and exceeds the threshold set to the source.
There are other locations where mbedtls_entropy_func() might fail, therefore I suggest you check these locations as well.

Related

How to get data from POST/GET method in a C program?

I want to write a simple program that takes data from forms via POST OR GET. A simple form lets say for adding two numbers.
I saw that libcurl is capable of talking with http protocol but I did not see any example related to this question.
All i saw is how to send data to webpage but not how to get it.
Thank you for your time.
Quick-n-dirty, very untested example based on another project of mine - no warranties express or implied. This assumes that the binary has properly been deployed on the Web server (for example, under the cgi-bin directory on an Apache server) and that the input form has been set up to call it properly:
<form action="http://my-url.com/cgi-bin/adder" method="get"> <!-- or method="post" -->
<label for="v1">V1:</label><input type="text" name="v1"><br>
<label for="v2">V2:</label><input type="text" name="v2"><br>
<input type="submit" name="submitbutton" value="Add">
</form>
Then your C code will look something like
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
char *interface = getenv( "GATEWAY_INTERFACE" );
/**
* If interface is NULL, then we were not invoked through CGI.
* For this example we just fail silently.
*/
if ( !interface )
exit( EXIT_FAILURE );
char *method = getenv( "REQUEST_METHOD" );
/**
* If method is NULL, then we were not invoked through CGI;
* for this example we'll just fail silently
*/
if ( !method )
exit( EXIT_FAILURE );
if ( strcmp( method, "GET" ) == 0 )
{
/**
* We were invoked from a Web client with the HTTP GET method -
* input parameters will be in the QUERY_STRING environment
* variable as "param=value&param=value"
*/
char *query_string = getenv( "QUERY_STRING" );
do_stuff_with( query_string );
}
else if ( strcmp( method, "POST" ) == 0 )
{
/**
* We were invoked from a Web client with the HTTP POST method -
* input parameters will be received via standard input
*/
char query_string[SOME_SIZE];
if ( fgets( query_string, sizeof query_string, stdin ) )
{
do_stuff_with( query_string );
}
else
// handle error
}
else
{
/**
* Input method is not GET or POST, log an error and fail
*/
fputs( "Don't know how to handle this request\n", stderr );
exit( EXIT_FAILURE );
}
}
Any response back to the Web client will be written through standard output:
printf( "Content-type: text/html\r\n\r\n" );
printf( "<!DOCTYPE HTML><html><head><title>Adder result</title></head>" );
printf( "<body><p>Result of add is %d</p></body></html>", add_result );

MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED

im trying to code a Diffie-Hellman key Exchange (client side) into a XMC4500 and I'm using ARMmbed lib.
This is the code I got (based on dh_client.c):
int dhm (void)
{
int ret;
size_t n, buflen;
unsigned char *p, *end;
unsigned char buf[512];
unsigned char hash[32];
const char *pers = "dh_client";
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_rsa_context rsa;
mbedtls_dhm_context dhm;
mbedtls_aes_context aes;
mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256 );
mbedtls_dhm_init( &dhm );
mbedtls_aes_init( &aes );
mbedtls_ctr_drbg_init( &ctr_drbg );
/*
* 1. Setup the RNG
*/
mbedtls_entropy_init( &entropy );
ret = mbedtls_ctr_drbg_seed( &ctr_drbg,
mbedtls_entropy_func,
&entropy,
(const unsigned char *) pers,
strlen( pers ) );
mbedtls_aes_free( &aes );
mbedtls_rsa_free( &rsa );
mbedtls_dhm_free( &dhm );
mbedtls_ctr_drbg_free( &ctr_drbg );
mbedtls_entropy_free( &entropy );
return ret;}
I did not try to go further this, because it is not working and it is the very beginning of dhm algorithm. The function mbedtls_ctr_drbg_seed is returning MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED.
Also in the ctr_drbg.h I had to edit the MBEDTLS_CTR_DRBG_MAX_SEED_INPUT from 384(default) to 336, otherwise the code would crash. Everything else is default.
Someone knows why is returning this error?
Thanks in advance.
Note: Im calling this function in main. Running the code gives me no errors.
This error is returned when your entropy function(mbedtls_entropy_func) fails. Do you have an entropy source enabled? You probably don't have any strong entropy source configured in your platform, thus causing this failure.

fgetpos failing in iOS 6.1 simulator when opening files in bundles

I'm working on some multiplatform C++ code. Hence the requirement to use fopen, fgetpos, etc. The following was working earlier on iOS and with my update to the latest version it stopped working.
I have a couple of text files Shader.vsh and Shader.fsh in a Shaders folder that is getting copied over to the bundle. In order to open the file, I do the following..
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFStringRef cfstrFilename = CFSTRFromConstCharPtr( "Shader" );
CFStringRef cfstrFileType = CFSTRFromConstCharPtr( "vsh" );
CFStringRef cfstrSubDir = CFSTRFromConstCharPtr( "Shaders" );
CFURLRef resourcesURL = CFBundleCopyResourceURL( mainBundle, cfstrFilename, cfstrFileType, cfstrSubDir );
CFStringRef str = CFURLCopyFileSystemPath( resourcesURL, kCFURLPOSIXPathStyle );
CFRelease( resourcesURL );
char path[ PATH_MAX ];
CFStringGetCString( str, path, FILENAME_MAX, kCFStringEncodingASCII );
CFRelease( str );
FILE* fp = fopen( path, "rb" );
At this point, fp is Non NULL. So I assume it succeeded. Later, when I try to do
fpos_t pos;
int result = fgetpos( fp, &fpos_t );
result = -1 and errno = 0x2, which I believe is file not found.
As I mentioned earlier, this used to work on a previous version at some point. I started working on this again and in the process updated to the latest XCode, etc and things stopped working.
The path for the file that I pass into fopen turns out to be /Users/shammi/Library/Application Support/iPhone Simulator/6.1/Applications/9132490F-71AC-4C61-A584-E8F6C5B261FF/TestApp.app/Shaders/Shader.vsh
I'm able to see and open that file in finder/console and confirmed that its valid.
What am I doing wrong? Is there another alternative that allows me to use portable IO functions?
Found the problem. What I failed to mention here is what happens between the 2 sections of code above. Prior to this, I used to have my own ref counting solution and I recently changed to using shared_ptr. My own ref counting solution allowed for implicit casts. With shared_ptr, you can't do that. So here is the exact code...
std::shared_ptr< BinaryStream > BundleNamespace::OpenStream( const char* _szPath,
BinaryStream::Mode _eMode )
{
std::shared_ptr< BinaryStream > pStream = __super::OpenStream( _szPath, _eMode );
if ( !pStream )
{
std::string strDir;
std::string strFile;
std::string strExt;
SplitPath( _szPath, strDir, strFile, strExt );
std::string strFullPath = GetResourcePathFor( strFile.c_str(), strExt.c_str(), strDir.c_str() );
FILE* fp = fopen( strFullPath.c_str(), _eMode == BinaryStream::Mode_Read ? "r" : "w+b" );
pStream = std::make_shared<FileStream>( fp, _eMode );
}
return pStream;
}
The problem here is with
pStream = std::make_shared<FileStream>( fp, _eMode );
My FileStream's destructor calls fclose(m_pFile). The fix here is to change it to..
pStream = std::static_pointer_cast< BinaryStream >( std::make_shared<FileStream>( fp, _eMode ) );`
Also, using perror() proved to be more useful compared to trying to decipher errno.

How to know the address range when searching for a function by its signature?

I'm trying to search for a function by its "signature".
However I can't figure out what address range I'm supposed to be searching?
I've had a look at VirtualQuery() and GetNativeSystemInfo() but I'm not if I'm on the right path or not.
Edit: Question re-attempt.
Using Win32 API I'm trying to find out how to get the start and end address of the executable pages of the process my code is executing in.
This is what I've tried:
SYSTEM_INFO info;
ZeroMemory( &info, sizeof( SYSTEM_INFO ) );
GetNativeSystemInfo( &info ); // GetSystemInfo() might be wrong on WOW64.
info.lpMinimumApplicationAddress;
info.lpMaximumApplicationAddress;
HANDLE thisProcess = GetCurrentProcess();
MEMORY_BASIC_INFORMATION memInfo;
ZeroMemory( &memInfo, sizeof( memInfo ) );
DWORD addr = (DWORD)info.lpMinimumApplicationAddress;
do
{
if ( VirtualQueryEx( thisProcess, (LPVOID)addr, &memInfo, sizeof( memInfo ) ) == 0 )
{
DWORD gle = GetLastError();
if ( gle != ERROR_INVALID_PARAMETER )
{
std::stringstream str;
str << "VirtualQueryEx failed with: " << gle;
MessageBoxA( NULL, str.str().c_str(), "Error", MB_OK );
}
break;
}
if ( memInfo.Type == MEM_IMAGE )
{
// TODO: Scan this memory block for the the sigature
}
addr += info.dwPageSize;
}
while ( addr < (DWORD)info.lpMaximumApplicationAddress );
The reason for doing this is that I'm looking for an un-exported function by its signature as asked here:
Find a function by it signature in Windows DLL
See the answer about "code signature scanning".
While this is enumerating an address range I don't know if this is correct or not since I don't know what the expected range should be. Its just the best I could come up with from looking around MSDN.
the address range when signature scanning a module is from the start of the code section to the start + the section size. the start of the code section and its size are in the PE. most tools take the lazy route and scan the entire module (again using the PE to get the size, but with the module handle as the start address).

How to get a sha256 hash of a file using ANSI C

Simply what the topic states, what's a memory efficient way to compute a sha256 hash of a file that's variable in size? I'm also willing to compromise using more memory for faster computation.
I used a simple stand-alone implementation by Christophe Devine -- and while his site seems to be off the Net, Google Code Search finds it
in this place.
Using these sha256.c and sha256.h, the core of his main() function is simply
if( ! ( f = fopen( argv[1], "rb" ) ) )
{
perror( "fopen" );
return( 1 );
}
sha256_starts( &ctx );
while( ( i = fread( buf, 1, sizeof( buf ), f ) ) > 0 )
{
sha256_update( &ctx, buf, i );
}
sha256_finish( &ctx, sha256sum );
for( j = 0; j < 32; j++ )
{
printf( "%02x", sha256sum[j] );
}
printf( " %s\n", argv[1] );
}
The rest of the main() function validates the FIPS-180-2 test vectors, so you get that warm and fuzzy feeling too/ ;-)
Or use the OpenSSL libcrypto:
https://wiki.openssl.org/index.php/EVP_Message_Digests
You may try Con Kolivas's implementation used in multi-threaded multi-pool FPGA and ASIC miner for bitcoin or well profiled Dr Brian Gladman's code.

Resources