Can't run sha256 more than once in intel sgx enclave - c++

So I'm trying to create two sha256 hashes in intel sgx using their cyrpto library. Currently, if I run the following:
sgx_sha256_hash_t *hash1;
int first = 1;
sgx_status_t = stat;
stat = sgx_sha256_msg( ( uint8_t * ) &first, 8, hash1 );
I have no problems, and I properly get hash1, however if I try
sgx_sha256_hash_t *hash1;
sgx_sha256_hash_t *hash2;
int first = 1;
int second = 2;
sgx_status_t = stat;
stat = sgx_sha256_msg( ( uint8_t * ) &first, 8, hash1 );
stat = sgx_sha256_msg( ( uint8_t * ) &second, 8, hash2 );
I get a segmentation fault. I tried doing this with the sha init, update, get_hash and close method instead, but with no imporved results, does anyone know why this might be? I was thinking I might be running out of memory in the enclave, if that's true, is there a way to expand my enclave?

You are writing your hashes to a random location in memory through those two uninitialised pointers, hence the segfaults. Also, your src_len parameters are incorrect, and for completeness the first parameter should be const.
So, what you want is:
sgx_sha256_hash_t hash1; // note: no asterisk
sgx_sha256_hash_t hash2;
int first = 1;
int second = 2;
sgx_status_t = stat;
stat = sgx_sha256_msg( ( const uint8_t * ) &first, sizeof (first), &hash1 );
stat = sgx_sha256_msg( ( const uint8_t * ) &second, sizeof (second), &hash2 );

Related

How to compress/decompress buffer using Fast-LZMA2

I want to compress/decompress a unsigned char buffer using fast-LZMA2 by 7Zip : https://github.com/conor42/fast-lzma2
In the sample there's two function :
static int compress_file(FL2_CStream *fcs)
{
unsigned char in_buffer[8 * 1024];
unsigned char out_buffer[4 * 1024];
FL2_inBuffer in_buf = { in_buffer, sizeof(in_buffer), sizeof(in_buffer) };
FL2_outBuffer out_buf = { out_buffer, sizeof(out_buffer), 0 };
size_t res = 0;
size_t in_size = 0;
size_t out_size = 0;
do {
if (in_buf.pos == in_buf.size) {
in_buf.size = fread(in_buffer, 1, sizeof(in_buffer), fin);
in_size += in_buf.size;
in_buf.pos = 0;
}
res = FL2_compressStream(fcs, &out_buf, &in_buf);
if (FL2_isError(res))
goto error_out;
fwrite(out_buf.dst, 1, out_buf.pos, fout);
out_size += out_buf.pos;
out_buf.pos = 0;
} while (in_buf.size == sizeof(in_buffer));
do {
res = FL2_endStream(fcs, &out_buf);
if (FL2_isError(res))
goto error_out;
fwrite(out_buf.dst, 1, out_buf.pos, fout);
out_size += out_buf.pos;
out_buf.pos = 0;
} while (res);
fprintf(stdout, "\t%ld -> %ld\n", in_size, out_size);
return 0;
error_out:
fprintf(stderr, "Error: %s\n", FL2_getErrorName(res));
return 1;
}
static int decompress_file(FL2_DStream *fds)
{
unsigned char in_buffer[4 * 1024];
unsigned char out_buffer[8 * 1024];
FL2_inBuffer in_buf = { in_buffer, sizeof(in_buffer), sizeof(in_buffer) };
FL2_outBuffer out_buf = { out_buffer, sizeof(out_buffer), 0 };
size_t res;
size_t in_size = 0;
size_t out_size = 0;
do {
if (in_buf.pos == in_buf.size) {
in_buf.size = fread(in_buffer, 1, sizeof(in_buffer), fout);
in_size += in_buf.size;
in_buf.pos = 0;
}
res = FL2_decompressStream(fds, &out_buf, &in_buf);
if (FL2_isError(res))
goto error_out;
/* Discard the output. XXhash will verify the integrity. */
out_size += out_buf.pos;
out_buf.pos = 0;
} while (res && in_buf.size);
fprintf(stdout, "\t%ld -> %ld\n", in_size, out_size);
return 0;
error_out:
fprintf(stderr, "Error: %s\n", FL2_getErrorName(res));
return 1;
}
But I have no idea how to make it work with a buffer and also without size limit like 8*1024
like zlib deflate compression.
I want something like
LZMA2_Compress(void* buffer,size_t bufferSize);
and LZMA2_Decompress(void* buffer,size_t bufferSize);
I want to use this algorithm on some heavy files and Fast LZMA2 is the fastest high ratio compression I found, Please don't suggest me using other methods.
Here's my test code, It's working but just need to correct information:
https://gist.github.com/Bit00009/3241bb66301f8aaba16074537d094e61
Check the header file for all of the functions available. This one looks like the one you need. You will need to cast your buffers as (void *).
High level functions
fast-lzma2.h
...
/*! FL2_compress() :
* Compresses `src` content as a single LZMA2 compressed stream into already allocated `dst`.
* Call FL2_compressMt() to use > 1 thread. Specify nbThreads = 0 to use all cores.
* #return : compressed size written into `dst` (<= `dstCapacity),
* or an error code if it fails (which can be tested using FL2_isError()). */
FL2LIB_API size_t FL2LIB_CALL FL2_compress(void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
int compressionLevel);
...
Management of memory and options
To do explicit memory management (set dictionary size, buffer size, etc.) you need to create a context:
fast-lzma2.h
/*= Compression context
* When compressing many times, it is recommended to allocate a context just once,
* and re-use it for each successive compression operation. This will make workload
* friendlier for system's memory. The context may not use the number of threads requested
* if the library is compiled for single-threaded compression or nbThreads > FL2_MAXTHREADS.
* Call FL2_getCCtxThreadCount to obtain the actual number allocated. */
typedef struct FL2_CCtx_s FL2_CCtx;
FL2LIB_API FL2_CCtx* FL2LIB_CALL FL2_createCCtx(void);
than you can use FL2_CCtx_setParameter() to set the parameters in the context. The possible values for the paramters are listed in FL2_cParameter , and the value FL2_p_dictionarySize will allow you to set the dictionary size.
/*! FL2_CCtx_setParameter() :
* Set one compression parameter, selected by enum FL2_cParameter.
* #result : informational value (typically, the one being set, possibly corrected),
* or an error code (which can be tested with FL2_isError()). */
FL2LIB_API size_t FL2LIB_CALL FL2_CCtx_setParameter(FL2_CCtx* cctx, FL2_cParameter param, size_t value);
Finally you can compress the buffer by calling FL2_compressCCtx()
/*! FL2_compressCCtx() :
* Same as FL2_compress(), but requires an allocated FL2_CCtx (see FL2_createCCtx()). */
FL2LIB_API size_t FL2LIB_CALL FL2_compressCCtx(FL2_CCtx* cctx,
void* dst, size_t dstCapacity,
const void* src, size_t srcSize,
int compressionLevel);

What wrong I have done? The function of GetDiskFreeSpaceExA didn't work at all

I tried to use GetDiskFreeSpaceExA function, but it doesn't work:
int drvNbr = PathGetDriveNumber(db7zfolderw);
if (drvNbr == -1) // fn returns -1 on error
{
const char * errmsg = "error occured during get drive number";
strcpy_s(retmsg, strlen(errmsg) + 1, errmsg);
return -3;
}
char driverletter = (char)(65 + drvNbr);
string driverstr(1, driverletter);
driverstr = driverstr + ":";
PULARGE_INTEGER freespace = 0;
PULARGE_INTEGER totalnumbtype = 0;
PULARGE_INTEGER totalnumberfreebyte = 0;
fileSize = SzArEx_GetFileSize(&db, i);
BOOL myresult=GetDiskFreeSpaceExA(
driverstr.c_str(),
freespace,
totalnumbtype,
totalnumberfreebyte
);
The value of variable freespace is 0. I have no idea why it didn't work if the value of variable which is driverstr.c_str() was D:?
Thanks for your help.
You need to supply pointers to variables that will hold the value returned. Right now you a re supplying null pointers so nothing is retured:
::ULARGE_INTEGER freespace{};
::ULARGE_INTEGER totalnumbtype{};
::ULARGE_INTEGER totalnumberfreebyte{};
::BOOL myresult
{
::GetDiskFreeSpaceExA
(
driverstr.c_str()
, &freespace
, &totalnumbtype
, &totalnumberfreebyte
)
};
It would also be a good idea to use wide char versions of these functions.

A function to display contents of 1 or 2 dimensional array of any type

I needed to be able to display the contents of my various arrays (for debugging purposes at this point), and decided to write a function to help me with that. This is what I came up with.
The goal is to be able to display any type of incoming array (int, double, etc).
Because I never had any official programming training, I am wondering if what I have is too "inelegant" and could be improved by doing something obvious to a good computer science person, but not so to a layperson.
int
DisplayArrayInDebugWindow(
void** incoming_array,
char* array_type_str,
int array_last_index_dim_size,
int array_terminator,
HWND handle_to_display_window,
wchar_t* optional_array_name )
{
wchar_t message_bufferw[1000];
message_bufferw[0] = L'\0';
wchar_t temp_buffer[400];
if ( array_last_index_dim_size == 0 ) { array_last_index_dim_size = 1; }
// ----------------------------------------------------------------------------
// Processing for "int" type array
// ----------------------------------------------------------------------------
if ( 0 == (strcmp( array_type_str, "int" )) )
{
int j = 0;
swprintf( temp_buffer, L"%s\r\n", optional_array_name );
wcscat( message_bufferw, temp_buffer );
for ( int i = 0; ((int)(*((int*)( (int)incoming_array + i * (int)sizeof(int) * array_last_index_dim_size + j * (int)sizeof(int))))) != array_terminator; i++ )
{
swprintf( temp_buffer, L"%02i:\t", i );
wcscat( message_bufferw, temp_buffer );
for ( j; j < last_array_dim_size; j++ )
{
swprintf( temp_buffer, L"%i\t", ((int)(*((int*)( (int)incoming_array + i * (int)sizeof(int) * array_last_index_dim_size + j * (int)sizeof(int) )))) ); //
wcscat( message_bufferw, temp_buffer );
}
wcscat( message_bufferw, L"\r\n" );
// --------------------------------------------------------------------
// reset j to 0 each time
// --------------------------------------------------------------------
j = 0;
}
swprintf( temp_buffer, L"\nEnd of Array\n" );
wcscat( message_bufferw, temp_buffer );
SetWindowText( handle_to_display_window, message_bufferw );
}
return 0;
}
NB: When I pass in "incoming array", I type cast it as (void**) obviously.
When the data type changes but the algorithm doesn't, it's time to consider using templates.
template<class Element_Type>
print_array(Element_Type const * p_begin,
Element_Type const * p_end)
{
while (p_begin != p_end)
{
cout << *p_begin;
++p_begin;
}
}
The conversion from single dimension to multiple dimension is left as an exercise to the OP and readers.
Edit 1: Another alternative
At some point, the output function will need information about how to print the information you gave it.
One option is for you to write your own printf function that has format specifiers for the data you send it.
While another option is to pass a pointer to a function that prints the data.
The fundamental issue is that the output function needs to know how to print the data.
For C++, I suggest overriding operator<< in the class / structure. Since the class/structure knows the data, it can easily know how to print the data.

Need to convert cstring to byte* and need to pass it as an i/p argument in c++ functions

In SendCompressedString(),
*passing the compressed data string as an i/p argument.
*Tried printing the whole compressed data in a console window.Can able to print it in the console window....
*Now i need to convert that whole data to Byte * and sizeof that data as an i/p argument to SendBytes()
bool NetOutputBuffer_c::SendCompressedString ( std::string sStr )
{
std::cout.write(sStr.c_str(), sStr.size());
SendInt ( sStr.size() );
return SendBytes ( sStr.c_str(), sStr.size() );
}
In SendBytes(),
Tried to print the pBuf data but can able to print only 5% of data...
what shall i need to do inorder to print the whole data?
bool NetOutputBuffer_c::SendBytes ( const void * pBuf, int iLen )
{
BYTE * pMy = (BYTE*)pBuf;
printf("pMy is %s\n",pMy);
while ( iLen>0 && !m_bError )
{
int iLeft = m_iBufferSize - ( m_pBufferPtr-m_pBuffer );
printf("iLeft is %d\n",iLeft);
if ( iLen<=iLeft )
{
printf("iLen is %d\n",iLen);
memcpy ( m_pBufferPtr, pMy, iLen );
printf("m_pBuffer is %s\n",(char*)m_pBufferPtr);
m_pBufferPtr += iLen;
break;
}
ResizeIf ( iLen );
}
return !m_bError;
}
Requirement::
In SendCompressedString(),
*Need to convert the whole data into Byte * and send it as an i/p argument to SendBytes()
*In SendBytes(),need to print all the data...
*Can someone please help me to achieve this?
Why are you doing the memcpy in a loop? That looks wrong to me. Here is the memcpy reference:
http://www.cplusplus.com/reference/cstring/memcpy/
So you just need to specify a source and destination pointer (address) and what size to copy. So your code should be:
bool NetOutputBuffer_c::SendBytes ( const void * pBuf, int iLen )
{
BYTE * pMy = (BYTE*)pBuf;
memcpy ( m_pBufferPtr, pMy, iLen );
}

Resource instead of external file C++

I am reusing some old code(originally developed on c, not c++) with some functions to open/read/manipulate text-files. The path to the text-files is passed to the functions as a string (char*) then opened using: FileToUse = fopen(filename, "rb"); then multiple calls to fread() and fseek() are used. This code is known to work for external text-files, but now I would like to include the textfiles as resources in my project (MFC C++ in visual studio).
I found some examples on the web on how to use resources rusulting in this code:
HINSTANCE hInst = AfxGetResourceHandle();
HRSRC hResource = FindResource(hInst, MAKEINTRESOURCE(IDR_TEXTFILE1), "TEXTFILE");
if (hResource){
HGLOBAL hLoadedResource = LoadResource(hInst, hResource);
if (hLoadedResource){
const char* pResource = LockResource(hLoadedResource);
if (pResource){
DWORD dwResourceSize = SizeofResource(hInst, hResource);
if (0 != dwResourceSize){ // if(FileToUse){
memcpy(&Buffer, pResource, (15 * 2)); // fread($Buffer, 15, 2, FileToUse);
pTemp = pResource + 200; // fseek(FileToUse, 200, SEEK_SET);
pTemp = pTemp + 100; // fseek(FileToUse, 100, SEEK_CUR);
pTemp = pResource + (dwResourceSize - 1) - 40; // fseek(FileToUse, -40, SEEK_END);
}
}
}
}
I replaced the fread call by memcpy() as shown, but I'm missing the return value of fread (actual read items) and in the original code the filepointer was moved by fseek, I wonder whether my approach using a temporary pointer is correct.
My ultimate goal is to simulate the fread and fseek calls for resources with similar function prototypes:
size_t resread( void* buffer, size_t size, size_t count, char* resource );
int resseek( char* resource, long offset, int origin );
Any suggestions are much appreciated.
Thanks for your help, based on the Agent_L's suggestion this is what I came up with:
Text-resource type:
struct _resource {
const char * content; // File content
size_t size; // File size
size_t ptrloc; // 'Pointer' location
};
typedef struct _resource RES_TXT;
resread based on fread:
size_t resread( void* buffer, size_t size, size_t count, RES_TXT * resource)
{
size_t actualCount = ( resource->size - resource->ptrloc ) / size;
actualCount = min( count, actualCount );
if ( actualCount <= 0 ) return 0;
memcpy(buffer, (resource->_ptr + resource->ptrloc), (actualCount * size) );
resource->ptrloc += (actualCount * size);
return actualCount;
}
and to complete resseek based on fseek:
int resseek( RES_TXT * resource, long offset, int origin ) {
size_t nextloc;
switch ( origin ) {
case SEEK_SET: nextloc = 0;
break;
case SEEK_CUR: nextloc = resource->ptrloc;
break;
case SEEK_END: nextloc = resource->size;
break;
default: return -1;
}
nextloc += offset;
if ( nextloc >= 0 && nextloc < resource->size )
resource->ptrloc = nextloc;
else
return -1;
return 0;
}
Any call to fseek and fread can now be replaced to use a resource instead of an external file.
The file handle contains not only the data but also it's length and current position. You have to duplicate that.
(handwirtten code, unproven):
struct resFile
{
char* pData;
int iLenght;
int iCurrPosition;
};
size_t resread( void* buffer, size_t size, size_t count, resFile* resource)
{
int ActualRead = min(size*count, resource->iLenght - resource->iCurrPosition);
memcpy(buffer, resource->pData + resource->iCurrPosition, ActualRead);
resource->iCurrPostion += ActualRead;
return ActualRead;
}
Let me notify you that fread shifts current file position. This means that you don't need invoke fseek each time. From this perspective may be you code can avoid implementation of resseek by simple increasing Buffer pointer