virtual bool start() = 0;\r
virtual void reset() = 0;\r
virtual bool getPropertyValue(PropertyValue&) = 0;\r
+ void setPropSet(unsigned int propset) {\r
+ this->propset = propset;\r
+ };\r
Property() {\r
}\r
;\r
virtual ~Property() {\r
}\r
;\r
+ unsigned int propset;\r
};\r
\r
#endif /* PROPERTYACCESS_PROPERTY_H_ */\r
#include <PropertyAccess/PropertyUtility.h>\r
#include "config.h"\r
#include <string.h>\r
+#include <set>\r
\r
using namespace std;\r
\r
* @return NULL if handle is invalid else returns valid handle\r
*/\r
static Property* _GetTargetProperty(TEE_PropSetHandle propsetOrEnumerator);\r
+static uint32_t _GetTargetPropsetType(TEE_PropSetHandle propsetOrEnumerator);\r
\r
//GLOBAL DEFNS\r
typedef struct {\r
Property* property;\r
} PropertyEnumHandle;\r
\r
+std::set<PropertyEnumHandle*> propertyEnumHandleSet;\r
+\r
/*-----------------------------------------------------------------------------\r
* Member functions\r
*-----------------------------------------------------------------------------*/\r
delete teeProperty;\r
}\r
\r
+string getQueryProp(TEE_PropSetHandle propsetOrEnumerator, string name) {\r
+ size_t pos;\r
+ uint32_t propSet = _GetTargetPropsetType(propsetOrEnumerator);\r
+ if(propSet == TEE_PROPSET_CURRENT_TA &&\r
+ (pos = name.rfind(".")) != string::npos) {\r
+ return name.substr(pos + 1);\r
+ }\r
+ return name;\r
+}\r
+\r
//TODO: TEE_ERROR_ITEM_NOT_FOUND also to be returned when the string\r
//received in not UTF8 encoded format\r
//Assuming valueBufferLen is [in] param only.\r
return TEE_ERROR_ITEM_NOT_FOUND;\r
}\r
\r
- if (NULL != name) queryProp = string(name);\r
+ if (NULL != name) queryProp = getQueryProp(propsetOrEnumerator, name);\r
// 1. Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(propsetOrEnumerator);\r
Property* targetProperty = NULL;\r
PropertyValue pv;\r
string queryProp = "";\r
- if (NULL != name) queryProp = string(name);\r
+ if (NULL != name) queryProp = getQueryProp(propsetOrEnumerator, name);\r
// 1. Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(propsetOrEnumerator);\r
Property* targetProperty = NULL;\r
PropertyValue pv;\r
string queryProp = "";\r
- if (NULL != name) queryProp = string(name);\r
+ if (NULL != name) queryProp = getQueryProp(propsetOrEnumerator,name);\r
// 1. Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(propsetOrEnumerator);\r
Property* targetProperty = NULL;\r
PropertyValue pv;\r
string queryProp = "";\r
- if (NULL != name) queryProp = string(name);\r
-\r
+ if (NULL != name) queryProp = getQueryProp(propsetOrEnumerator,name);\r
// Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(propsetOrEnumerator);\r
if (targetProperty\r
&& ((NULL != name && targetProperty->getPropertyByName(queryProp, pv))\r
|| (NULL == name && targetProperty->getPropertyValue(pv)))) {\r
-\r
string binaryBlockOut;\r
returnValue = PropertyUtility::convertToBinaryBlock(pv, binaryBlockOut);\r
bool conversionStatus = (returnValue == TEE_SUCCESS) ? true : false;\r
Property* targetProperty = NULL;\r
PropertyValue pv;\r
string queryProp = "";\r
- if (NULL != name) queryProp = string(name);\r
+ if (NULL != name) queryProp = getQueryProp(propsetOrEnumerator,name);\r
// 1. Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(propsetOrEnumerator);\r
Property* targetProperty = NULL;\r
PropertyValue pv;\r
string queryProp = "";\r
- if (NULL != name) queryProp = string(name);\r
+ if (NULL != name) queryProp = getQueryProp(propsetOrEnumerator,name);\r
// 1. Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(propsetOrEnumerator);\r
PropertyEnumHandle *newEnumHandle = new PropertyEnumHandle;\r
newEnumHandle->property = NULL;\r
*enumerator = (TEE_PropSetHandle)newEnumHandle;\r
+ propertyEnumHandleSet.insert(newEnumHandle);\r
} catch (std::bad_alloc &ba) {\r
return TEE_ERROR_OUT_OF_MEMORY;\r
}\r
void TEE_FreePropertyEnumerator(TEE_PropSetHandle enumerator) {\r
PropertyEnumHandle* enumeratorHandle = (PropertyEnumHandle*)enumerator;\r
if (enumeratorHandle) {\r
- delete enumeratorHandle->property;\r
- enumeratorHandle = NULL;\r
- delete enumeratorHandle;\r
+ set<PropertyEnumHandle*>::iterator it = propertyEnumHandleSet.find((PropertyEnumHandle*)enumerator);\r
+ if(it != propertyEnumHandleSet.end())\r
+ {\r
+ propertyEnumHandleSet.erase(it);\r
+ delete enumeratorHandle->property;\r
+ delete enumeratorHandle;\r
+ }\r
+ else {\r
+ TEE_Panic(0);\r
+ }\r
}\r
}\r
\r
void TEE_StartPropertyEnumerator(TEE_PropSetHandle enumerator,\r
TEE_PropSetHandle propSet) {\r
PropertyEnumHandle *newEnumHandle = (PropertyEnumHandle*)enumerator;\r
- switch ((intptr_t)propSet) {\r
+ switch ((uint32_t)propSet) {\r
case TEE_PROPSET_CURRENT_TA: {\r
newEnumHandle->property = new TAProperty(\r
string(TEE_TASTORE_ROOT) + thisTAUUIDGlobal + "-ext/"\r
}\r
}\r
\r
- if (newEnumHandle && newEnumHandle->property) \r
+ newEnumHandle->property->setPropSet((uint32_t)propSet);\r
+ if (newEnumHandle && newEnumHandle->property)\r
newEnumHandle->property->start();\r
}\r
\r
// 1. Select the enumerator object based on propset or consider given enumerator\r
// if any\r
targetProperty = _GetTargetProperty(enumerator);\r
- \r
PropertyEnumHandle* enumeratorHandle = (PropertyEnumHandle*)enumerator;\r
// Check if enumerator and property are valid\r
//if (enumeratorHandle && enumeratorHandle->property) {\r
strncpy((char*)nameBuffer, propName.c_str(), *nameBufferLen);\r
}\r
// item not found or enumerator end has reached\r
- else {\r
- return TEE_ERROR_ITEM_NOT_FOUND;\r
- }\r
- } else {\r
- return TEE_ERROR_ITEM_NOT_FOUND;\r
- }\r
+ else return TEE_ERROR_ITEM_NOT_FOUND;\r
+ } else return TEE_ERROR_ITEM_NOT_FOUND;\r
return TEE_SUCCESS;\r
}\r
\r
&& enumeratorHandle->property->getNextProperty()) {\r
return TEE_SUCCESS;\r
} else return TEE_ERROR_ITEM_NOT_FOUND;\r
+}\r
\r
+uint32_t _GetTargetPropsetType(TEE_PropSetHandle propsetOrEnumerator) {\r
+ switch ((uint32_t)propsetOrEnumerator) {\r
+ case TEE_PROPSET_TEE_IMPLEMENTATION:\r
+ case TEE_PROPSET_CURRENT_CLIENT:\r
+ case TEE_PROPSET_CURRENT_TA:\r
+ return (uint32_t)propsetOrEnumerator;\r
+ }\r
+ set<PropertyEnumHandle*>::iterator it =\r
+ propertyEnumHandleSet.find((PropertyEnumHandle*)propsetOrEnumerator);\r
+ if(it != propertyEnumHandleSet.end()) {\r
+ Property *targetProperty = NULL;\r
+ PropertyEnumHandle *enumHandle =\r
+ (PropertyEnumHandle*)propsetOrEnumerator;\r
+ if (enumHandle && enumHandle->property)\r
+ targetProperty = enumHandle->property;\r
+ return targetProperty->propset;\r
+ }\r
+ return 0;\r
}\r
\r
Property* _GetTargetProperty(TEE_PropSetHandle propsetOrEnumerator) {\r
Property *targetProperty = NULL;\r
- switch ((intptr_t)propsetOrEnumerator) {\r
+ switch ((uint32_t)propsetOrEnumerator) {\r
case TEE_PROPSET_TEE_IMPLEMENTATION: {\r
targetProperty = teeProperty;\r
break;\r
targetProperty = taProperty;\r
break;\r
}\r
-/* default: {\r
- PropertyEnumHandle *newEnumHandle =\r
- (PropertyEnumHandle*)propsetOrEnumerator;\r
-\r
- if (newEnumHandle && newEnumHandle->property) \r
- targetProperty = newEnumHandle->property;\r
- break;\r
+ }\r
+ if(targetProperty == NULL) {\r
+ set<PropertyEnumHandle*>::iterator it =\r
+ propertyEnumHandleSet.find((PropertyEnumHandle*)propsetOrEnumerator);\r
+ if(it != propertyEnumHandleSet.end()) {\r
+ PropertyEnumHandle *enumHandle =\r
+ (PropertyEnumHandle*)propsetOrEnumerator;\r
+ if (enumHandle && enumHandle->property)\r
+ targetProperty = enumHandle->property;\r
}\r
-*/ }\r
+ }\r
return targetProperty;\r
}\r
+\r
string tokensString[8];\r
int i = 0;\r
for (i = 0; i < 8; i++) {\r
- strncpy(&tokensString[i][0], &text[4 * i], 4);\r
+ tokensString[i] = text.substr(4*i, 4);\r
}\r
// convert each token\r
sscanf((tokensString[0] + tokensString[1]).c_str(), "%8x", &uuid.timeLow);\r
* Include files\r
*-----------------------------------------------------------------------------*/\r
#include "tee_internal_api.h"\r
-#include "log.h"\r
+#include <debug.h>\r
#include <PropertyAccess/Property.h>\r
#include <string>\r
#include <sstream>\r
#include <iostream>\r
#include <config.h>\r
#include <string.h>\r
+#include <debug.h>\r
+#include <permission.h>\r
\r
using namespace rapidxml;\r
\r
TAProperty::TAProperty(string filePath) {\r
currentItr = propertiesMap.begin();\r
this->filePath = filePath;\r
-\r
}\r
\r
/**\r
string type;\r
//1a. Get property value\r
newValue.value = attr->value();\r
-\r
+ string typeName = attr->name();\r
//1b. Identify type\r
// TODO: UUID type to be added yet\r
if (PropertyUtility::isNumber(newValue.value)) {\r
type = "integer";\r
} else if (newValue.value == "true" || newValue.value == "false")\r
type = "boolean";\r
+ else if (typeName == "appID")\r
+ type = "uuid";\r
else type = "string";\r
+\r
//1c. Assign type identified\r
newValue.type = type;\r
//2. Assign property value to map\r
propertiesMap[attr->name()] = newValue;\r
}\r
+\r
+ xml_node<> *policyName;\r
+ xml_node<> *permissionName;\r
+ xml_node<> *childnode;\r
+ unsigned int permissionValue = 0;\r
+\r
+ policyName = doc.first_node("manifest")->first_node("policy");\r
+\r
+ if (policyName != NULL) {\r
+ PropertyValue newValue;\r
+ string type = "integer";\r
+\r
+ permissionName = policyName->first_node("permission");\r
+ if(permissionName != NULL) {\r
+ for (childnode = policyName->first_node("permission")->first_node("uses-permission"); childnode; childnode = childnode->next_sibling()) {\r
+ if (!strncmp(childnode->first_attribute()->value(), "system.permission.CRYPTO",\r
+ strlen("system.permission.CRYPTO"))) {\r
+ permissionValue |= PERM_CRYPTO;\r
+ } else if (!strncmp(childnode->first_attribute()->value(), "system.permission.STORAGE",\r
+ strlen("system.permission.STORAGE"))) {\r
+ permissionValue |= PERM_STORAGE;\r
+ } else if (!strncmp(childnode->first_attribute()->value(), "system.permission.DISPLAY",\r
+ strlen("system.permission.DISPLAY"))) {\r
+ permissionValue |= PERM_DISPLAY;\r
+ } else if (!strncmp(childnode->first_attribute()->value(), "system.permission.NETWORK",\r
+ strlen("system.permission.NETWORK"))) {\r
+ permissionValue |= PERM_NETWORK;\r
+ } else if (!strncmp(childnode->first_attribute()->value(), "system.permission.TIME",\r
+ strlen("system.permission.TIME"))) {\r
+ permissionValue |= PERM_TIME;\r
+ } else if (!strncmp(childnode->first_attribute()->value(), "system.permission.ARITHMETIC",\r
+ strlen("system.permission.ARITHMETIC"))) {\r
+ permissionValue |= PERM_ARITHMETIC;\r
+ }\r
+ }\r
+ }\r
+\r
+ std::stringstream ss;\r
+ ss << permissionValue;\r
+ newValue.type = type;\r
+ newValue.value = ss.str();\r
+ propertiesMap["permission"] = newValue;\r
+ }\r
}\r
// Catch rapid xml errors\r
catch (rapidxml::parse_error &e) {\r
* Include files\r
*-----------------------------------------------------------------------------*/\r
#include <PropertyAccess/Property.h>\r
-#include "log.h"\r
+#include <debug.h>\r
#include <map>\r
\r
/*-----------------------------------------------------------------------------\r
*-----------------------------------------------------------------------------*/
#include "tee_sim_command.h"
#include "tee_internal_api.h"
-#include "log.h"
+#include <debug.h>
#include "boost/shared_ptr.hpp"
#include <string>
#include <string.h>
*/
TEE_Result CommandCloseSession::execute() {
TOGGLE_PROPERTY_ACCESS;
- TA_CloseSessionEntryPoint(&sessionContext);
+ TA_CloseSessionEntryPoint(sessionContext);
LOGD(TEE_STUB, "TA_CloseSessionEntryPoint done");
TOGGLE_PROPERTY_ACCESS;
return TEE_SUCCESS;
TOGGLE_PROPERTY_ACCESS;
sharedResult = SharedMemoryMap::allocateSharedMemory(data.op);
if (sharedResult) {
- data.returnValue = TA_InvokeCommandEntryPoint(&sessionContext,
+ data.returnValue = TA_InvokeCommandEntryPoint(sessionContext,
data.commandID, data.op.paramTypes, data.op.params);
LOGD(TEE_STUB, "TA_InvokeCommandEntryPoint done");
} else {
#include <sys/shm.h>
#include <iostream>
#include <string.h>
+#include <time.h>
+#include <stdlib.h>
+#include <debug.h>
using namespace std;
/*-----------------------------------------------------------------------------
#define PAGE_SIZE 0x1000
#define PAGE_MASK (~(PAGE_SIZE - 1))
-map<uint32_t, void*> SharedMemoryMap::shmMap;
+map<uint32_t, registerItem> SharedMemoryMap::shmMap;
/*-----------------------------------------------------------------------------
* Member functions
* @param key[in] Shared memory key
* @param pBuffer[in] Pointer to shared memory
*/
-void SharedMemoryMap::addToMap(const uint32_t key, void* pBuffer) {
- shmMap[key] = pBuffer;
+void SharedMemoryMap::addToMap(const uint32_t key, pRegisterItem reg) {
+ shmMap[key] = *reg;
}
/**
* @return true if successfully detached else false.
*/
bool SharedMemoryMap::deleteFromMap(uint32_t key) {
- map<uint32_t, void*>::iterator it = shmMap.find(key);
+ map<uint32_t, registerItem>::iterator it = shmMap.find(key);
if (it != shmMap.end()) {
- if (-1 != shmdt(it->second)) {
+ registerItem item = it->second;
+ if (-1 != shmdt(item.pBuffer)) {
shmMap.erase(it);
return true;
} else return false;
return false;
}
+/**
+ * Verify that the key exists
+ * @param key[in] Shared memory key
+ * @param reg[out] Pointer to registerItem
+ */
+bool SharedMemoryMap::isExist(uint32_t key, pRegisterItem reg)
+{
+ map<uint32_t, registerItem>::iterator it = shmMap.find(key);
+ if (it != shmMap.end()) {
+ if(reg != 0)
+ *reg = it->second;
+ return true;
+ }
+ return false;
+}
+
+void* SharedMemoryMap::newOnceSharedMemory(uint32_t size) {
+ static uint32_t add_value = 0;
+ if(++add_value == 10000) add_value = 0;
+ srand(time(NULL) + add_value + (uint32_t)&size);
+ uint32_t useKey = rand();
+
+ //uint32_t useKey = (uint32_t)&size;
+ while(isExist(useKey, 0))
+ {
+ LOGD(TEE_STUB, "Exist Key(%u)",useKey);
+ useKey += 1;
+ }
+ LOGD(TEE_STUB, "Key for shm(size : %u) : %u", size, useKey);
+
+ bool sharedResult = true;
+ uint32_t shmid = shmget(useKey, size, IPC_CREAT | 0666);
+ if(shmid <= 0)
+ {
+ LOGE(TEE_STUB, "shmid failed(%d)",(int32_t)shmid);
+ sharedResult = false;
+ }
+ /* Allocate page aligned buffer */
+ if (size < PAGE_SIZE) {
+ size = PAGE_SIZE;
+ } else if (size & (PAGE_SIZE - 1)) {
+ size = (size & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
+ }
+ size = (size + (PAGE_SIZE - 1)) & PAGE_MASK;
+ void* buffer = (void*)shmat(shmid, NULL, 0);
+ if (buffer == (void*)-1) {
+ LOGE(TEE_STUB, "shmat failed(%d(shmid:%d))",(int32_t)buffer, shmid);
+ sharedResult = false;
+ }
+ if (!buffer) {
+ LOGE(TEE_STUB, "allocate failed");
+ sharedResult = false;
+ }
+
+ if(sharedResult != false) {
+ registerItem item;
+ item.pBuffer = buffer;
+ item.size = size;
+ // Add shared memory allocated to shared memory map so that
+ // it can be detached on closing the sessions or exiting the TA
+ SharedMemoryMap::addToMap(useKey, &item);
+ LOGD(TEE_STUB, "newOnceSharedMemory return %p(size:%u)", buffer, size);
+ return buffer;
+ }
+ LOGE(TEE_STUB, "newOnceSharedMemory return NULL");
+ return 0;
+}
+
+bool SharedMemoryMap::deleteOnceSharedMemory(void* buffer) {
+ for (map<uint32_t, registerItem>::iterator it = shmMap.begin(); it != shmMap.end();
+ it++) {
+ registerItem item = it->second;
+ if(buffer == item.pBuffer) {
+ if (-1 != shmdt(item.pBuffer)) {
+ LOGD(TEE_STUB, "deleteOnceSharedMemory return true(%p(%u))",item.pBuffer, item.size);
+ shmMap.erase(it);
+ return true;
+ } else {
+ LOGE(TEE_STUB, "deleteOnceSharedMemory return false(shmdt return fail %p)", buffer);
+ return false;
+ }
+ }
+ }
+ LOGE(TEE_STUB, "deleteOnceSharedMemory return false(can not find %p)", buffer);
+ return false;
+}
+
/**
* Allocates shared memory from a pre-shared key
* @param op Operation values which contain param types and params.
&& (type != TEE_PARAM_TYPE_VALUE_INOUT)
&& (type != TEE_PARAM_TYPE_NONE)) {
uint32_t size = op.params[i].memref.size;
- uint32_t shmid = shmget(op.shmID[i], size, 0666);
-
- //LOGD(TEE_STUB, "SHM KEY: %d SHM ID: %d", op.shmID[i], shmid);
- /* Allocate page aligned buffer */
- if (size < PAGE_SIZE) {
- size = PAGE_SIZE;
- } else if (size & (PAGE_SIZE - 1)) {
- size = (size & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
+ uint32_t offset = op.shmOffset[i];
+ registerItem item;
+ if(SharedMemoryMap::isExist(op.shmID[i], &item))
+ {
+ op.params[i].memref.buffer =
+ (void*)((char*)item.pBuffer + offset);
}
- size = (size + (PAGE_SIZE - 1)) & PAGE_MASK;
- op.params[i].memref.buffer = (void*)shmat(shmid, NULL, 0);
- if (op.params[i].memref.buffer == (void*)-1) {
- LOGE(TEE_STUB, "shmat failed");
- sharedResult = false;
- }
- if (!op.params[i].memref.buffer) {
- LOGE(TEE_STUB, "allocate failed");
- sharedResult = false;
- }
- //memset(op.params[i].memref.buffer, 0x00, size);
+ else
+ {
+ uint32_t shmid = shmget(op.shmID[i], size, 0666);
+ /* Allocate page aligned buffer */
+ if (size < PAGE_SIZE) {
+ size = PAGE_SIZE;
+ } else if (size & (PAGE_SIZE - 1)) {
+ size = (size & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
+ }
+ size = (size + (PAGE_SIZE - 1)) & PAGE_MASK;
+ op.params[i].memref.buffer = (void*)shmat(shmid, NULL, 0);
+ if (op.params[i].memref.buffer == (void*)-1) {
+ LOGE(TEE_STUB, "shmat failed");
+ sharedResult = false;
+ }
+ if (!op.params[i].memref.buffer) {
+ LOGE(TEE_STUB, "allocate failed");
+ sharedResult = false;
+ }
- // Add shared memory allocated to shared memory map so that
- // it can be detached on closing the sessions or exiting the TA
- SharedMemoryMap::addToMap(op.shmID[i], op.params[i].memref.buffer);
+ if(sharedResult != false) {
+ registerItem item;
+ item.pBuffer = op.params[i].memref.buffer;
+ item.size = size;
+ op.params[i].memref.buffer =
+ (void*)(((char*)op.params[i].memref.buffer) + offset);
+ // Add shared memory allocated to shared memory map so that
+ // it can be detached on closing the sessions or exiting the TA
+ SharedMemoryMap::addToMap(op.shmID[i], &item);
+ }
+ }
}
}
return sharedResult;
LOGE(TEE_STUB, "de-allocate failed");
sharedResult = false;
}
- // Add shared memory allocated to shared memory map so that
- // it can be detached on closing the sessions or exiting the TA
- SharedMemoryMap::deleteFromMap(op.shmID[i]);
+ if(sharedResult != false) {
+ // Add shared memory allocated to shared memory map so that
+ // it can be detached on closing the sessions or exiting the TA
+ SharedMemoryMap::deleteFromMap(op.shmID[i]);
+ }
}
}
return sharedResult;
*/
bool SharedMemoryMap::deleteAllSharedMemory() {
bool sharedResult = true;
- for (map<uint32_t, void*>::iterator it = shmMap.begin(); it != shmMap.end();
+ for (map<uint32_t, registerItem>::iterator it = shmMap.begin(); it != shmMap.end();
it++) {
- if (-1 == shmdt(it->second)) {
+ registerItem item = it->second;
+ LOGE(TEE_STUB, "item will be free(%p(%u))",item.pBuffer, item.size);
+ if (-1 == shmdt(item.pBuffer)) {
sharedResult = false;
}
+ LOGE(TEE_STUB, "item will be free end(%p(%u))",item.pBuffer, item.size);
}
return sharedResult;
}
-bool deleteAllSharedMemory() {
- return SharedMemoryMap::deleteAllSharedMemory();
+char* SharedMemoryMap::getSharedMemoryAddress(uint32_t shmID) {
+ for (map<uint32_t, registerItem>::iterator it = shmMap.begin(); it != shmMap.end();
+ it++) {
+ if (it->first == shmID) {
+ registerItem item = it->second;
+ return (char*)item.pBuffer;
+ }
+ }
+ return 0;
+}
+
+uint32_t SharedMemoryMap::getSharedMemoryShmID(void* buffer) {
+ for (map<uint32_t, registerItem>::iterator it = shmMap.begin(); it != shmMap.end();
+ it++) {
+ registerItem item = it->second;
+ if(item.pBuffer == buffer)
+ return it->first;
+ }
+ return 0;
+}
+
+uint32_t SharedMemoryMap::getSharedMemorySize(void* buffer) {
+ for (map<uint32_t, registerItem>::iterator it = shmMap.begin(); it != shmMap.end();
+ it++) {
+ registerItem item = it->second;
+ if(item.pBuffer == buffer)
+ return item.size;
+ }
+ return 0;
+}
+
+void* newOnceSharedMemory(uint32_t size) {
+ return SharedMemoryMap::newOnceSharedMemory(size);
+}
+
+bool deleteOnceSharedMemory(void* buffer) {
+ return SharedMemoryMap::deleteOnceSharedMemory(buffer);
}
bool allocateSharedMemory(Operation &op) {
bool deleteSharedMemory(Operation &op) {
return SharedMemoryMap::deleteSharedMemory(op);
}
+
+bool deleteAllSharedMemory() {
+ return SharedMemoryMap::deleteAllSharedMemory();
+}
+
+char* getSharedMemoryAddress(uint32_t shmID) {
+ return SharedMemoryMap::getSharedMemoryAddress(shmID);
+}
+
+uint32_t getSharedMemoryShmID(void* buffer) {
+ return SharedMemoryMap::getSharedMemoryShmID(buffer);
+}
+
+uint32_t getSharedMemorySize(void* buffer) {
+ return SharedMemoryMap::getSharedMemorySize(buffer);
+}
+
* Include files
*-----------------------------------------------------------------------------*/
#include <map>
-#include "log.h"
#include "tee_internal_api.h"
#include "tee_sim_command.h"
using namespace std;
+typedef struct _registerItem {
+ void* pBuffer;
+ uint32_t size;
+}registerItem, *pRegisterItem;
+
/*-----------------------------------------------------------------------------
* Class definitions
*-----------------------------------------------------------------------------*/
*/
class SharedMemoryMap {
private:
- // map <shared memory key, shared memory buffer pointer>
- static map<uint32_t, void*> shmMap;
- static void addToMap(const uint32_t key, void* shmid);
+ static map<uint32_t, registerItem> shmMap;
+ static void addToMap(const uint32_t key, pRegisterItem reg);
static bool deleteFromMap(uint32_t key);
+ static bool isExist(uint32_t key, pRegisterItem reg);
public:
+ static void* newOnceSharedMemory(uint32_t size);
+ static bool deleteOnceSharedMemory(void* buffer);
static bool allocateSharedMemory(Operation &op);
static bool deleteSharedMemory(Operation &op);
static bool deleteAllSharedMemory();
+ static char* getSharedMemoryAddress(uint32_t shmID);
+ static uint32_t getSharedMemoryShmID(void* buffer);
+ static uint32_t getSharedMemorySize(void* buffer);
};
extern "C" {
+void* newOnceSharedMemory(uint32_t size);
+bool deleteOnceSharedMemory(void* buffer);
bool allocateSharedMemory(Operation &op);
bool deleteSharedMemory(Operation &op);
bool deleteAllSharedMemory();
+char* getSharedMemoryAddress(uint32_t shmID);
+uint32_t getSharedMemoryShmID(void* buffer);
+uint32_t getSharedMemorySize(void* buffer);
}
#endif /* TACOMMANDS_SHAREDMEMORYMAP_H_ */
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: TADebug.cpp
+ *
+ * Description: ta debug function
+ *
+ * Version: 1.0
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: jklolo.lee@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include <stdio.h>
+#include <stdlib.h>
+#include <log_level.h>
+#include <dlog/dlog.h>
+#include <stdarg.h>
+#include <string.h>
+
+#define LOG_LABEL_SIZE 64
+#define LOG_BUFFER_SIZE 4096
+
+static int level = TA_LOG_LEVEL;
+static char log_label[LOG_LABEL_SIZE];
+static char log_one_buffer[LOG_BUFFER_SIZE];
+
+extern "C" void setDebugLogName(const char* __name);
+extern "C" int __logger_log(const char* tag, const usr_log_level lv,
+ const char* fmt, const char* function,
+ const int line, ...)
+{
+ va_list args;
+ int len = 0;
+
+ if(fmt == NULL || function == NULL)
+ return 0;
+
+ if(tag != NULL && strlen(log_label) == 0)
+ setDebugLogName(tag);
+
+ if(level >= lv && level != LOG_SILENT) {
+ log_priority dlog_level = DLOG_DEBUG;
+ switch(lv)
+ {
+ case LOG_DEBUG:
+ dlog_level = DLOG_DEBUG;
+ break;
+ case LOG_INFO:
+ case LOG_NOTICE:
+ dlog_level = DLOG_INFO;
+ break;
+ case LOG_WARNING:
+ dlog_level = DLOG_WARN;
+ break;
+ case LOG_ERR:
+ case LOG_CRIT:
+ case LOG_ALERT:
+ case LOG_EMERG:
+ dlog_level = DLOG_ERROR;
+ break;
+ default:
+ break;
+ }
+
+ va_start(args, line);
+ len = vsnprintf(log_one_buffer, sizeof(log_one_buffer), fmt, args);
+ va_end(args);
+ len += strlen(log_label);
+ dlog_print(dlog_level, log_label, "%s\n", log_one_buffer);
+ printf("[%s] %s %d : %s\n",
+ log_label, function, line, log_one_buffer);
+ }
+ return len;
+}
+
+extern "C" void initDebugLogLevel(const char* fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ __logger_log("Level", LOG_DEBUG, fmt, __FILE__, __LINE__, args);
+ va_end(args);
+}
+
+extern "C" void setDebugLogLevelNum(const usr_log_level __level)
+{
+ level = __level;
+}
+
+extern "C" int getDebugLogLevelNum(void)
+{
+ return level;
+}
+
+extern "C" void setDebugLogLevel(const char* __level)
+{
+ if(__level != NULL)
+ level = atoi(__level);
+}
+
+extern "C" void setDebugLogName(const char* __name)
+{
+ if(__name == NULL)
+ return;
+
+ strncpy(log_label, __name, sizeof(log_label)-1);
+ log_label[sizeof(log_label)-1] = 0;
+}
+
+extern "C" void getDebugLogName(char* __name)
+{
+ if(__name != NULL)
+ {
+ int length = strlen(log_label);
+ strncpy(__name, log_label, length);
+ __name[length] = '\0';
+ }
+}
+
if (argc < 2) {
LOGE(TEE_STUB, "Invalid arguments to TEE Stub");
}
+ //for export function
+ getSharedMemoryAddress(0);
+
// Initialize Properties module
// TODO: fetch login method from Context, not to be hardcoded
TEE_Result initStatus;
GIT_SDK = ../../..
TOOLCHAIN_PATH = $(GIT_SDK)/toolchain/linux
+TOOLCHAIN = $(TOOLCHAIN_PATH)/i386-linux-gnueabi-gcc-4.6/bin/i386-linux-gnueabi-
INCLUDE = $(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr/include/
SYSROOT = --sysroot=$(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/
-# Add inputs and outputs from these tool invocations to the build variables
+# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
$(TEECLIB_SOURCE)/src/teec_api.c \
-$(TEECLIB_SOURCE)/src/teec_connection.c
+$(TEECLIB_SOURCE)/src/teec_connection.c
OBJS += \
./src/teec_api.o \
-./src/teec_connection.o
+./src/teec_connection.o
C_DEPS += \
./src/teec_api.d \
-./src/teec_connection.d
-
-C_FLAGS += -fPIC
+./src/teec_connection.d
# Each subdirectory must supply rules for building sources it contributes
src/%.o: $(TEECLIB_SOURCE)/src/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -I"$(HOME)/include/include" -I"$(HOME)/log" -I"$(HOME)/TEECLib/inc" -I"../../osal" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/log" -I"$(HOME)/TEECLib/inc" -I"../../osal" -I$(INCLUDE) -O0 -g3 -Wall -Werror -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
-# Add inputs and outputs from these tool invocations to the build variables
+# Add inputs and outputs from these tool invocations to the build variables
CPP_SRCS += \
$(TEESTUB_SOURCE)/TEEStubServer/ConnectionSession.cpp \
$(TEESTUB_SOURCE)/TEEStubServer/TAProperty.cpp \
-$(TEESTUB_SOURCE)/TEEStubServer/TEEStubServer.cpp
+$(TEESTUB_SOURCE)/TEEStubServer/TEEStubServer.cpp \
+$(TEESTUB_SOURCE)/TEEStubServer/TADebug.cpp
OBJS += \
./TEEStubServer/ConnectionSession.o \
./TEEStubServer/TAProperty.o \
-./TEEStubServer/TEEStubServer.o
+./TEEStubServer/TEEStubServer.o \
+./TEEStubServer/TADebug.o
CPP_DEPS += \
./TEEStubServer/ConnectionSession.d \
./TEEStubServer/TAProperty.d \
-./TEEStubServer/TEEStubServer.d
+./TEEStubServer/TEEStubServer.d \
+./TEEStubServer/TADebug.d
# Each subdirectory must supply rules for building sources it contributes
TEEStubServer/%.o: $(TEESTUB_SOURCE)/TEEStubServer/%.cpp
@echo 'Building file: $<'
@echo 'Invoking: GCC C++ Compiler'
- $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/TEEStub/../ssflib/inc" -I"$(HOME)/TEEStub" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/osal" -I"$(HOME)/TEEStub/../ssflib/inc" -I"$(HOME)/TEEStub" -I$(INCLUDE) -Ldlog -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
GIT_SDK = ../../..
TOOLCHAIN_PATH = $(GIT_SDK)/toolchain/linux
+TOOLCHAIN = $(TOOLCHAIN_PATH)/i386-linux-gnueabi-gcc-4.6/bin/i386-linux-gnueabi-
INCLUDE = $(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr/include/
SYSROOT = --sysroot=$(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr
-include ../makefile.defs
-# Add inputs and outputs from these tool invocations to the build variables
+# Add inputs and outputs from these tool invocations to the build variables
# All Target
all: libTEEStub.a
libTEEStub.a: $(OBJS) $(USER_OBJS)
@echo 'Building target: $@'
@echo 'Invoking: GCC Archiver'
- $(TOOLCHAIN)ar -r "libTEEStub.a" $(OBJS) $(USER_OBJS) $(LIBS) ../log/log.o
+ $(TOOLCHAIN)ar -r "libTEEStub.a" $(OBJS) $(USER_OBJS) $(LIBS)
@echo 'Finished building target: $@'
@echo ' '
$(TEESTUB_SOURCE)/teestubmain.cpp
OBJS += \
-./teestubmain.o
+./teestubmain.o
CPP_DEPS += \
-./teestubmain.d
+./teestubmain.d
# Each subdirectory must supply rules for building sources it contributes
%.o: $(TEESTUB_SOURCE)/%.cpp
@echo 'Building file: $<'
@echo 'Invoking: GCC C++ Compiler'
- $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/TEEStub/../ssflib/inc" -I"$(HOME)/TEEStub" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<" -g
+ $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/osal" -I"$(HOME)/TEEStub/../ssflib/inc" -I"$(HOME)/TEEStub" -I$(INCLUDE) -O0 -g3 -Wall -Werror -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
-
TEESTUB_PATH=$DIR/TEEStub
SIMDAEMON_PATH=$DIR/simulatordaemon
Package=$2
-TOOLCHAIN=$3
-
-CA_SIMULATOR_LIB=$Package/CA/simulator/usr/lib/
-TA_SIMULATOR_LIB=$Package/TA/simulator/usr/lib/
#check error case
check_make_error()
cd $LOG_PATH
make clean
check_make_error
-make TOOLCHAIN=$TOOLCHAIN
+make
check_make_error
cd $DIR
}
cd $OSAL_PATH
make clean
check_make_error
-make TOOLCHAIN=$TOOLCHAIN
+make
check_make_error
cd $DIR
}
cd $TEECLIB_PATH
make clean
check_make_error
-make TOOLCHAIN=$TOOLCHAIN
+make
check_make_error
echo "Copying libteec.so in Package"
-mkdir -p $CA_SIMULATOR_LIB
-cp libteec2.so $CA_SIMULATOR_LIB
+cp libteec2.so $Package/CA/simulator/usr/lib/
check_make_error
cd $DIR
}
cd $SSFLIB_PATH
make clean
check_make_error
-make TOOLCHAIN=$TOOLCHAIN
+make
check_make_error
echo "Copying libssflib.so in Package"
-mkdir -p $TA_SIMULATOR_LIB
-cp libssflib.so $TA_SIMULATOR_LIB
+cp libssflib.so $Package/TA/simulator/usr/lib/
check_make_error
cd $DIR
}
cd $TEESTUB_PATH
make clean
check_make_error
-make TOOLCHAIN=$TOOLCHAIN
+make
check_make_error
echo "Copying libTEEStub.a in Package"
-mkdir -p $TA_SIMULATOR_LIB
-cp libTEEStub.a $TA_SIMULATOR_LIB
+cp libTEEStub.a $Package/TA/simulator/usr/lib/
check_make_error
cd $DIR
}
cd $SIMDAEMON_PATH
make clean
check_make_error
-make TOOLCHAIN=$TOOLCHAIN
+make
check_make_error
echo "Copying SimulatorDaemon in Package"
-mkdir -p $CA_SIMULATOR_LIB
-cp SimulatorDaemon $CA_SIMULATOR_LIB
+cp SimulatorDaemon $Package/CA/simulator/usr/lib/
check_make_error
cd $DIR
}
echo_invalid() {
echo "Simulator Build script
Invalid arguments
-Format: ./build.sh <Build Option> <Package Path> <Toolchain>
-Example:./build.sh buildall ~/Package \"\"
+Format: ./build.sh <Build Option> <Package Path>
+Example:./build.sh buildall ~/Package
<Build Option>
log : Build Logger module
}
# Verify number of arguments to build.sh
-if [[ "$#" -ne 3 ]]; then
+if [[ "$#" -ne 2 ]]; then
echo "Illegal number of arguments"
echo_invalid
exit 0
GIT_SDK = ../../..
TOOLCHAIN_PATH = $(GIT_SDK)/toolchain/linux
+TOOLCHAIN = $(TOOLCHAIN_PATH)/i386-linux-gnueabi-gcc-4.6/bin/i386-linux-gnueabi-
INCLUDE = $(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr/include/
LOG_SOURCE = ../../log
C_DEPS += \
./log.d
-C_FLAGS += -fPIC
-
# Each subdirectory must supply rules for building sources it contributes
%.o: $(LOG_SOURCE)/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -I$(INCLUDE) -O0 -g3 -Wall -c $(SYSROOT) -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -I$(INCLUDE) -O0 -g3 -Wall -c $(SYSROOT) -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
GIT_SDK = ../../..
TOOLCHAIN_PATH = $(GIT_SDK)/toolchain/linux
+TOOLCHAIN = $(TOOLCHAIN_PATH)/i386-linux-gnueabi-gcc-4.6/bin/i386-linux-gnueabi-
INCLUDE = $(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr/include/
OSAL_SOURCE = ../../osal
./OsaSignal.d \
./OsaTask.d
-C_FLAGS += -fPIC
# Each subdirectory must supply rules for building sources it contributes
%.o: $(OSAL_SOURCE)/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -lrt -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -lrt -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
GIT_SDK = ../../..
TOOLCHAIN_PATH = $(GIT_SDK)/toolchain/linux
+TOOLCHAIN = $(TOOLCHAIN_PATH)/i386-linux-gnueabi-gcc-4.6/bin/i386-linux-gnueabi-
INCLUDE = $(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr/include/
SYSROOT = --sysroot=$(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/
CPP_SRCS += \
$(SIMDAEMON_SOURCE)/src/ConnectionSession.cpp \
$(SIMDAEMON_SOURCE)/src/Session.cpp \
-$(SIMDAEMON_SOURCE)/src/SecurityChecker.cpp \
$(SIMDAEMON_SOURCE)/src/SimulatorDaemon.cpp \
$(SIMDAEMON_SOURCE)/src/SimulatorDaemonServer.cpp \
$(SIMDAEMON_SOURCE)/src/TAFactory.cpp \
$(SIMDAEMON_SOURCE)/src/TAInstance.cpp \
$(SIMDAEMON_SOURCE)/src/TEEContext.cpp \
-$(SIMDAEMON_SOURCE)/src/ioService.cpp \
-$(SIMDAEMON_SOURCE)/src/security.c
+$(SIMDAEMON_SOURCE)/src/ioService.cpp
OBJS += \
./src/ConnectionSession.o \
./src/TAFactory.o \
./src/TAInstance.o \
./src/TEEContext.o \
-./src/ioService.o \
-./src/SecurityChecker.o \
-./src/security.o
+./src/ioService.o
CPP_DEPS += \
./src/ConnectionSession.d \
./src/TAFactory.d \
./src/TAInstance.d \
./src/TEEContext.d \
-./src/ioService.d \
-./src/SecurityChecker.d \
-./src/security.d
+./src/ioService.d
# Each subdirectory must supply rules for building sources it contributes
src/%.o: $(SIMDAEMON_SOURCE)/src/%.cpp
@echo 'Building file: $<'
@echo 'Invoking: GCC C++ Compiler'
- $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/simulatordaemon/src/TABinaryManager" -I"$(HOME)/simulatordaemon/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -I"$(HOME)/include/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/simulatordaemon/src/TABinaryManager" -I"$(HOME)/simulatordaemon/inc" -I$(INCLUDE) -O0 -g3 -Wall -Werror -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
./dep/cryptocore/source/base/cc_sha2.d \
./dep/cryptocore/source/base/cc_snow2.d
-C_FLAGS += -fPIC
# Each subdirectory must supply rules for building sources it contributes
dep/cryptocore/source/base/%.o: $(SSFLIB_SOURCE)/dep/cryptocore/source/base/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
./dep/cryptocore/source/middle/cc_symmetric.d \
./dep/cryptocore/source/middle/cc_tdes.d
-C_FLAGS += -fPIC
# Each subdirectory must supply rules for building sources it contributes
dep/cryptocore/source/middle/%.o: $(SSFLIB_SOURCE)/dep/cryptocore/source/middle/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
C_DEPS += \
./dep/cryptocore/source/CC_API.d
-C_FLAGS += -fPIC
-
# Each subdirectory must supply rules for building sources it contributes
dep/cryptocore/source/%.o: $(SSFLIB_SOURCE)/dep/cryptocore/source/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
./dep/swdss/source/ss_misc.d \
./dep/swdss/source/ss_temp_store.d
-C_FLAGS += -fPIC
# Each subdirectory must supply rules for building sources it contributes
dep/swdss/source/%.o: $(SSFLIB_SOURCE)/dep/swdss/source/%.cpp
@echo 'Building file: $<'
@echo 'Invoking: GCC C++ Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
CPP_DEPS += \
./dep/time/ssf_time.d
-C_FLAGS += -fPIC
# Each subdirectory must supply rules for building sources it contributes
dep/time/%.o: $(SSFLIB_SOURCE)/dep/time/%.cpp
@echo 'Building file: $<'
@echo 'Invoking: GCC C++ Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
./dep/uci/source/uci_cryptocore.d \
./dep/uci/source/uci_hwcrypto.d
-C_FLAGS += -fPIC
# Each subdirectory must supply rules for building sources it contributes
dep/uci/source/%.o: $(SSFLIB_SOURCE)/dep/uci/source/%.c
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
GIT_SDK = ../../..
TOOLCHAIN_PATH = $(GIT_SDK)/toolchain/linux
+TOOLCHAIN = $(TOOLCHAIN_PATH)/i386-linux-gnueabi-gcc-4.6/bin/i386-linux-gnueabi-
INCLUDE = $(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/usr/include/
SYSROOT = --sysroot=$(TOOLCHAIN_PATH)/rootstraps/mobile-2.3-emulator.core/
-# Add inputs and outputs from these tool invocations to the build variables
+# Add inputs and outputs from these tool invocations to the build variables
C_SRCS += \
-$(SSFLIB_SOURCE)/src/ssf_arithmetic.c \
-$(SSFLIB_SOURCE)/src/ssf_client.c \
-$(SSFLIB_SOURCE)/src/ssf_crypto.c \
-$(SSFLIB_SOURCE)/src/ssf_lib.c \
-$(SSFLIB_SOURCE)/src/ssf_malloc.c \
-$(SSFLIB_SOURCE)/src/ssf_panic.c \
-$(SSFLIB_SOURCE)/src/ssf_storage.c \
-$(SSFLIB_SOURCE)/src/ssf_taentrypoint.c \
-$(SSFLIB_SOURCE)/src/app_debug.c
+$(SSFLIB_SOURCE)/src/ssf_arithmetic.cpp \
+$(SSFLIB_SOURCE)/src/ssf_client.cpp \
+$(SSFLIB_SOURCE)/src/ssf_crypto.cpp \
+$(SSFLIB_SOURCE)/src/ssf_lib.cpp \
+$(SSFLIB_SOURCE)/src/ssf_malloc.cpp \
+$(SSFLIB_SOURCE)/src/ssf_panic.cpp \
+$(SSFLIB_SOURCE)/src/ssf_storage.cpp \
+$(SSFLIB_SOURCE)/src/ssf_taentrypoint.cpp \
+$(SSFLIB_SOURCE)/src/ssf_permission.cpp \
+$(SSFLIB_SOURCE)/src/app_debug.cpp
OBJS += \
./src/ssf_arithmetic.o \
./src/ssf_malloc.o \
./src/ssf_panic.o \
./src/ssf_storage.o \
-./src/ssf_taentrypoint.o \
+./src/ssf_taentrypoint.o \
+./src/ssf_permission.o \
./src/app_debug.o
C_DEPS += \
./src/ssf_panic.d \
./src/ssf_storage.d \
./src/ssf_taentrypoint.d \
+./src/ssf_permission.d \
./src/app_debug.d
-C_FLAGS += -fPIC
-
# Each subdirectory must supply rules for building sources it contributes
-src/%.o: $(SSFLIB_SOURCE)/src/%.c
+src/%.o: $(SSFLIB_SOURCE)/src/%.cpp
@echo 'Building file: $<'
@echo 'Invoking: GCC C Compiler'
- $(TOOLCHAIN)g++ $(C_FLAGS) -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
+ $(TOOLCHAIN)g++ -D_SECOS_SIM_ -D__DEBUG__ -I"$(HOME)/ssflib/dep/cryptocore/include" -I"$(HOME)/log" -I"$(HOME)/osal" -I"$(HOME)/include/include" -I"$(HOME)/ssflib/dep/cryptocore/include/base" -I"$(HOME)/ssflib/dep/cryptocore/include/middle" -I"$(HOME)/ssflib/dep/swdss/include" -I"$(HOME)/ssflib/dep/uci/include" -I"$(HOME)/ssflib/inc" -I$(INCLUDE) -O2 -g2 -Wall -Werror -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
@echo 'Finished building: $<'
@echo ' '
--- /dev/null
+/*
+ * debug.h
+ *
+ * This source file is proprietary property of Samsung Electronics Co., Ltd.
+ *
+ * Copyright (C) 2011 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Contact: Jaemin Ryu <jm77.ryu@samsung.com>
+ *
+ */
+
+#ifndef __ALLOC_DEBUG_H__
+#define __ALLOC_DEBUG_H__
+
+#include <log_level.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define TEE_STUB "TEE_STUB"
+#define LOG_LABEL_SIZE 64
+
+int __logger_log(const char* tag, const usr_log_level lv, const char* fmt, const char* function, const int line, ...);
+
+#define LOGD(Tag, Fmt, ...) __logger_log(Tag, LOG_DEBUG, Fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
+#define LOGI(Tag, Fmt, ...) __logger_log(Tag, LOG_INFO, Fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
+#define LOGW(Tag, Fmt, ...) __logger_log(Tag, LOG_WARNING, Fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
+#define LOGE(Tag, Fmt, ...) __logger_log(Tag, LOG_ERR, Fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
+#define LOGC(Tag, Fmt, ...) __logger_log(Tag, LOG_CRIT, Fmt, __FUNCTION__, __LINE__, ##__VA_ARGS__)
+
+void setDebugLogLevelNum(const usr_log_level __level);
+int getDebugLogLevelNum(void);
+void setDebugLogLevel(const char* __level);
+void setDebugLogName(const char* __name); /* buffer(__name) size should be LOG_LABEL_SIZE(64) */
+void getDebugLogName(char* __name); /* buffer(__name) size should be LOG_LABEL_SIZE(64) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ALLOC_DEBUG_H */
--- /dev/null
+/*
+ * log_level.h
+ *
+ * This source file is proprietary property of Samsung Electronics Co., Ltd.
+ *
+ * Copyright (C) 2016 - 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ */
+
+#ifndef __LOG_LEVEL_H__
+#define __LOG_LEVEL_H__
+
+typedef enum {
+ LOG_EMERG = 0,
+ LOG_ALERT,
+ LOG_CRIT,
+ LOG_ERR,
+ LOG_WARNING,
+ LOG_NOTICE,
+ LOG_INFO,
+ LOG_DEBUG,
+ LOG_SILENT,
+} usr_log_level;
+
+/* Tee World */
+#define TA_LOG_LEVEL LOG_DEBUG /* Generation Default */
+
+#endif
void* mac,
size_t *macLen);
TEE_Result TEE_MACCompareFinal(TEE_OperationHandle operation,
- const void* message,
+ void* message,
size_t messageLen,
- const void* mac,
+ void* mac,
size_t *macLen);
/******************************************************************************
******************************************************************************/
TEE_Result TEE_AEInit(TEE_OperationHandle operation,
- const void* nonce,
+ void* nonce,
size_t nonceLen,
uint32_t tagLen,
uint32_t AADLen,
uint32_t payloadLen);
void TEE_AEUpdateAAD(TEE_OperationHandle operation,
- const void* AADdata,
+ void* AADdata,
size_t AADdataLen);
TEE_Result TEE_AEUpdate(TEE_OperationHandle operation,
- const void* srcData,
+ void* srcData,
size_t srcLen,
void* destData,
size_t *destLen);
TEE_Result TEE_AEEncryptFinal(TEE_OperationHandle operation,
- const void* srcData,
+ void* srcData,
size_t srcLen,
void* destData,
size_t* destLen,
void* tag,
size_t* tagLen);
TEE_Result TEE_AEDecryptFinal(TEE_OperationHandle operation,
- const void* srcData,
+ void* srcData,
size_t srcLen,
void* destData,
size_t *destLen,
******************************************************************************/
void TEE_DeriveKey(TEE_OperationHandle operation,
- const TEE_Attribute* params,
+ TEE_Attribute* params,
uint32_t paramCount,
TEE_ObjectHandle derivedKey);
uint32_t paramTypes;
TEE_Param params[4];
uint32_t shmID[4];
+ uint32_t shmOffset[4];
} Operation;
typedef struct {
typedef OperationData IntTAOperationData;
typedef struct {
+ TEE_UUID source;
TEE_UUID destination;
uint32_t cancelTimeOut;
IntTAOperationData operation;
#define INOUT
#define OUT
-#define _LOGGING
+//#define _LOGGING
#ifdef _WIN
typedef int int8_t;
#define MAX_NAMEDSEM_MGR 256
-static UlOsaSem_t* sem[MAX_NAMEDSEM_MGR]={0};
-
-
-unsigned int addptr(UlOsaSem_t*s) {
- for (int i=0; i < MAX_NAMEDSEM_MGR; ++i) {
- if (sem[i]==NULL) {sem[i]=s; return i;}
- }
- return -1;
-}
-
-
-UlOsaSem_t* getptr(unsigned int id) {
- return sem[id];
-}
-
-
-void rmid(unsigned int id) {
- sem[id]=NULL;
-}
-
-
static int UlOsaNamedSemCreate(const char pcName[10], int iCount,
int iAttribute, unsigned int* puiSmid) {
int iRetVal = OSAL_OK;
memcpy((void*)sem->bName, (const void*)pcName, (size_t)10);
sem->bName[10] = '\0';
- *puiSmid = addptr(sem);
+ *puiSmid = (unsigned int)sem;
return iRetVal;
}
struct timeval tv;
int ret;
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
if (!sem) {
return OSAL_ERROR;
}
static int UlOsaNamedSemRelease(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
struct sembuf semBuf;
if (!sem) {
}
static int UlOsaNamedSemReset(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
union semun semUnion;
if (!sem) {
}
static int UlOsaNamedSemGetval(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
int n;
if (!sem) {
*-----------------------------------------------------------------------------*/
/* TODO: apply iAttribute */
// COMMON_071008_1
-
-#define MAX_NAMEDSEM_MGR 256
-static UlOsaSem_t* sem[MAX_NAMEDSEM_MGR]={0};
-
-
-unsigned int addptr(UlOsaSem_t*s) {
- for (int i=0; i < MAX_NAMEDSEM_MGR; ++i) {
- if (sem[i]==NULL) {sem[i]=s; return i;}
- }
- return -1;
-}
-
-
-UlOsaSem_t* getptr(unsigned int id) {
- return sem[id];
-}
-
-
-void rmid(unsigned int id) {
- sem[id]=NULL;
-}
-
-
-
static int UlOsaSemCreate(const char bName[10], int iCount, int iAttribute,
unsigned int* puiSmid) {
UlOsaSem_t* sem;
memcpy((void*)sem->bName, (const void*)bName, (size_t)10);
sem->bName[10] = '\0';
- *puiSmid = addptr(sem);
+ *puiSmid = (unsigned int)sem;
return OSAL_OK;
}
static int UlOsaSemDelete(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
if (!sem) {
return OSAL_ERROR;
sem_destroy(&sem->sem);
free(sem);
- rmid(uiSmid);
return OSAL_OK;
}
static int UlOsaSemGet(unsigned int uiSmid, int iFlags, int iTimeout) {
int ret;
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
if (!sem) {
return OSAL_ERROR;
}
static int UlOsaSemRelease(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
if (!sem) {
return OSAL_ERROR;
}
}
static int UlOsaSemReset(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
if (!sem) {
return OSAL_ERROR;
}
}
static int UlOsaSemGetval(unsigned int uiSmid) {
- UlOsaSem_t *sem = getptr(uiSmid);
+ UlOsaSem_t *sem = (UlOsaSem_t*)uiSmid;
int n;
if (!sem) {
return OSAL_ERROR;
//------------------------------------------------------------------------------
// $$$
*/
-
-
-pthread_mutex_t* mutexes[MAX_NAMEDSEM_MGR] = {0};
-
-unsigned int add_mutex(pthread_mutex_t* s) {
- for (int i=0; i < MAX_NAMEDSEM_MGR; ++i) {
- if (mutexes[i]==NULL) {mutexes[i]=s; return i;}
- }
- return -1;
-}
-
-
-pthread_mutex_t* get_mutex(unsigned int id) {
- return mutexes[id];
-}
-
-
-void rmid_mutex(unsigned int id) {
- mutexes[id]=NULL;
-}
-
-
int OsaMutCreate(const char bName[10], int iAttributes, unsigned int* puiMutid) {
pthread_mutexattr_t attr_t;
pthread_mutex_t* pmutex_t;
break;
}
- (*puiMutid) = add_mutex(pmutex_t);
+ (*puiMutid) = (unsigned int)pmutex_t;
pthread_mutexattr_destroy(&attr_t);
} else {
int OsaMutDelete(unsigned int uiMutid) {
int iRet;
- pthread_mutex_t* pmutex_t = get_mutex(uiMutid);
+ pthread_mutex_t* pmutex_t = (pthread_mutex_t *)uiMutid;
if (pmutex_t == NULL) {
return OSAL_OK;
}
}
free(pmutex_t);
- rmid_mutex(uiMutid);
return OSAL_OK;
}
int OsaMutRelease(unsigned int uiMutid) {
int iRet;
- pthread_mutex_t* pmutex_t = get_mutex(uiMutid);
+ pthread_mutex_t* pmutex_t = (pthread_mutex_t *)uiMutid;
iRet = pthread_mutex_unlock(pmutex_t);
if (iRet < 0) {
perror("In OsaMutRelease() : failed ");
*/
int OsaMutGet(unsigned int uiMutid, int iFlags, int iTimeout) {
int iRet;
- pthread_mutex_t* pmutex_t = get_mutex(uiMutid);
+ pthread_mutex_t* pmutex_t = (pthread_mutex_t *)uiMutid;
iRet = pthread_mutex_lock(pmutex_t);
if (iRet < 0) {
perror("In OsaMutGet() : failed ");
int OsaMutTryGet(unsigned int uiMutid, int iFlags, int iTimeout) {
int iRet;
- pthread_mutex_t* pmutex_t = get_mutex(uiMutid);
+ pthread_mutex_t* pmutex_t = (pthread_mutex_t *)uiMutid;
iRet = pthread_mutex_trylock(pmutex_t);
if (iRet) {
return ((int)iRet);
*-----------------------------------------------------------------------------*/
#include <pthread.h>
#include <cstdlib>
-#include <algorithm>
#include "ISession.h"
/*-----------------------------------------------------------------------------
#include "Session.h"
#include "tee_command.h"
#include "IConnectionSession.h"
-#include "ConnectionSession.h"
-#include "SecurityChecker.h"
using namespace std;
/*-----------------------------------------------------------------------------
IConnectionSession* mConnSess;
// ContextID assigned to the instance
uint32_t mContextID;
- /* Security checker wich can tell us if client has different Tizen's policy permissions*/
- SecurityChecker mConnSecChecker;
-
/* For TA internal APIs support, dummy Context is created and for recognizing
* the context as dummy isInternal member variable is used
*/
bool isInternal;
- TEEContext(uint32_t contextID, ConnectionSession* connSession);
+ TEEContext(uint32_t contextID, IConnectionSession* connSession);
TEEC_Result initContext(InitContextData* data);
void finContext(FinalizeContextData data);
TEEC_Result openSession(OpenSessionData data);
TEEC_Result invokeTACommand(IntTAInvokeCommandData data);
TEEC_Result registerSharedMemory(RegSharedMemData data);
TEEC_Result releaseSharedMemory(RelSharedMemData data);
+ TEEC_Result checkTADomain(IntTAOpenSessionData data);
void reqCancel(ReqCancellationData data);
~TEEContext();
};
// No operation data
} else {
idata.operation.params[i].mem.size = data->op.params[i].memref.size;
- idata.operation.params[i].mem.shmKey = data->op.shmID[i];
+ idata.operation.params[i].mem.shmKey = data->op.params[i].memref.memid;
+ idata.operation.params[i].mem.offset = data->op.shmOffset[i];
}
}
idata.returnValue = data->returnValue;
// No operation data
} else {
idata.operation.params[i].mem.size = data->op.params[i].memref.size;
- idata.operation.params[i].mem.shmKey = data->op.shmID[i];
+ idata.operation.params[i].mem.shmKey = data->op.params[i].memref.memid;
+ idata.operation.params[i].mem.offset = data->op.shmOffset[i];
}
}
idata.returnValue = data->returnValue;
// No operation data
} else {
odata.operation.params[i].mem.size = data->op.params[i].memref.size;
- odata.operation.params[i].mem.shmKey = data->op.shmID[i];
+ odata.operation.params[i].mem.shmKey = data->op.params[i].memref.memid;
+ odata.operation.params[i].mem.offset = data->op.shmOffset[i];
}
}
odata.returnValue = data->returnValue;
// No operation data
} else {
odata.operation.params[i].mem.size = data->op.params[i].memref.size;
- odata.operation.params[i].mem.shmKey = data->op.shmID[i];
+ odata.operation.params[i].mem.shmKey = data->op.params[i].memref.memid;
+ odata.operation.params[i].mem.offset = data->op.shmOffset[i];
}
}
odata.returnValue = data->returnValue;
string TAUUID = TABin->getUUIDAsString(data.uuid);
string argvPort = TABin->getPort(TAUUID);
- string TAName(TAUUID);
- std::transform(TAName.begin(), TAName.end(), TAName.begin(), ::toupper);
- if(!mContext->nConnSecChecker.clientHasAccessToTa(TAUUID)){
- LOGE(SIM_DAEMON, "Client has no permission for access TA: %s ", TAName.c_str());
- return TEEC_ERROR_ACCESS_DENIED;
- }
-
if (argvPort != "") {
pthread_rwlock_wrlock(&TAFact->mTAInstanceMapLock);
multimap<string, TAInstancePtr>::iterator itr;
// No operation data
} else {
tdata.op.params[i].memref.size = data.operation.params[i].mem.size;
+ tdata.op.params[i].memref.memid = data.operation.params[i].mem.shmKey;
tdata.op.shmID[i] = data.operation.params[i].mem.shmKey;
+ tdata.op.shmOffset[i] = data.operation.params[i].mem.offset;
}
}
// Send OPENSESSION request to TA
// No operation data
} else {
idata.op.params[i].memref.size = data.operation.params[i].mem.size;
+ idata.op.params[i].memref.memid = data.operation.params[i].mem.shmKey;
idata.op.shmID[i] = data.operation.params[i].mem.shmKey;
+ idata.op.shmOffset[i] = data.operation.params[i].mem.offset;
}
}
* Include files
*-----------------------------------------------------------------------------*/
#include "SimulatorDaemonServer.h"
-#include "SecurityChecker.h"
/*-----------------------------------------------------------------------------
* Member functions
ConnectionSession::session_ptr new_session = ConnectionSession::create(
acceptor.get_io_service());
-
acceptor.async_accept(new_session->socket(),
boost::bind(&SimulatorDaemonServer::handleAccept, this, new_session,
boost::asio::placeholders::error));
void SimulatorDaemonServer::handleAccept(
ConnectionSession::session_ptr new_session,
const boost::system::error_code& error) {
-
- const string privelege("http://tizen.org/privilege/account.read");
LOGD(SIM_DAEMON, "Entry");
- if (!SecurityChecker::clientHasCynaraPermission(new_session.get(), privelege)){
- LOGE("Client has no permission to use TEE");
- return;
- }
-
if (!error) {
new_session->start();
}
try {
// 1. PROPERTIES
xml_node<> *node = doc.first_node("manifest")->first_node("properties");
- {
+
+ if (node != NULL) {
stringstream sstream;
// GENERAL
xml_node<> *propertiesGeneral = node->first_node("general");
- properties.general.appID = string(
- propertiesGeneral->first_attribute("appID")->value());
- properties.general.singleInstance =
- string(propertiesGeneral->first_attribute("singleInstance")->value())
- .compare("true") == 0 ? true : false;
- properties.general.multiSession =
- string(propertiesGeneral->first_attribute("multiSession")->value())
- .compare("true") == 0 ? true : false;
- properties.general.instanceKeepAlive =
- string(
- propertiesGeneral->first_attribute("instanceKeepAlive")->value())
- .compare("true") == 0 ? true : false;
-
- sstream.clear();
- sstream.str(
- string(propertiesGeneral->first_attribute("stackSize")->value()));
- sstream >> properties.general.stackSize;
-
- sstream.clear();
- sstream.str(
- string(propertiesGeneral->first_attribute("dataSize")->value()));
- sstream >> properties.general.dataSize;
+
+ if (propertiesGeneral != NULL) {
+ properties.general.appID = string(propertiesGeneral->first_attribute("appID")->value());
+ properties.general.singleInstance = string(propertiesGeneral->first_attribute("singleInstance")->value())
+ .compare("true") == 0 ? true : false;
+ properties.general.multiSession = string(propertiesGeneral->first_attribute("multiSession")->value())
+ .compare("true") == 0 ? true : false;
+ properties.general.instanceKeepAlive =string(propertiesGeneral->first_attribute("instanceKeepAlive")->value())
+ .compare("true") == 0 ? true : false;
+
+ sstream.clear();
+ sstream.str(string(propertiesGeneral->first_attribute("stackSize")->value()));
+ sstream >> properties.general.stackSize;
+
+ sstream.clear();
+ sstream.str(string(propertiesGeneral->first_attribute("dataSize")->value()));
+ sstream >> properties.general.dataSize;
+ }
+
// EXTENSION
xml_node<> *propertiesExtension = node->first_node("extension");
- properties.extension.appName = string(
- propertiesExtension->first_attribute("appName")->value());
- properties.extension.appVersion = string(
- propertiesExtension->first_attribute("appVersion")->value());
- /*properties.extension.type = string(
- propertiesExtension->first_attribute("type")->value());
- properties.extension.zone = string(
- propertiesExtension->first_attribute("zone")->value());*/
- properties.extension.sdkVersion = string(
- propertiesExtension->first_attribute("sdkVersion")->value());
- // Removed, taEncrypion flag used now
- //properties.extension.secret = string(
- // propertiesExtension->first_attribute("secret")->value());
- properties.extension.launchMode = string(
- propertiesExtension->first_attribute("launchMode")->value());
+
+ if (propertiesExtension != NULL) {
+ properties.extension.appName = string(propertiesExtension->first_attribute("appName")->value());
+ properties.extension.appVersion = string(propertiesExtension->first_attribute("appVersion")->value());
+
+ /*properties.extension.type = string(propertiesExtension->first_attribute("type")->value());
+ properties.extension.zone = string(propertiesExtension->first_attribute("zone")->value());*/
+ properties.extension.sdkVersion = string(propertiesExtension->first_attribute("sdkVersion")->value());
+
+ // Removed, taEncrypion flag used now
+ //properties.extension.secret = string(propertiesExtension->first_attribute("secret")->value());
+
+ properties.extension.launchMode = string(propertiesExtension->first_attribute("launchMode")->value());
+ }
}
// 2. POLICY
node = doc.first_node("manifest")->first_node("policy");
- {
+
+ if (node != NULL) {
// PRIVILEGE
xml_node<> *policyPrivilege = node->first_node("privilege");
- policy.privilegeName = string(
- policyPrivilege->first_attribute("name")->value());
+
+ if (policyPrivilege != NULL) {
+ policy.privilegeName = string(
+ policyPrivilege->first_attribute("name")->value());
+ }
+
// PROTECTION DOMAIN
xml_node<> *policyProtectionDomain = node->first_node("protectionDomain");
- policy.protectionDomain.createDomain = string(
- policyProtectionDomain->first_node("createDomain")->first_attribute(
- "name")->value());
- policy.protectionDomain.allowedDomain = string(
- policyProtectionDomain->first_node("allowedDomain")->first_attribute(
- "name")->value());
+
+ if (policyProtectionDomain != NULL) {
+ policy.protectionDomain.createDomain = string(
+ policyProtectionDomain->first_node("createDomain")->first_attribute("name")->value());
+ for (xml_node<> *childnode = policyProtectionDomain->first_node("allowedDomain"); childnode; childnode = childnode->next_sibling()) {
+ policy.protectionDomain.allowedDomain.push_back(string(childnode->first_attribute("name")->value()));
+ }
+ }
+
// PERMISSION - vector
xml_node<> *policyPermission = node->first_node("permission");
- for (xml_node<> *childnode = policyPermission->first_node(
- "uses-permission"); childnode; childnode =
- childnode->next_sibling()) {
- //std::cout << "[SIM_DAEMON] Permission vector: " << string(childnode->first_attribute("name")->value()) << endl;
- policy.usesPermission.push_back(
- string(childnode->first_attribute("name")->value()));
+
+ if (policyPermission != NULL) {
+ for (xml_node<> *childnode = policyPermission->first_node("uses-permission"); childnode; childnode = childnode->next_sibling()) {
+ //std::cout << "[SIM_DAEMON] Permission vector: " << string(childnode->first_attribute("name")->value()) << endl;
+ policy.usesPermission.push_back(string(childnode->first_attribute("name")->value()));
+ }
}
+
}
// 3. TA ENC
node = doc.first_node("manifest")->first_node("taEncryption");
- {
+
+ if (node != NULL) {
// MODEL
xml_node<> *model = node->first_node("model");
- taencryption.model.modelName = string(
- model->first_node("modelName")->first_attribute("value")->value());
- taencryption.model.plainkeydata = string(
- model->first_node("plainkeydata")->first_attribute("value")->value());
+
+ if (model != NULL) {
+ taencryption.model.modelName = string(model->first_node("modelName")->first_attribute("value")->value());
+ taencryption.model.plainkeydata = string(model->first_node("plainkeydata")->first_attribute("value")->value());
+ }
}
+
// 4. INFORMATION
node = doc.first_node("manifest")->first_node("information");
- {
- information.description = string(
- node->first_node("description")->value());
+
+ if (node!= NULL) {
+ information.description = string(node->first_node("description")->value());
information.author = string(node->first_node("author")->value());
information.terms = string(node->first_node("terms")->value());
information.copyright = string(node->first_node("copyright")->value());
-
}
+
ret = true;
}
// Catch rapid xml errors
std::cout << "[SIM_DAEMON] policy.privilegeName: " << policy.privilegeName
<< endl;
- std::cout << "[SIM_DAEMON] " << policy.protectionDomain.allowedDomain << endl;
+ for (unsigned int i = 0; i < policy.protectionDomain.allowedDomain.size(); i++) {
+ std::cout << "[SIM_DAEMON] \tpolicy.protectionDomain.allowedDomain: "
+ << policy.protectionDomain.allowedDomain[i] << endl;
+ }
std::cout << "[SIM_DAEMON] " << policy.protectionDomain.createDomain << endl;
for (unsigned int i = 0; i < policy.usesPermission.size(); i++) {
std::cout << "[SIM_DAEMON] \tpolicy.usesPermission: "
typedef struct {
string createDomain;
- string allowedDomain;
+ vector<string> allowedDomain;
} StructPolicyProtectionDomain;
typedef struct {
LOGD(SIM_DAEMON, "Connect to TEEStub");
// Try to connect to TA RETRY_COUNT number of times
while (error && (retry_count < RETRY_COUNT)) {
-#if 0
+#if 0
LOGD(SIM_DAEMON, "Trying to connect to TEEStub");
LOGE(SIM_DAEMON, "Response returned with error code %d", error.value());
LOGE(SIM_DAEMON, "Response returned with error code %s",
*/
void TAInstance::closeConnectionToTA() {
LOGD(SIM_DAEMON, "Entry");
- TEEC_Result result = TEEC_ERROR_COMMUNICATION;
boost::system::error_code ec;
-
+
mTAConnectionSocket.close(ec);
- if(!ec)
- result = TEEC_SUCCESS;
- else
+ if(ec)
LOGE(SIM_DAEMON, "TA Connection close FAILED");
}
* Include files
*-----------------------------------------------------------------------------*/
#include "TEEContext.h"
+#include "TABinaryManager.h"
/*-----------------------------------------------------------------------------
* Globals
* @param contextID ID for Context reference
* @param connSession ConnectionSession instance associated with the context
*/
-TEEContext::TEEContext(uint32_t contextID, ConnectionSession* connSession)
- :mConnSecChecker(connSession)
-{
+TEEContext::TEEContext(uint32_t contextID, IConnectionSession* connSession) {
LOGD(SIM_DAEMON, "ContextID: %d", contextID);
sdata.operation = data.operation;
memcpy(&sdata.uuid, &data.destination, sizeof(TEEC_UUID));
+ result = checkTADomain(data);
+ if (TEEC_SUCCESS != result) {
+ data.returnValue = result;
+
+ /* Write the response back to SSFLIB in case of failure */
+ result = mConnSess->write(OPEN_TA_SESSION, (char*)&data,
+ sizeof(IntTAOpenSessionData));
+
+ if (result != TEEC_SUCCESS) {
+ LOGE(SIM_DAEMON, "Open TA Session response write to CA FAILED");
+ }
+
+ return result;
+ }
+
/* Create a new Session instance */
ISession *mSession = new Session(this);
return result;
}
+TEEC_Result TEEContext::checkTADomain(IntTAOpenSessionData data) {
+ TEEC_Result result = TEEC_ERROR_GENERIC;
+
+ LOGD(SIM_DAEMON, "Entry");
+
+ const TAManifest* srcTAManifest;
+ const TAManifest* dstTAManifest;
+ string source_uuid, dest_uuid;
+ string srcCreateDomain;
+ string dstAllowedDomain;
+ unsigned int dstAllowedDomainCount;
+
+ TEEC_UUID src, dst;
+ TABinaryManager *TABin = TABinaryManager::getInstance();
+ if(TABin == NULL) {
+ LOGE(SIM_DAEMON, "Creating TABinaryManager Instance FAILED - ");
+ return TEEC_ERROR_GENERIC;
+ }
+
+ memcpy(&src, &data.source, sizeof(TEEC_UUID));
+ memcpy(&dst, &data.destination, sizeof(TEEC_UUID));
+
+ source_uuid = TABin->getUUIDAsString(src);
+ dest_uuid = TABin->getUUIDAsString(dst);
+
+ std::transform(source_uuid.begin(), source_uuid.end(), source_uuid.begin(), ::toupper);
+ std::transform(dest_uuid.begin(), dest_uuid.end(), dest_uuid.begin(), ::toupper);
+
+ dstTAManifest = TABin->getManifest(dest_uuid);
+ srcTAManifest = TABin->getManifest(source_uuid);
+
+ srcCreateDomain = srcTAManifest->policy.protectionDomain.createDomain;
+ dstAllowedDomainCount = dstTAManifest->policy.protectionDomain.allowedDomain.size();
+
+ if (dstAllowedDomainCount == 0) {
+ return TEEC_SUCCESS;
+ }
+
+ for (unsigned int i = 0; i < dstAllowedDomainCount; i++) {
+ dstAllowedDomain = dstTAManifest->policy.protectionDomain.allowedDomain[i];
+
+ /*
+ * When comparing source`s createDomain and destination`s allowedDomain strings,
+ * It should be compared only length of the string with not included null character.
+ *
+ * ex) In the below case, openTASession should be success.
+ * source`s createDomain : [mainDomain/subDomain]
+ * destination`s allowedDomain : [mainDomain]
+ */
+ if (strncmp(dstAllowedDomain.c_str(), srcCreateDomain.c_str(), dstAllowedDomain.size()) == 0) {
+ result = TEEC_SUCCESS;
+ break;
+ }
+ }
+
+ return result;
+}
+
/**
* TEEContext destructer.
*/
#ifndef _CC_TYPE_H_
#define _CC_TYPE_H_
-#include <stdint.h>
/*! @brief 1-byte data type */
-typedef uint8_t cc_u8;
+typedef unsigned char cc_u8;
/*! @brief 2-byte data type */
-typedef uint16_t cc_u16;
+typedef unsigned short cc_u16;
/*! @brief 4-byte data type */
-typedef uint32_t cc_u32;
+typedef unsigned int cc_u32;
#ifndef _OP64_NOTSUPPORTED
#ifdef _WIN32
typedef unsigned __int64 cc_u64;
#else
- typedef uint64_t cc_u64;
+ typedef unsigned long long cc_u64;
#endif //_WIN32
#endif //_OP64_NOTSUPPORTED
#endif //_CC_TYPE_H_
-/***************************** End of File *****************************/
+/***************************** End of File *****************************/
\ No newline at end of file
--- /dev/null
+#ifndef _SELFTEST_H_\r
+#define _SELFTEST_H_\r
+\r
+#include "CC_API.h"\r
+\r
+\r
+\r
+int fips_aes_selftest(void);\r
+int fips_des_selftest(void);\r
+int fips_dh_selftest(void);\r
+int fips_dsa_selftest(void);\r
+int fips_hmac_selftest(void);\r
+int fips_rand_selftest(void);\r
+int fips_rsa_selftest(void);\r
+int fips_sha_selftest(void);\r
+\r
+int fips_cmac_selftest(void);\r
+int fips_ecdh_selftest(void);\r
+int fips_ecdsa_selftest(void);\r
+int fips_drbg_hmac_selftest(void);\r
+\r
+int fips_selftest_check(void);\r
+\r
+#if (defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) || defined(__ANDROID__)) && defined(CC_BUILD_TARGET_UNIX)\r
+int integrity_check();\r
+#endif\r
+\r
+\r
+\r
+#endif //_SELFTEST_H_
\ No newline at end of file
CryptoCoreContainer *create_CryptoCoreContainer(cc_u32 algorithm)
{
CryptoCoreContainer *crt;
- srand((unsigned int)time(NULL));
+
+ static int add_value = 0;
+ if(++add_value == 10000) add_value = 0;
+
+ srand(time(NULL) + add_value );
// allocate memory for crypt data structure (by using CCMalloc)
crt = (CryptoCoreContainer *)CCMalloc(sizeof(CryptoCoreContainer));
crt->ECDH_Gen1stPhaseKey= NULL;
crt->ECDH_GenAuthKey = NULL;
+ printf("TEST!!! step 1 in create_CryptoCoreContainer(%d)\n",algorithm);
+
// allocate memory for context data structure
// and set up the member functions according to the algorithm
crt->alg = algorithm;
crt = NULL;
break;
}
+
+ printf("TEST!!! after in create_CryptoCoreContainer(%p %d)\n",crt, ID_AES128);
+ printf("TEST!!! after in create_CryptoCoreContainer(%p)\n",crt->SE_init);
+/* crt->SE_init = SDRM_AES_init;
+ crt->SE_process = SDRM_AES_process;
+ crt->SE_final = SDRM_AES_final;
+ crt->SE_EncryptOneBlock = SDRM_AES128_Encryption;
+ crt->SE_DecryptOneBlock = SDRM_AES128_Decryption;*/
+
return crt;
}
CCFree(crt);
}
-/***************************** End of File *****************************/
\ No newline at end of file
+/***************************** End of File *****************************/
cc_u32 i, n, k, j;
cc_u8 * bufferHex = NULL;
+ n = (cc_u32)strlen((const char*)pbSrc);
+
if (!BN_Dst)
{
- BN_Dst = SDRM_BN_Init(BN_Dst->Length * SDRM_SIZE_OF_DWORD * 8);
+ BN_Dst = SDRM_BN_Init((n / SDRM_SIZE_BLOCK) * SDRM_SIZE_OF_DWORD * 8);
if(BN_Dst == NULL)
{
return CRYPTO_MEMORY_ALLOC_FAIL;
pbSrc[0] = '0';
}
- BN_Dst->Length = 0;
- n = strlen((const char*)pbSrc);
-
BN_Dst->Length = n / SDRM_SIZE_BLOCK;
//normalize length
if( n % SDRM_SIZE_BLOCK != 0 ) {
BN_Dst->Length+=1;
}
-#if 0 //fix prevent problem by guoxing.xu 20140826. move to before
+#if 0 //fix prevent problem by guoxing.xu 20140826. move to before
if (!BN_Dst)
{
BN_Dst = SDRM_BN_Init(BN_Dst->Length * SDRM_SIZE_OF_DWORD * 8);
//full string: bufferHex mod Length = 0
bufferHex = (cc_u8 *)malloc( sizeof(cc_u8) * (BN_Dst->Length * SDRM_SIZE_BLOCK));
- //init byffer by 0
+ //init byffer by 0
for(i = 0; i < BN_Dst->Length * SDRM_SIZE_BLOCK; i++)
{
bufferHex[i] = '0';
}
-
k = n - 1;
for(i = (BN_Dst->Length * SDRM_SIZE_BLOCK) - 1; (int)k >= 0; i--, k--)
{
bufferHex[i] = pbSrc[k];
}
-
+
for(i = 0; i < BN_Dst->Length; i++)
{
for(j = (BN_Dst->Length * SDRM_SIZE_BLOCK) - (i * SDRM_SIZE_BLOCK) - SDRM_SIZE_BLOCK; j < (BN_Dst->Length * SDRM_SIZE_BLOCK) - (i * SDRM_SIZE_BLOCK) ; j++)
- {
+ {
switch(bufferHex[j])
{
case '0':
BN_Dst->pData[i] |= 0xf;
break;
default:
+ {
+ free(bufferHex);
return CRYPTO_INVALID_ARGUMENT;
+ }
}
}
}
-
+
//clear time buffer
- free(bufferHex);
+ free(bufferHex);
return CRYPTO_SUCCESS;
}
cc_u8 tempChar[10];
(*numberBits) = 0;
+ if(strDestTemp == NULL)
+ {
+ return NULL;
+ }
+
d = SDRM_BN_Init(BN_Src->Size);
if( d == NULL)// fix prevent cid =89093 by guoxing.xu
{
+ free(strDestTemp);
return NULL;
}
tempREM = SDRM_BN_Init(BN_Src->Size);
num = SDRM_BN_Init(BN_Src->Size);
if( num == NULL)//fix prevent cid = 89093 by guoxing.xu
{
+ free(strDestTemp);
SDRM_BN_FREE(d);
return NULL;
}
SDRM_BN_Copy(num, BN_Src);
SDRM_BN_SetWord(d, 4);
-
-
while (!SDRM_BN_isZero(num))
{
- SDRM_BN_Div(num, tempREM, num, d);
- //itoa(tempREM->pData[0], (char *)tempChar, 10);
+ SDRM_BN_Div(num, tempREM, num, d);
+ //itoa(tempREM->pData[0], (char *)tempChar, 10);
//sprintf((char*)tempChar, "%d", tempREM->pData[0]);
snprintf((char*)tempChar, sizeof(tempChar), "%d", tempREM->pData[0]);// fix prevnet 60199 by guoxing.xu
strDestTemp[(*numberBits)] = tempChar[0];
(*numberBits)++;
}
-
if((*numberBits) != 0)
{
strDest = (cc_u8*)malloc((*numberBits) + 1);
nWordX = SDRM_ll_getMSW(pOperand, nWordX) + 1;
nWordP = SDRM_ll_getMSW(pModule, nWordX) + 1;
- // Krishna
- pTempResult = (BasicWord*) calloc(nWordX+1,BASICWORD_BYTES_COUNT);
+ pTempResult = (BasicWord *)calloc(nWordX+1,BASICWORD_BYTES_COUNT);
if (!pTempResult)
{
return CRYPTO_MEMORY_ALLOC_FAIL;
#ifdef _WIN32_WCE
srand(GetTickCount());
#else
- srand((unsigned int)time(NULL));
+
+ static int add_value = 0;
+ if(++add_value == 10000) add_value = 0;
+
+ srand(time(NULL) + add_value );
+
#endif
return SDRM_RNG_X931(crt->ctx->x931ctx->Seed, bitLength, data);
}
-/***************************** End of File *****************************/
\ No newline at end of file
+/***************************** End of File *****************************/
retVal = SDRM_Enpad_Rsaes_oaep(pbBuf, in, inLen, RSA_KeyByteLen, SDRM_HIGH_HALF(crt->ctx->rsactx->pm));
break;
case ID_NO_PADDING :
- if( inLen != RSA_KeyByteLen) // add by guoxing.xu 20140919
- {
- free(pbBuf);
- return CRYPTO_INVALID_ARGUMENT;
- }
+ if( inLen != RSA_KeyByteLen) // add by guoxing.xu 20140919
+ {
+ free(pbBuf);
+ return CRYPTO_INVALID_ARGUMENT;
+ }
memset(pbBuf, 0x00, RSA_KeyByteLen - inLen);
memcpy(pbBuf + RSA_KeyByteLen - inLen, in, inLen);
- retVal= CRYPTO_SUCCESS;// add by guoxing.xu 20140919
+ retVal= CRYPTO_SUCCESS;// add by guoxing.xu 20140919
break;
default :
free(pbBuf);
#include "cc_moo.h"
#include "cc_rc4.h"
#include "cc_snow2.h"
-#include <stdio.h>
+
////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////
{
return CRYPTO_NULL_POINTER;
}
-
if (!(((mode >= 1111) && (mode <= 1115)) || ((mode >= 1121) && (mode <= 1125))))
{
return CRYPTO_INVALID_ARGUMENT;
}
-
if (!((crt->alg == ID_AES128) && (keysize == 16)) &&
!((crt->alg == ID_AES192) && (keysize == 24)) &&
!((crt->alg == ID_AES256) && (keysize == 32)))
{
return CRYPTO_INVALID_ARGUMENT;
}
-
if ((crt->alg != ID_AES128) && (crt->alg != ID_AES192) && (crt->alg != ID_AES256))
{
return CRYPTO_INVALID_ARGUMENT;
{
return CRYPTO_INVALID_ARGUMENT;
}
-
crt->ctx->aesctx->moo = mode;
crt->ctx->aesctx->padding = PADDING;
-
if (mode != ID_DEC_ECB && mode != ID_DEC_CBC)
{
SDRM_getEncRoundKey(crt->alg, key, crt->ctx->aesctx->RoundKey);
{
SDRM_getDecRoundKey(crt->alg, key, crt->ctx->aesctx->RoundKey);
}
-
if (IV)
{
memcpy(crt->ctx->aesctx->IV, IV, SDRM_AES_BLOCK_SIZ);
{
memset(crt->ctx->aesctx->IV, 0x00, SDRM_AES_BLOCK_SIZ);
}
-
crt->ctx->aesctx->BlockLen = 0;
GET_UINT32(crt->ctx->aesctx->CTR_Count, crt->ctx->aesctx->IV + 12, 0);
-
return CRYPTO_SUCCESS;
}
cc_u8 *Block, PADDING[16];
cc_u32 BlockLen;
cc_u8 t;
- int i = 0;
-
-
if (outputLen != NULL)
{
Block = crt->ctx->aesctx->Block;
BlockLen = crt->ctx->aesctx->BlockLen;
- i = 0;
- printf("Block [%d]: %d\n", i, Block[0]);
+
if (crt->ctx->aesctx->moo >= ID_DEC_ECB)
{
}
break;
default :
- {
-
return CRYPTO_INVALID_ARGUMENT;
- }
}
//encryption
}
break;
default :
- {
- retVal = CRYPTO_INVALID_ARGUMENT;
- }
+ retVal = CRYPTO_INVALID_ARGUMENT;
break;
}
retVal = SDRM_CTR_Dec(crt->alg, Block, Block, crt->ctx->aesctx->RoundKey, crt->ctx->aesctx->IV, crt->ctx->aesctx->CTR_Count++);
break;
default :
- {
- return CRYPTO_INVALID_ARGUMENT;
- }
+ return CRYPTO_INVALID_ARGUMENT;
}
if (retVal != CRYPTO_SUCCESS)
{
case 0 :
case ID_PKCS5 :
- { i = 0;
- //for (; i < 16; i++)
- printf("Block [%d]: %d\n", i, Block[i]);
-
if ((t > SDRM_AES_BLOCK_SIZ) || (t < 1))
{
return CRYPTO_INVALID_ARGUMENT;
}
memset(PADDING, t, t);
break;
- }
case ID_SSL_PADDING :
++t;
if ((t > SDRM_AES_BLOCK_SIZ) || (t < 1))
if (outputLen != NULL)
{
*outputLen = 0;
-
- return CRYPTO_INVALID_ARGUMENT;
}
+ return CRYPTO_INVALID_ARGUMENT;
}
if (memcmp(PADDING, Block + SDRM_AES_BLOCK_SIZ - t, t) != 0)
}
-/***************************** End of File *****************************/
+/***************************** End of File *****************************/
\ No newline at end of file
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License.
*/
#ifndef _SWD_LOG_H_
#define _SWD_LOG_H_
#include <stdio.h>
#define THE_PRINTF(fmt, ARG...) printf(fmt"\n", ##ARG)
-#define SLOGV(FMT, ARG ...) THE_PRINTF("[VBOSE][%s]"FMT, LOG_TAG, ##ARG)
-#define SLOGD(FMT, ARG ...) THE_PRINTF("[DEBUG][%s]"FMT, LOG_TAG, ##ARG)
-#define SLOGI(FMT, ARG ...) THE_PRINTF("[INFO] [%s]"FMT, LOG_TAG, ##ARG)
-#define SLOGW(FMT, ARG ...) THE_PRINTF("[WARN] [%s]"FMT, LOG_TAG, ##ARG)
-#define SLOGE(FMT, ARG ...) THE_PRINTF("[ERROR][%s]"FMT, LOG_TAG, ##ARG)
-#define SLOGF(FMT, ARG ...) THE_PRINTF("[FATAL][%s]"FMT, LOG_TAG, ##ARG)
+#define SLOGV(FMT, ARG ...) THE_PRINTF("[VBOSE][%s]" FMT, LOG_TAG, ##ARG)
+#define SLOGD(FMT, ARG ...) THE_PRINTF("[DEBUG][%s]" FMT, LOG_TAG, ##ARG)
+#define SLOGI(FMT, ARG ...) THE_PRINTF("[INFO] [%s]" FMT, LOG_TAG, ##ARG)
+#define SLOGW(FMT, ARG ...) THE_PRINTF("[WARN] [%s]" FMT, LOG_TAG, ##ARG)
+#define SLOGE(FMT, ARG ...) THE_PRINTF("[ERROR][%s]" FMT, LOG_TAG, ##ARG)
+#define SLOGF(FMT, ARG ...) THE_PRINTF("[FATAL][%s]" FMT, LOG_TAG, ##ARG)
#endif
#ifndef _SWD_SS_COMMON_H_
#define _SWD_SS_COMMON_H_
-#include <stdint.h>
-
#define SS_MAX_UUID_LEN 64
#define SS_MAX_MODULE_NAME_LEN 32
#define SS_MAX_DATA_NAME_LEN 128
} ss_credential_s;
+typedef unsigned char uint8_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
typedef uint8_t CBT_OCTET;
typedef uint8_t* CBT_OCTET_PTR;
typedef uint32_t CBT_UINT32;
typedef uint32_t* CBT_UINT32_PTR;
typedef void* CBT_DATA_PTR;
typedef CBT_UINT32 CBT_BOOL;
+typedef unsigned short uint16_t;
#endif
int xcbc_init(aes_xcbc_state *xcbc, unsigned char *key, unsigned int keylen);
int xcbc_process(aes_xcbc_state *xcbc, unsigned char *in, unsigned int inlen);
-int xcbc_done(aes_xcbc_state *xcbc, unsigned char *out, size_t *outlen);
+int xcbc_done(aes_xcbc_state *xcbc, unsigned char *out, unsigned int *outlen);
#ifdef __cplusplus
}
* @retval UCI_ERROR if output is NULL.
*/
int uci_mac_final(UCI_HANDLE oh, unsigned char *output,
- size_t *output_len);
+ unsigned int *output_len);
/**
* @brief generate c-mac code
* @retval UCI_ERROR input or output is NULL..
*/
int uci_ae_encrypt(UCI_HANDLE oh, unsigned char * input, unsigned int input_len,
- unsigned char * output, size_t* output_len);
+ unsigned char * output, unsigned int* output_len);
/**
* @brief RSA Decryption
* @retval UCI_ERROR input or output is NULL.
*/
int uci_ae_decrypt(UCI_HANDLE oh, unsigned char * input, unsigned int input_len,
- unsigned char * output, size_t* output_len);
+ unsigned char * output, unsigned int* output_len);
/**
* @brief RSA Decryption using CRT
* @retval UCI_ERROR if hash or signature is NULL.
*/
int uci_ds_sign(UCI_HANDLE oh, unsigned char * hash, unsigned int hash_len,
- unsigned char * signature, size_t* sign_len);
+ unsigned char * signature, unsigned int* sign_len);
/**
* @brief generate signature for given value
int uci_authcrypt_update_aad(UCI_HANDLE oh, unsigned char *aad,
unsigned int aad_len);
int uci_authcrypt_update(UCI_HANDLE oh, unsigned char *src,
- unsigned int src_len, unsigned char *dest, size_t *dest_len);
+ unsigned int src_len, unsigned char *dest, unsigned int *dest_len);
int uci_authcrypt_encryptfinal(UCI_HANDLE oh, unsigned char *src,
- unsigned int src_len, unsigned char *dest, size_t *dest_len,
- unsigned char *tag, size_t *tag_len);
+ unsigned int src_len, unsigned char *dest, unsigned int *dest_len,
+ unsigned char *tag, unsigned int *tag_len);
int uci_authcrypt_decryptfinal(UCI_HANDLE oh, unsigned char *src,
- unsigned int src_len, unsigned char *dest, size_t *dest_len,
+ unsigned int src_len, unsigned char *dest, unsigned int *dest_len,
unsigned char *tag, unsigned int tag_len);
/**
*/
int cryptocore_mac_final(UCI_HANDLE oh, unsigned char *output,
- size_t *output_len);
+ unsigned int *output_len);
/**
* @brief generate c-mac code
*/
int cryptocore_ae_encrypt(UCI_HANDLE oh, unsigned char * input,
- unsigned int input_len, unsigned char * output, size_t* output_len);
+ unsigned int input_len, unsigned char * output, unsigned int* output_len);
/**
* @brief RSA Decryption
* @retval UCI_ERROR other error occured.
*/
int cryptocore_ae_decrypt(UCI_HANDLE oh, unsigned char * input,
- unsigned int input_len, unsigned char * output, size_t* output_len);
+ unsigned int input_len, unsigned char * output, unsigned int* output_len);
/**
* @brief RSA Decryption using CRT
* @retvla UCI_ERROR other error occured.
*/
int cryptocore_ae_decryptbycrt(UCI_HANDLE oh, unsigned char * input,
- unsigned int input_len, unsigned char * output, size_t * output_len);
+ unsigned int input_len, unsigned char * output, unsigned int* output_len);
/**
* @brief generate signature for given value
* @retval UCI_ERROR other error occured.
*/
int cryptocore_ds_sign(UCI_HANDLE oh, unsigned char * hash,
- unsigned int hash_len, unsigned char * signature, size_t* sign_len);
+ unsigned int hash_len, unsigned char * signature, unsigned int* sign_len);
/**
* @brief generate signature for given value
* @brief UCI handle.
*
*/
-typedef intptr_t UCI_HANDLE;
+typedef int UCI_HANDLE;
/**
* @brief UCI return error type.
*
}
return 1;
}
-int xcbc_done(aes_xcbc_state *xcbc, unsigned char *out, size_t *outlen) {
+int xcbc_done(aes_xcbc_state *xcbc, unsigned char *out, unsigned int *outlen) {
unsigned int x;
if (xcbc == NULL || out == NULL) {
return 0;
ctx = (uci_context_s*)OsaMalloc(sizeof(uci_context_s));
ctx->imp = (aes_xcbc_state *)OsaMalloc(sizeof(aes_xcbc_state));
ctx->alg = ID_UCI_XCBCMAC;
- return (UCI_HANDLE)ctx;
+ return (int)ctx;
}
if (conf == UCI_SW_CRYPTOCORE) {
return cryptocore_context_alloc(algorithm);
}
int uci_mac_final(UCI_HANDLE oh, unsigned char *output,
- size_t *output_len) {
+ unsigned int *output_len) {
int ret = 0;
uci_context_s *pctx = (uci_context_s*)oh;
if (pctx->alg == ID_UCI_XCBCMAC) {
int uci_mac_get_mac(UCI_HANDLE oh, unsigned char *key, unsigned int key_len,
unsigned char *msg, unsigned int msg_len, unsigned char *output,
- size_t *output_len) {
- int ret = 0;
+ unsigned int *output_len) {
+ //int ret = 0;
uci_context_s *pctx = (uci_context_s*)oh;
if (pctx->alg == ID_UCI_XCBCMAC) {
if (xcbc_init((aes_xcbc_state *)(pctx->imp), key, key_len) != 1) {
return UCI_SUCCESS;
}
- unsigned int uioutput_len = (unsigned int)(*output_len);
- ret = cryptocore_mac_getmac(oh, key, key_len, msg, msg_len, output,
- &uioutput_len);
- *output_len = (size_t)uioutput_len;
- return ret;
+ return cryptocore_mac_getmac(oh, key, key_len, msg, msg_len, output,
+ output_len);
}
int uci_se_init(UCI_HANDLE oh, unsigned int mode, unsigned padding,
}
int uci_ae_encrypt(UCI_HANDLE oh, unsigned char *input, unsigned int input_len,
- unsigned char *output, size_t *output_len) {
+ unsigned char *output, unsigned int *output_len) {
return cryptocore_ae_encrypt(oh, input, input_len, output, output_len);
}
int uci_ae_decrypt(UCI_HANDLE oh, unsigned char *input, unsigned int input_len,
- unsigned char *output, size_t *output_len) {
+ unsigned char *output, unsigned int *output_len) {
return cryptocore_ae_decrypt(oh, input, input_len, output, output_len);
}
int uci_ae_decryptbycrt(UCI_HANDLE oh, unsigned char *input,
- unsigned int input_len, unsigned char *output, size_t *output_len) {
+ unsigned int input_len, unsigned char *output, unsigned int *output_len) {
return cryptocore_ae_decryptbycrt(oh, input, input_len, output, output_len);
}
}
int uci_ds_sign(UCI_HANDLE oh, unsigned char *hash, unsigned int hash_len,
- unsigned char *signature, size_t *sign_len) {
+ unsigned char *signature, unsigned int *sign_len) {
return cryptocore_ds_sign(oh, hash, hash_len, signature, sign_len);
}
return UCI_ERROR;
}
int uci_authcrypt_update(UCI_HANDLE oh, unsigned char *src,
- unsigned int src_len, unsigned char *dest, size_t *dest_len) {
+ unsigned int src_len, unsigned char *dest, unsigned int *dest_len) {
#if 0
uci_context_s *pctx = (uci_context_s*)oh;
gcm_context *gctx;
return UCI_ERROR;
}
int uci_authcrypt_encryptfinal(UCI_HANDLE oh, unsigned char *src,
- unsigned int src_len, unsigned char *dest, size_t *dest_len,
- unsigned char *tag, size_t *tag_len) {
+ unsigned int src_len, unsigned char *dest, unsigned int *dest_len,
+ unsigned char *tag, unsigned int *tag_len) {
#if 0
uci_context_s *pctx = (uci_context_s*)oh;
gcm_context *gctx = NULL;
return UCI_ERROR;
}
int uci_authcrypt_decryptfinal(UCI_HANDLE oh, unsigned char *src,
- unsigned int src_len, unsigned char *dest, size_t *dest_len,
+ unsigned int src_len, unsigned char *dest, unsigned int *dest_len,
unsigned char *tag, unsigned int tag_len) {
#if 0
uci_context_s *pctx = (uci_context_s*)oh;
}
int cryptocore_mac_final(UCI_HANDLE oh, unsigned char *output,
- size_t *output_len) {
+ unsigned int *output_len) {
int ret;
uci_context_s *pctx = (uci_context_s*)oh;
if (pctx == NULL) {
return UCI_INVALID_HANDLE;
}
- cc_u32 output_len32 = (cc_u32)(*output_len);
ret = ((CryptoCoreContainer *)pctx->imp)->MAC_final(
- (CryptoCoreContainer*)(pctx->imp), output, &output_len32);
- *output_len = (size_t)output_len32;
-
+ (CryptoCoreContainer*)(pctx->imp), output, output_len);
if (ret != CRYPTO_SUCCESS) {
return UCI_ERROR;
}
}
int cryptocore_ae_encrypt(UCI_HANDLE oh, unsigned char *input,
- unsigned int input_len, unsigned char *output, size_t *output_len) {
+ unsigned int input_len, unsigned char *output, unsigned int *output_len) {
int ret;
uci_context_s *pctx = (uci_context_s*)oh;
if (pctx->alg < ID_UCI_RSA || pctx->alg > ID_UCI_RSA512) {
return UCI_INVALID_HANDLE;
}
-
- cc_u32 output_len32 = (cc_u32)(*output_len);
ret = ((CryptoCoreContainer *)pctx->imp)->AE_encrypt(
- ((CryptoCoreContainer*)pctx->imp), input, input_len, output, &output_len32);
- *output_len = (size_t)output_len32;
+ ((CryptoCoreContainer*)pctx->imp), input, input_len, output, output_len);
if (ret == CRYPTO_MSG_TOO_LONG) {
return UCI_MSG_TOO_LONG;
}
}
int cryptocore_ae_decrypt(UCI_HANDLE oh, unsigned char *input,
- unsigned int input_len, unsigned char *output, size_t *output_len) {
+ unsigned int input_len, unsigned char *output, unsigned int *output_len) {
int ret;
uci_context_s *pctx = (uci_context_s*)oh;
if (pctx->alg < ID_UCI_RSA || pctx->alg > ID_UCI_RSA512) {
return UCI_INVALID_HANDLE;
}
-
- cc_u32 output_len32 = (cc_u32)(*output_len);
ret = ((CryptoCoreContainer *)pctx->imp)->AE_decrypt(
- ((CryptoCoreContainer*)pctx->imp), input, input_len, output, &output_len32);
- *output_len = (size_t)output_len32;
-
+ ((CryptoCoreContainer*)pctx->imp), input, input_len, output, output_len);
if (ret == CRYPTO_MSG_TOO_LONG) {
return UCI_MSG_TOO_LONG;
}
}
int cryptocore_ae_decryptbycrt(UCI_HANDLE oh, unsigned char *input,
- unsigned int input_len, unsigned char *output, size_t *output_len) {
+ unsigned int input_len, unsigned char *output, unsigned int *output_len) {
int ret;
uci_context_s *pctx = (uci_context_s*)oh;
// ctr=(CryptoCoreContainer *)(pctx->imp);
// ctr->MD_update(ctr,msg,msg_len);
- cc_u32 output_len32 = (cc_u32)(*output_len);
ret = ((CryptoCoreContainer *)pctx->imp)->AE_decryptByCRT(
- ((CryptoCoreContainer*)pctx->imp), input, input_len, output, &output_len32);
- *output_len = (size_t)output_len32;
+ ((CryptoCoreContainer*)pctx->imp), input, input_len, output, output_len);
if (ret == CRYPTO_MSG_TOO_LONG) {
return UCI_MSG_TOO_LONG;
}
}
int cryptocore_ds_sign(UCI_HANDLE oh, unsigned char *hash,
- unsigned int hash_len, unsigned char *signature, size_t *sign_len) {
+ unsigned int hash_len, unsigned char *signature, unsigned int *sign_len) {
int ret;
uci_context_s *pctx = (uci_context_s*)oh;
return UCI_INVALID_HANDLE;
}
- cc_u32 sign_len32 = (cc_u32)(*sign_len);
ret = ((CryptoCoreContainer *)pctx->imp)->DS_sign(
- ((CryptoCoreContainer*)pctx->imp), hash, hash_len, signature, &sign_len32);
- *sign_len = (size_t)sign_len32;
+ ((CryptoCoreContainer*)pctx->imp), hash, hash_len, signature, sign_len);
if (ret == CRYPTO_MSG_TOO_LONG) {
return UCI_MSG_TOO_LONG;
}
--- /dev/null
+/*
+ * ace.c
+ *
+ * This source file is proprietary property of Samsung Electronics Co., Ltd.
+ *
+ * Copyright (C) 2011 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Contact: Jaemin Ryu <jm77.ryu@samsung.com>
+ *
+ */
+
+#include "tee_internal_api.h"
+
+#define TZSL_CRYPTO_PADDING
+#define MAX_BLOCK_SIZE 64
+#define MAX_IVEC_SIZE 16
+
+#define TEE_ALG_GENERATE_SECRET_KEY 0x90000000
+#define TEE_ALG_GENERATE_RSA_KEY 0x90000001
+#define TEE_ALG_GENERATE_DSA_KEY 0x90000002
+#define TEE_ALG_GENERATE_DH_KEY 0x90000003
+
+typedef enum
+{
+ CRYPTO_HW_ENGINE,
+ CRYPTO_SW_ENGINE,
+ CRYPTO_NO_ENGINE
+}crypto_internal_engine;
+
+typedef enum
+{
+ CRYPTO_USE_DEFAULT_ENGINE,
+ CRYPTO_USE_SW_ENGINE
+}crypto_internal_engine_type;
+
+typedef struct
+{
+ TEE_OperationInfo info;
+ TEE_ObjectHandle key1;
+ TEE_ObjectHandle key2;
+ int crypto; // handle to crypto driver or ponter to crypto library context
+ unsigned char data[MAX_BLOCK_SIZE]; // accumulated stream data
+ unsigned int data_len; // accumulated data length
+ unsigned int block_len; // cipher block data length
+} crypto_internal_operation;
+
+typedef struct
+{
+ unsigned char *buffer;
+ unsigned int size;
+} crypto_internal_keydata;
+
+typedef struct
+{
+ crypto_internal_keydata secret; /* TEE_ATTR_SECRET_VALUE */
+ crypto_internal_keydata rsa_modulus; /* TEE_ATTR_RSA_MODULUS */
+ crypto_internal_keydata rsa_public; /* TEE_ATTR_RSA_PUBLIC_EXPONENT */
+ crypto_internal_keydata rsa_private; /* TEE_ATTR_RSA_PRIVATE_EXPONENT */
+ crypto_internal_keydata rsa_prime1; /* TEE_ATTR_RSA_PRIME1 */
+ crypto_internal_keydata rsa_prime2; /* TEE_ATTR_RSA_PRIME2 */
+ crypto_internal_keydata rsa_exponent1; /* TEE_ATTR_RSA_EXPONENT1 */
+ crypto_internal_keydata rsa_exponent2; /* TEE_ATTR_RSA_EXPONENT2 */
+ crypto_internal_keydata rsa_coefficient; /* TEE_ATTR_RSA_COEFFICIENT */
+} crypto_internal_keystruct;
+
+void crypto_internal_set_engine(int set);
+int crypto_internal_open(crypto_internal_operation *operation);
+int crypto_internal_close(crypto_internal_operation *operation);
+int crypto_internal_init(crypto_internal_operation *operation, crypto_internal_keystruct *key, unsigned char *ivec, size_t ivec_len);
+int crypto_internal_update(crypto_internal_operation *operation, unsigned char *src_data, size_t src_len, unsigned char *dst_data, size_t *dst_len);
+int crypto_internal_final(crypto_internal_operation *operation, unsigned char *src_data, size_t src_len, unsigned char *dst_data, size_t *dst_len);
+
--- /dev/null
+/*
+ * permission.h
+ *
+ * This source file is proprietary property of Samsung Electronics Co., Ltd.
+ *
+ * Copyright (C) 2011 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ */
+
+#ifndef __PERMISSION_H__
+#define __PERMISSION_H__
+
+#include <tee_internal_api.h>
+
+#define PERMISSION_CHECK(variable) \
+ if(CheckPermission(variable)) { \
+ LOGE(SSF_LIB, "Permission Denied - Function %s() is not permitted." , __FUNCTION__ ); \
+ return TEE_ERROR_ACCESS_DENIED; }
+
+#define PERMISSION_CHECK_RETURN_VOID(variable) \
+ if(CheckPermission(variable)) { \
+ LOGE(SSF_LIB, "Permission Denied - Function %s() is not permitted." , __FUNCTION__ ); \
+ return; }
+
+typedef enum {
+ PERM_CRYPTO = 0x00000001,
+ PERM_STORAGE = 0x00000002,
+ PERM_TIME = 0x00000004,
+ PERM_ARITHMETIC = 0x00000008,
+ PERM_DISPLAY = 0x00000010,
+ PERM_NETWORK = 0x00000020,
+} ACCESS_PERMISSION;
+
+typedef enum {
+ TA_PRIVILEGE_PUBLIC=1,
+ TA_PRIVILEGE_PARTNER,
+ TA_PRIVILEGE_PLATFORM,
+} TA_PRIVILEGE;
+
+#define TA_UID 1
+#define TA_PLATFORM_GID 100
+#define TA_PARTNER_GID 200
+#define TA_PUBLIC_GID 255
+
+#define GP_TEE_TIME_PROTECTION_LEVEL_PROPERTY_REE 100
+#define GP_TEE_TIME_PROTECTION_LEVEL_PROPERTY_TEE 1000
+
+int CheckPermission(const int flag);
+
+#endif
+
// po share rule
int init_share_info(po_share_info* share_info);
-int check_share_rule(po_share_info* share_info, uint32_t handleFlags);
-int update_share_info(po_share_info* share_info, uint32_t handleFlags,
- int b_open);
+int check_share_rule(po_share_info* share_info, uint32_t handleFlags, uint32_t origFlags);
+int update_share_info(po_share_info* share_info, uint32_t handleFlags, uint32_t origFlags,
+ int b_open, persistent_object* po);
int release_share_info(po_share_info* share_info);
void lock_po_share_info(po_share_info* share_info);
void unlock_po_share_info(po_share_info* share_info);
// po list operations
void add_to_po_list(persistent_object* po);
void rem_from_po_list(persistent_object* po);
+po_user* get_po_user_from_po_list(uint32_t storageID, const void* objectID,
+ size_t objectIDLen);
void cleanup();
void regist_clean_up();
+++ /dev/null
-/** \r
- * @file app_debug.h\r
- * @brief \r
- * @author longhai.wu (longhai.wu@samsung.com)\r
- * @version 0.9 Initial Draft Version\r
- * @date 2013/04/13\r
- * - Revision History :\r
- * Version Date Author Detail description \r
- * --------------------------------------------------------------------\r
- * 0.9 2013/04/03 longhai.wu \r
- * --------------------------------------------------------------------\r
- */\r
-\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include <app_debug.h>\r
-\r
-//#define PRINT_LOG_TO_CONSOLE\r
-#ifdef PRINT_LOG_TO_CONSOLE\r
-#include <fcntl.h>\r
-#define portname "/dev/ttyS0"\r
-static int m_fd = -1;\r
-int g_app_svc_dbglvl = TRUSTAPP_DEBUG_LEVEL_NON;\r
-\r
-int app_open_log_file( char *processName)\r
-{\r
- \r
- /* save log to LOGFILE */\r
- \r
- m_fd = open( portname,O_RDWR | O_NOCTTY | O_NONBLOCK);\r
- if(m_fd < 0)\r
- {\r
- return -1;\r
- }\r
-\r
- write(m_fd,processName,strlen(processName));\r
- \r
- memset(one_time_print_buffer,0,sizeof(one_time_print_buffer));\r
- return 0;\r
-\r
-}\r
-\r
-void app_close_log_file(void)\r
-{\r
-\r
- close(m_fd);\r
- m_fd = -1;\r
-}\r
-void app_print_log(unsigned char logBuffer[])\r
-{\r
-\r
- write(m_fd,logBuffer,strlen(logBuffer));\r
-}\r
-\r
-#else\r
-#define SVC1_LOGFILE "/opt/usr/apps/tz_simulator/data/SWDLog.txt" \r
-\r
-static FILE *fp = NULL;\r
-\r
-#ifdef _TURN_ON_TALOG_\r
-int g_app_svc_dbglvl = TRUSTAPP_DEBUG_LEVEL_ALL;\r
-#else\r
-int g_app_svc_dbglvl = TRUSTAPP_DEBUG_LEVEL_NON;\r
-#endif\r
-\r
-int app_open_log_file(char *processName)\r
-{\r
- \r
- /* save log to LOGFILE */\r
- fp = fopen(SVC1_LOGFILE, "a+");\r
- if(!fp)\r
- {\r
- return -1;\r
- }\r
- \r
- fprintf(fp,"Trust App name : %s.\n",processName); \r
- fflush(fp);\r
- \r
- memset(one_time_print_buffer,0,sizeof(one_time_print_buffer));\r
- return 0;\r
-\r
-}\r
-\r
-void app_close_log_file(void)\r
-{\r
-\r
- fclose(fp);\r
- fp = NULL;\r
-}\r
-void app_print_log(unsigned char logBuffer[])\r
-{\r
-\r
- fprintf(fp,"%s",logBuffer);\r
- fflush(fp);\r
-}\r
-\r
-void app_print_log_test(unsigned char logBuffer[])\r
-{\r
-\r
- fprintf(fp,"%s",logBuffer);\r
- fflush(fp);\r
-}\r
-\r
-\r
-\r
-\r
-#endif\r
-\r
--- /dev/null
+/** \r
+ * @file app_debug.h\r
+ * @brief \r
+ * @author longhai.wu (longhai.wu@samsung.com)\r
+ * @version 0.9 Initial Draft Version\r
+ * @date 2013/04/13\r
+ * - Revision History :\r
+ * Version Date Author Detail description \r
+ * --------------------------------------------------------------------\r
+ * 0.9 2013/04/03 longhai.wu \r
+ * --------------------------------------------------------------------\r
+ */\r
+\r
+#include <stdio.h>\r
+#include <string.h>\r
+#include <app_debug.h>\r
+\r
+//#define PRINT_LOG_TO_CONSOLE\r
+#ifdef PRINT_LOG_TO_CONSOLE\r
+#include <fcntl.h>\r
+#define portname "/dev/ttyS0"\r
+static int m_fd = -1;\r
+int g_app_svc_dbglvl = TRUSTAPP_DEBUG_LEVEL_NON;\r
+\r
+int app_open_log_file( char *processName)\r
+{\r
+ \r
+ /* save log to LOGFILE */\r
+ \r
+ m_fd = open( portname,O_RDWR | O_NOCTTY | O_NONBLOCK);\r
+ if(m_fd < 0)\r
+ {\r
+ return -1;\r
+ }\r
+\r
+ write(m_fd,processName,strlen(processName));\r
+ \r
+ memset(one_time_print_buffer,0,sizeof(one_time_print_buffer));\r
+ return 0;\r
+\r
+}\r
+\r
+void app_close_log_file(void)\r
+{\r
+\r
+ close(m_fd);\r
+ m_fd = -1;\r
+}\r
+void app_print_log(unsigned char logBuffer[])\r
+{\r
+\r
+ write(m_fd,logBuffer,strlen(logBuffer));\r
+}\r
+\r
+#else\r
+#define SVC1_LOGFILE "/opt/usr/apps/tz_simulator/data/SWDLog.txt" \r
+\r
+static FILE *fp = NULL;\r
+\r
+#ifdef _TURN_ON_TALOG_\r
+int g_app_svc_dbglvl = TRUSTAPP_DEBUG_LEVEL_ALL;\r
+#else\r
+int g_app_svc_dbglvl = TRUSTAPP_DEBUG_LEVEL_NON;\r
+#endif\r
+\r
+int app_open_log_file(char *processName)\r
+{\r
+ \r
+ /* save log to LOGFILE */\r
+ fp = fopen(SVC1_LOGFILE, "a+");\r
+ if(!fp)\r
+ {\r
+ return -1;\r
+ }\r
+ \r
+ fprintf(fp,"Trust App name : %s.\n",processName); \r
+ fflush(fp);\r
+ \r
+ memset(one_time_print_buffer,0,sizeof(one_time_print_buffer));\r
+ return 0;\r
+\r
+}\r
+\r
+void app_close_log_file(void)\r
+{\r
+\r
+ fclose(fp);\r
+ fp = NULL;\r
+}\r
+void app_print_log(unsigned char logBuffer[])\r
+{\r
+\r
+ fprintf(fp,"%s",logBuffer);\r
+ fflush(fp);\r
+}\r
+\r
+void app_print_log_test(unsigned char logBuffer[])\r
+{\r
+\r
+ fprintf(fp,"%s",logBuffer);\r
+ fflush(fp);\r
+}\r
+\r
+\r
+\r
+\r
+#endif\r
+\r
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssf_arithmetic.c
- *
- * Description: SSF arithmetic functions
- *
- * Version: 1.0
- * Created: 29 June 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: Cheryl (cb), cheryl.b@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include <log.h>
-#include "tee_internal_api.h"
-#include "CC_API.h"
-#include "base/cc_bignum.h"
-
-/*-----------------------------------------------------------------------------
- * MACROS
- *-----------------------------------------------------------------------------*/
-#define TAG SSF_LIB
-#define SDRM_API_METADATA_LENGTH_IN_U32 4
-#define CNT_OF_BIT_IN_BYTE 8
-#define PASS_NOT_IMP_CODE
-
-/*-----------------------------------------------------------------------------
- * TEE API implementation
- *-----------------------------------------------------------------------------*/
-/**
- * The TEE_BigIntInit function initializes bigInt and sets its represented
- * value to zero. This function assumes that bigInt points to a memory area
- * of len uint32_t.
- * @param value A pointer to the TEE_BigInt to be initialized
- * @param length The size in uint32_t of the memory pointed to by bigInt
- */
-void TEE_BigIntInit(TEE_BigInt* value, const size_t length) {
-
- LOGD(TAG, "TEE_BigIntInit - length : %d", length);
- uint32_t teeMaxBigIntSize;
- TEE_Result result = TEE_GetPropertyAsU32(
- (TEE_PropSetHandle)TEE_PROPSET_TEE_IMPLEMENTATION,
- "gpd.tee.arith.maxBigIntSize", &teeMaxBigIntSize);
- LOGD(TAG, "TEE_GetPropertyAsU32(arith.maxBigIntSize) : %d (ret:%d)",
- teeMaxBigIntSize, result);
-#ifndef PASS_NOT_IMP_CODE
- if(result == TEE_SUCCESS)
- {
- if(teeMaxBigIntSize == 0 ||
- (length - SDRM_API_METADATA_LENGTH_IN_U32) * SDRM_SIZE_OF_DWORD * CNT_OF_BIT_IN_BYTE < teeMaxBigIntSize)
- {
- LOGE(TAG, "Panic Reason: BN size is creater than max allowed");
- TEE_Panic(TEE_ERROR_OUT_OF_MEMORY);
- }
- }
-#endif
- if (length <= SDRM_API_METADATA_LENGTH_IN_U32) {
- LOGE(TAG, "Panic Reason: insufficient length");
- TEE_Panic(TEE_ERROR_OUT_OF_MEMORY);
- }
- SDRM_BIG_NUM *bn = SDRM_BN_Alloc((cc_u8*)value,
- length - SDRM_API_METADATA_LENGTH_IN_U32);
- if (bn == NULL) {
- LOGE(TAG, "Panic Reason: SDRM_BN_Alloc fail");
- TEE_Panic(TEE_ERROR_OUT_OF_MEMORY);
- }
- LOGD(TAG, "Success");
-}
-
-/**
- * The TEE_BigIntConvertFromOctetString function converts a bufferLen byte
- * octet string buffer into a TEE_BigInt format. The octet string is in most
- * significant byte first representation. The input parameter sign will set
- * the sign of dest. It will be set to negative if sign<0 and to positive if
- * sign>=0.
- * @param dest Pointer to a TEE_BigInt to hold the result
- * @param buffer Pointer to the buffer containing the octet string
- * representation of the integer
- * @param sz_buffer The length of *buffer in bytes
- * @param sign The sign of dest is set to the sign of sign
- */
-TEE_Result TEE_BigIntConvertFromOctetString(TEE_BigInt* dest,
- const uint8_t* buffer, const size_t sz_buffer, const int32_t sign) {
-
- LOGD(TAG,
- "TEE_BigIntConvertFromOctetString - dest:%p buffer:%p sz_buffer:%d sign:%d",
- dest, buffer, sz_buffer, sign);
- TEE_Result result = TEE_SUCCESS;
- SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)dest;
-
- if (bn->Size * SDRM_SIZE_OF_DWORD < sz_buffer) {
- LOGD(TAG, "Fail Reason: TEE_ERROR_OVERFLOW(%d %d)",
- bn->Size * SDRM_SIZE_OF_DWORD, sz_buffer);
- return TEE_ERROR_OVERFLOW;
- }
- int ret = SDRM_OS2BN((cc_u8*)buffer, sz_buffer, bn);
- if (ret == CRYPTO_SUCCESS) {
- bn->sign = ((sign < 0) ? 1 : 0);
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_OS2BN fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- return result;
-}
-
-/**
- * The TEE_BigIntConvertToOctetString function converts the absolute value of
- * an integer in TEE_BigInt format into an octet string. The octet string is
- * written in a most significant byte first representation.
- * @param buffer Output buffer where converted octet string representation
- * of the integer is written
- * @param sz_buffer_out The length of *buffer in bytes
- * @param value Pointer to the integer that will be converted to an octet
- * string
- */
-TEE_Result TEE_BigIntConvertToOctetString(void* buffer, size_t* sz_buffer_out,
- const TEE_BigInt* value) {
-
- LOGD(TAG, "TEE_BigIntConvertToOctetString - buffer:%p value:%p", buffer,
- value);
- TEE_Result result = TEE_SUCCESS;
- SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)value;
- if (*sz_buffer_out == 0) {
- if (bn->Length != 0) {
- *sz_buffer_out = bn->Length * 4;
- result = TEE_ERROR_SHORT_BUFFER;
- }
- return result;
- }
- int ret = SDRM_BN2OS(bn, *sz_buffer_out, (cc_u8 *)buffer);
- if (ret == CRYPTO_BUFFER_TOO_SMALL || ret == CRYPTO_NULL_POINTER) {
- LOGD(TAG, "Fail Reason: CRYPTO_BUFFER_TOO_SMALL or CRYPTO_NULL_POINTER");
- *sz_buffer_out = bn->Length * 4;
- result = TEE_ERROR_SHORT_BUFFER;
- } else if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN2OS fail(%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- return result;
-}
-
-/**
- * The TEE_BigIntConvertFromS32 function sets *result to the value input.
- * @param result Pointer to a TEE_BigInt to store the result
- * @param input Input value
- */
-void TEE_BigIntConvertFromS32(TEE_BigInt* result, const int32_t input) {
- SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)result;
- bn->pData[0] = ((input < 0) ? (input * -1) : (input));
- bn->Length = 1;
- bn->sign = ((input < 0) ? 1 : 0);
- LOGD(TAG, "Success");
-}
-
-/**
- * The TEE_BigIntConvertToS32 function sets *result to the value of input,
- * including the sign of input. If input does not fit within an int32_t,
- * the value of *result is undefined.
- * @param result Pointer to an int32_t to store the result
- * @param input Pointer to the input value
- */
-TEE_Result TEE_BigIntConvertToS32(int32_t* value_result,
- const TEE_BigInt* input) {
- SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)input;
- *value_result = (bn->sign == 1) ? (bn->pData[0] * -1) : (bn->pData[0]);
- LOGD(TAG, "Success");
- return TEE_SUCCESS;
-}
-
-/**
- * The TEE_BigIntCmp function checks whether op1>op2, op1==op2, or op1<op2.
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- */
-int32_t TEE_BigIntCmp(const TEE_BigInt* op1, const TEE_BigInt* op2) {
- SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
- int ret = SDRM_BN_Cmp_sign(bn1, bn2);
- LOGD(TAG, "Success");
- return ret;
-}
-
-/**
- * The TEE_BigIntCmpS32 function checks whether value1_raw>value2,
- * value1_raw==value2, or value1_raw<value2.
- * @param value1_raw Pointer to the first operand
- * @param value2 Pointer to the second operand
- */
-int32_t TEE_BigIntCmpS32(const TEE_BigInt* value1_raw, const int32_t value2) {
- int32_t value1 = 0;
- TEE_Result result = TEE_BigIntConvertToS32(&value1, value1_raw);
- if (result != TEE_SUCCESS) {
- LOGE(TAG, "Panic Reason: TEE_BigIntConvertToS32 fail");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- int ret = 0;
- if (value1 == value2)
- ret = 0;
- else if (value1 > value2)
- ret = 1;
- else ret = -1;
- return ret;
-}
-
-/**
- * The TEE_BigIntShiftRight function computes
- * |destination_raw| = |source_raw| >> bits and destination_raw will have the
- * same sign as source_raw.4 If bits is greater than the bit length of
- * source_raw then the result is zero. destination_raw and source_raw MAY
- * point to the same memory region.
- * @param destination_raw Pointer to TEE_BigInt to hold the shifted result
- * @param source_raw Pointer to the operand to be shifted
- * @param bits Number of bits to shift
- */
-void TEE_BigIntShiftRight(TEE_BigInt* destination_raw,
- const TEE_BigInt* source_raw, const size_t bits) {
- SDRM_BIG_NUM *dstBn = (SDRM_BIG_NUM*)destination_raw;
- SDRM_BIG_NUM *srcBn = (SDRM_BIG_NUM*)source_raw;
- int ret = SDRM_BN_SHR(dstBn, srcBn, bits);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_SHR fail");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntGetBit function returns the indexth bit of the natural binary
- * representation of |object_raw|. A true return value indicates a \931\94 and a
- * false return value indicates a \930\94 in the indexth position. If index is
- * larger than the number of bits in object_raw, the return value is false,
- * thus indicating a \930\94.
- * @param object_raw Pointer to the integer
- * @param index The offset of the bit to be read, starting at offset 0 for the
- * least significant bit
- */
-bool TEE_BigIntGetBit(const TEE_BigInt* object_raw, const uint32_t index) {
- SDRM_BIG_NUM *objBn = (SDRM_BIG_NUM*)object_raw;
- bool bitValue = (bool)SDRM_BN_num_bits_index(objBn, index);
- LOGD(TAG, "Success");
- return bitValue;
-
-}
-
-/**
- * The TEE_BigIntGetBitCount function returns the number of bits in the
- * natural binary representation of |object_raw|; that is, the magnitude of
- * object_raw.
- * @param object_raw Pointer to the integer
- */
-uint32_t TEE_BigIntGetBitCount(const TEE_BigInt* object_raw) {
- SDRM_BIG_NUM *objBn = (SDRM_BIG_NUM*)object_raw;
- int retCnt = SDRM_BN_num_bits(objBn);
- LOGD(TAG, "Success");
- return retCnt;
-}
-
-/**
- * The TEE_BigIntAdd function computes dest = op1 + op2. All or some of dest,
- * op1, and op2 MAY point to the same memory region.
- * @param dest Pointer to TEE_BigInt to store the result op1 + op2
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- */
-void TEE_BigIntAdd(TEE_BigInt* dest, const TEE_BigInt* op1,
- const TEE_BigInt* op2) {
- SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
- SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
- int ret = SDRM_BN_Add(dst, bn1, bn2);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_Add fail");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntSub function computes dest = op1 \96 op2. All or some of dest,
- * op1, and op2 MAY point to the same memory region.
- * @param dest Pointer to TEE_BigInt to store the result op1 - op2
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- */
-void TEE_BigIntSub(TEE_BigInt* dest, const TEE_BigInt* op1,
- const TEE_BigInt* op2) {
- SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
- SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
- int ret = SDRM_BN_Sub(dst, bn1, bn2);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_Sub fail");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntNeg function negates an operand: dest = -op. dest and op MAY
- * point to the same memory region.
- * @param dest Pointer to TEE_BigInt to store the result -op
- * @param op Pointer to the operand to be negated
- */
-void TEE_BigIntNeg(TEE_BigInt* dest, const TEE_BigInt* op) {
- SDRM_BIG_NUM *bnOp = (SDRM_BIG_NUM*)op;
- if (dest == op)
- bnOp->sign = ((bnOp->sign == 1) ? 0 : 1);
- else {
- SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
- SDRM_BN_Copy(dst, bnOp);
- dst->sign = ((dst->sign == 1) ? 0 : 1);
- }
- LOGD(TAG, "Success");
-}
-
-/**
- * The TEE_BigIntMul function computes dest = op1 * op2. All or some of dest,
- * op1, and op2 MAY point to the same memory region.
- * @param dest Pointer to TEE_BigInt to store the result op1 * op2
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- */
-void TEE_BigIntMul(TEE_BigInt* dest, const TEE_BigInt* op1,
- const TEE_BigInt* op2) {
- SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
- SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
- int ret = SDRM_BN_Mul(dst, bn1, bn2);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_Mul fail");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntSquare function computes dest = op * op. dest and op MAY point
- * to the same memory region.
- * @param dest Pointer to TEE_BigInt to store the result op * op
- * @param op Pointer to the operand to be squared
- */
-void TEE_BigIntSquare(TEE_BigInt* dest, const TEE_BigInt* op) {
- TEE_BigIntMul(dest, op, op);
- LOGD(TAG, "Called");
-}
-
-/**
- * The TEE_BigIntDiv function computes dest_r and dest_q such that
- * op1 = dest_q * op2 + dest_r. It will round dest_q towards zero and dest_r
- * will have the same sign as op1.
- * @param dest_q Pointer to a TEE_BigInt to store the quotient.
- * dest_q can be NULL.
- * @param dest_r Pointer to a TEE_BigInt to store the remainder.
- * dest_r can be NULL.
- * @param op1 Pointer to the first operand, the dividend
- * @param op2 Pointer to the second operand, the divisor
- */
-void TEE_BigIntDiv(TEE_BigInt* dest_q, TEE_BigInt* dest_r,
- const TEE_BigInt* op1, const TEE_BigInt* op2) {
- SDRM_BIG_NUM *dst_q = (SDRM_BIG_NUM*)dest_q;
- SDRM_BIG_NUM *dst_r = (SDRM_BIG_NUM*)dest_r;
- SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
-
- if (dst_q == NULL) {
- SDRM_BIG_NUM *tmp = SDRM_BN_Init(bn1->Size);
- if (tmp != NULL) {
- SDRM_BN_Copy(tmp, bn1);
- dst_q = tmp;
- }
- }
- int ret = SDRM_BN_Div(dst_q, dst_r, bn1, bn2);
- if ((void*)dst_q != (void*)dest_q) {
- SDRM_BN_FREE(dst_q);
- }
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_Div fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntMod function computes dest = op (mod n) such that
- * 0 <= dest < n. dest and op MAY point to the same memory region but n MUST
- * point to a unique memory region. For negative op the function follows the
- * normal convention that -1 = (n-1) mod n.
- * @param dest Pointer to TEE_BigInt to hold the result op (mod n). The
- * result dest will be in the interval [0, n-1].
- * @param op Pointer to the operand to be reduced mod n
- * @param n Pointer to the modulus. Modulus MUST be larger than 1.
- */
-void TEE_BigIntMod(TEE_BigInt* dest, const TEE_BigInt* op, const TEE_BigInt* n) {
-
- SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
- SDRM_BIG_NUM *bnOp = (SDRM_BIG_NUM*)op;
- SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
- int32_t integerN = 0;
- TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
- if (integerN < 2) {
- LOGE(TAG, "Panic Reason: Modulus should be large than 2");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- int ret = SDRM_BN_ModRed(bnDst, bnOp, bnN);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_ModRed fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntAddMod function computes dest = (op1 + op2) (mod n). All or
- * some of dest, op1, and op2 MAY point to the same memory region but n MUST
- * point to a unique memory region.
- * @param dest Pointer to TEE_BigInt to hold the result (op1 + op2) (mod n)
- * @param op1 Pointer to the first operand. Operand MUST be in the interval
- * [0,n-1].
- * @param op2 Pointer to the second operand. Operand MUST be in the interval
- * [0,n-1].
- * @param n Pointer to the modulus. Modulus MUST be larger than 1.
- */
-void TEE_BigIntAddMod(TEE_BigInt* dest, const TEE_BigInt* op1,
- const TEE_BigInt* op2, const TEE_BigInt* n) {
-
- SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
- SDRM_BIG_NUM *bnOp1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bnOp2 = (SDRM_BIG_NUM*)op2;
- SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
- int32_t integerN = 0;
- TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
- if (integerN < 2) {
- LOGE(TAG, "Panic Reason: Modulus should be large than 2");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- int ret = SDRM_BN_ModAdd(bnDst, bnOp1, bnOp2, bnN);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_ModAdd fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntSubMod function computes dest = (op1 - op2) (mod n). All or
- * some of dest, op1, and op2 MAY point to the same memory region but n MUST
- * point to a unique memory region.
- * @param dest Pointer to TEE_BigInt to hold the result (op1 - op2) (mod n)
- * @param op1 Pointer to the first operand. Operand MUST be in the interval
- * [0,n-1].
- * @param op2 Pointer to the second operand. Operand MUST be in the interval
- * [0,n-1].
- * @param n Pointer to the modulus. Modulus MUST be larger than 1.
- */
-void TEE_BigIntSubMod(TEE_BigInt* dest, const TEE_BigInt* op1,
- const TEE_BigInt* op2, const TEE_BigInt* n) {
-
- SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
- SDRM_BIG_NUM *bnOp1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bnOp2 = (SDRM_BIG_NUM*)op2;
- SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
- int32_t integerN = 0;
- TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
- if (integerN < 2) {
- LOGE(TAG, "Panic Reason: Modulus should be large than 2");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- int ret = SDRM_BN_ModSub(bnDst, bnOp1, bnOp2, bnN);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_ModSub fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntMulMod function computes dest = (op1 * op2) (mod n). All or
- * some of dest, op1, and op2 MAY point to the same memory region but n MUST
- * point to a unique memory region.
- * @param dest Pointer to TEE_BigInt to hold the result (op1 * op2) (mod n)
- * @param op1 Pointer to the first operand. Operand MUST be in the interval
- * [0,n-1].
- * @param op2 Pointer to the second operand. Operand MUST be in the interval
- * [0,n-1].
- * @param n Pointer to the modulus. Modulus MUST be larger than 1.
- */
-void TEE_BigIntMulMod(TEE_BigInt* dest, const TEE_BigInt* op1,
- const TEE_BigInt* op2, const TEE_BigInt* n) {
-
- SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
- SDRM_BIG_NUM *bnOp1 = (SDRM_BIG_NUM*)op1;
- SDRM_BIG_NUM *bnOp2 = (SDRM_BIG_NUM*)op2;
- SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
- int32_t integerN = 0;
- TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
- if (integerN < 2) {
- LOGE(TAG, "Panic Reason: Modulus should be large than 2");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- int ret = SDRM_BN_ModMul(bnDst, bnOp1, bnOp2, bnN);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_ModMul fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/**
- * The TEE_BigIntSquareMod function computes dest = (op * op) (mod n).
- * dest and op MAY point to the same memory region but n MUST
- * point to a unique memory region.
- * @param dest Pointer to TEE_BigInt to hold the result (op * op) (mod n)
- * @param op Pointer to the operand. Operand MUST be in the interval
- * [0,n-1].
- * @param n Pointer to the modulus. Modulus MUST be larger than 1.
- */
-void TEE_BigIntSquareMod(TEE_BigInt* dest, const TEE_BigInt* op,
- const TEE_BigInt* n) {
-
- SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
- int32_t integerN = 0;
- TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
- if (integerN < 2) {
- LOGE(TAG, "Panic Reason: Modulus should be large than 2");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- TEE_BigIntMulMod(dest, op, op, n);
- LOGD(TAG, "Called");
-}
-
-/**
- * The TEE_BigIntInvMod function computes dest such that dest * op = 1 (mod n).
- * dest and op MAY point to the same memory region. This function assumes that
- * gcd(op,n) is equal to 1. If gcd(op,n) is greater than 1 then the result is
- * unreliable.
- * @param dest Pointer to TEE_BigInt to hold the result (op^-1) (mod n)
- * @param op Pointer to the operand. Operand MUST be in the interval
- * [0,n-1].
- * @param n Pointer to the modulus. Modulus MUST be larger than 1.
- */
-void TEE_BigIntInvMod(TEE_BigInt* dest, const TEE_BigInt* op,
- const TEE_BigInt* n) {
-
- SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
- SDRM_BIG_NUM *bnOp = (SDRM_BIG_NUM*)op;
- SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
-
- int32_t integerOp = 0;
- int32_t integerN = 0;
- TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
- TEE_BigIntConvertToS32(&integerOp, (TEE_BigInt*)bnOp);
- if (integerN < 2 || integerOp == 0) {
- LOGE(TAG, "Panic Reason: Modulus should be large than 2");
- TEE_Panic(TEE_ERROR_GENERIC);
- }
- int ret = SDRM_BN_ModInv(bnDst, bnOp, bnN);
- if (ret == CRYPTO_SUCCESS) {
- LOGD(TAG, "Success");
- } else {
- LOGE(TAG, "Panic Reason: SDRM_BN_ModInv fail(ret:%d)", ret);
- TEE_Panic(TEE_ERROR_GENERIC);
- }
-}
-
-/* TODO : NOT IMPLEMENTED */
-/**
- * The TEE_BigIntRelativePrime function determines whether gcd(op1, op2)==1.
- * op1 and op2 MAY point to the same memory region.
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- */
-bool TEE_BigIntRelativePrime(const TEE_BigInt* op1, const TEE_BigInt* op2) {
- (void)op1;
- (void)op2;
- return false;
-}
-
-/* TODO : NOT IMPLEMENTED */
-/**
- * The TEE_BigIntComputeExtendedGcd function computes the greatest common
- * divisor of the input parameters op1 and op2. Furthermore it computes the
- * coefficients u and v such that u*op1+v*op2==gcd. op1 and op2 MAY point to
- * the same memory region. u, v, or both can be NULL. If both are NULL then
- * the function only computes the gcd of op1 and op2.
- * @param gcd Pointer to TEE_BigInt to hold the greatest common divisor of
- * op1 and op2
- * @param u Pointer to TEE_BigInt to hold the first coefficient
- * @param v Pointer to TEE_BigInt to hold the second coefficient
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- */
-void TEE_BigIntComputeExtendedGcd(TEE_BigInt* gcd, TEE_BigInt* u, TEE_BigInt* v,
- const TEE_BigInt* op1, const TEE_BigInt* op2) {
- (void)gcd;
- (void)u;
- (void)v;
- (void)op1;
- (void)op2;
-}
-
-/* TODO : NOT IMPLEMENTED */
-/**
- * The TEE_BigIntIsProbablePrime function performs a probabilistic primality
- * test on op. The parameter confidenceLevel is used to specify the probability
- * of a non-conclusive answer. If the function cannot guarantee that op is
- * prime or composite, it MUST iterate the test until the probability that op
- * is composite is less than 2^(-confidenceLevel). Values smaller than 80 for
- * confidenceLevel will not be recognized and will default to 80. The maximum
- * honored value of confidenceLevel is implementation-specific, but MUST be at
- * least 80.
- * The algorithm for performing the primality test is implementation-specific,
- * but its correctness and efficiency MUST be equal to or better than the
- * Miller-Rabin test.
- * @param op Candidate number that is tested for primality
- * @param confidenceLevel The desired confidence level for a non-conclusive
- * test. This parameter (usually) maps to the number of iterations and thus to
- * the running time of the test. Values smaller than 80 will be treated as 80.
- */
-int32_t TEE_BigIntIsProbablePrime(const TEE_BigInt* op,
- uint32_t confidenceLevel) {
- (void)op;
- (void)confidenceLevel;
- return 0;
-}
-
-/**
- * The TEE_BigIntFMMSizeInU32 function returns the size of the array of
- * uint32_t values needed to represent an integer in the fast modular
- * multiplication representation, given the size of the modulus in bits.
- * This function MUST never fail.
- * @param modulusSizeInBits Size of modulus in bits
- */
-size_t TEE_BigIntFMMSizeInU32(size_t modulusSizeInBits) {
- return TEE_BigIntSizeInU32(modulusSizeInBits);
-}
-
-/**
- * The TEE_BigIntInitFMM function initializes bigIntFMM and sets its
- * represented value to zero. This function assumes that bigIntFMM points to
- * a memory area of len uint32_t.
- * @param object A pointer to the TEE_BigIntFMM to be initialized
- * @param len The size in uint32_t of the memory pointed to by bigIntFMM
- */
-void TEE_BigIntInitFMM(TEE_BigIntFMM* object, const size_t len) {
- TEE_BigIntInit((TEE_BigInt*)object, len);
-}
-
-/**
- * The TEE_BigIntFMMContextSizeInU32 function returns the size of the array
- * of uint32_t values needed to represent a fast modular context using a
- * given modulus size. This function MUST never fail.
- * @param modulusSizeInBits Size of modulus in bits
- */
-size_t TEE_BigIntFMMContextSizeInU32(const size_t modulusSizeInBits) {
- return TEE_BigIntSizeInU32(modulusSizeInBits);
-}
-
-/**
- * The TEE_BigIntInitFMMContext function calculates the necessary
- * prerequisites for the fast modular multiplication and stores them in a
- * context. This function assumes that context points to a memory area of
- * len uint32_t.
- * @param context A pointer to the TEE_BigIntFMMContext to be initialized
- * @param len The size in uint32_t of the memory pointed to by context
- * @param modulus The modulus, an odd integer larger than 2 and less than 2
- * to the power of gpd.tee.arith.maxBigIntSize
- */
-void TEE_BigIntInitFMMContext(TEE_BigIntFMMContext* context, const size_t len,
- const TEE_BigInt* modulus) {
-}
-
-/**
- * The TEE_BigIntConvertToFMM function converts src into a representation
- * suitable for doing fast modular multiplication. If the operation is
- * successful, the result will be written in implementation-specific format
- * into the buffer dest, which MUST have been allocated by the TA and
- * initialized using TEE_BigIntInitFMM.
- * @param dest Pointer to an initialized TEE_BigIntFMM memory area
- * @param src Pointer to the TEE_BigInt to convert
- * @param n Pointer to the modulus
- * @param context Pointer to a context previously initialized using
- * TEE_BigIntInitFMMContext
- */
-void TEE_BigIntConvertToFMM(TEE_BigIntFMM* dest, const TEE_BigInt* src,
- const TEE_BigInt* n, const TEE_BigIntFMMContext* context) {
-}
-
-/**
- * The TEE_BigIntConvertFromFMM function converts src in the fast modular
- * multiplication representation back to a TEE_BigInt representation.
- * @param dest Pointer to an initialized TEE_BigInt memory area to hold
- * the converted result
- * @param src Pointer to a TEE_BigIntFMM holding the value in the fast
- * modular multiplication representation
- * @param n Pointer to the modulus
- * @param context Pointer to a context previously initialized using
- * TEE_BigIntInitFMMContext
- */
-void TEE_BigIntConvertFromFMM(TEE_BigInt* dest, const TEE_BigIntFMM* src,
- const TEE_BigInt* n, const TEE_BigIntFMMContext* context) {
-}
-
-/**
- * The TEE_BigIntComputeFMM function calculates dest = op1 * op2 in the fast
- * modular multiplication representation. The pointers dest, op1, and op2 MUST
- * each point to a TEE_BigIntFMM which has been previously initialized with
- * the same modulus and context as used in this function call; otherwise the
- * result is undefined. All or some of dest, op1, and op2 MAY point to the
- * same memory region.
- * @param dest Pointer to TEE_BigIntFMM to hold the result op1 * op2 in the
- * fast modular multiplication representation
- * @param op1 Pointer to the first operand
- * @param op2 Pointer to the second operand
- * @param n Pointer to the modulus
- * @param context Pointer to a context previously initialized using
- * TEE_BigIntInitFMMContext
- */
-void TEE_BigIntComputeFMM(TEE_BigIntFMM* dest, const TEE_BigIntFMM* op1,
- const TEE_BigIntFMM* op2, const TEE_BigInt* n,
- const TEE_BigIntFMMContext* context) {
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssf_arithmetic.c
+ *
+ * Description: SSF arithmetic functions
+ *
+ * Version: 1.0
+ * Created: 29 June 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: Cheryl (cb), cheryl.b@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include <log.h>
+#include <permission.h>
+#include "tee_internal_api.h"
+#include "CC_API.h"
+#include "base/cc_bignum.h"
+
+/*-----------------------------------------------------------------------------
+ * MACROS
+ *-----------------------------------------------------------------------------*/
+#define TAG SSF_LIB
+#define SDRM_API_METADATA_LENGTH_IN_U32 4
+#define CNT_OF_BIT_IN_BYTE 8
+#define PASS_NOT_IMP_CODE
+
+/*-----------------------------------------------------------------------------
+ * TEE API implementation
+ *-----------------------------------------------------------------------------*/
+/**
+ * The TEE_BigIntInit function initializes bigInt and sets its represented
+ * value to zero. This function assumes that bigInt points to a memory area
+ * of len uint32_t.
+ * @param value A pointer to the TEE_BigInt to be initialized
+ * @param length The size in uint32_t of the memory pointed to by bigInt
+ */
+void TEE_BigIntInit(TEE_BigInt* value, const size_t length) {
+
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ LOGD(TAG, "TEE_BigIntInit - length : %d", length);
+ uint32_t teeMaxBigIntSize;
+ TEE_Result result = TEE_GetPropertyAsU32(
+ (TEE_PropSetHandle)TEE_PROPSET_TEE_IMPLEMENTATION,
+ "gpd.tee.arith.maxBigIntSize", &teeMaxBigIntSize);
+ LOGD(TAG, "TEE_GetPropertyAsU32(arith.maxBigIntSize) : %d (ret:%d)",
+ teeMaxBigIntSize, result);
+
+ if(result == TEE_SUCCESS)
+ {
+#ifndef PASS_NOT_IMP_CODE
+ if(teeMaxBigIntSize == 0 ||
+ (length - SDRM_API_METADATA_LENGTH_IN_U32) * SDRM_SIZE_OF_DWORD * CNT_OF_BIT_IN_BYTE < teeMaxBigIntSize)
+ {
+ LOGE(TAG, "Panic Reason: BN size is creater than max allowed");
+ TEE_Panic(TEE_ERROR_OUT_OF_MEMORY);
+ }
+#endif
+ }
+
+ if (length <= SDRM_API_METADATA_LENGTH_IN_U32) {
+ LOGE(TAG, "Panic Reason: insufficient length");
+ TEE_Panic(TEE_ERROR_OUT_OF_MEMORY);
+ }
+ SDRM_BIG_NUM *bn = SDRM_BN_Alloc((cc_u8*)value,
+ length - SDRM_API_METADATA_LENGTH_IN_U32);
+ if (bn == NULL) {
+ LOGE(TAG, "Panic Reason: SDRM_BN_Alloc fail");
+ TEE_Panic(TEE_ERROR_OUT_OF_MEMORY);
+ }
+ LOGD(TAG, "Success");
+}
+
+/**
+ * The TEE_BigIntConvertFromOctetString function converts a bufferLen byte
+ * octet string buffer into a TEE_BigInt format. The octet string is in most
+ * significant byte first representation. The input parameter sign will set
+ * the sign of dest. It will be set to negative if sign<0 and to positive if
+ * sign>=0.
+ * @param dest Pointer to a TEE_BigInt to hold the result
+ * @param buffer Pointer to the buffer containing the octet string
+ * representation of the integer
+ * @param sz_buffer The length of *buffer in bytes
+ * @param sign The sign of dest is set to the sign of sign
+ */
+TEE_Result TEE_BigIntConvertFromOctetString(TEE_BigInt* dest,
+ const uint8_t* buffer, const size_t sz_buffer, const int32_t sign) {
+
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+
+ LOGD(TAG,
+ "TEE_BigIntConvertFromOctetString - dest:%p buffer:%p sz_buffer:%d sign:%d",
+ dest, buffer, sz_buffer, sign);
+ TEE_Result result = TEE_SUCCESS;
+ SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)dest;
+
+ if (bn->Size * SDRM_SIZE_OF_DWORD < sz_buffer) {
+ LOGD(TAG, "Fail Reason: TEE_ERROR_OVERFLOW(%d %d)",
+ bn->Size * SDRM_SIZE_OF_DWORD, sz_buffer);
+ return TEE_ERROR_OVERFLOW;
+ }
+ int ret = SDRM_OS2BN((cc_u8*)buffer, sz_buffer, bn);
+ if (ret == CRYPTO_SUCCESS) {
+ bn->sign = ((sign < 0) ? 1 : 0);
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_OS2BN fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ return result;
+}
+
+/**
+ * The TEE_BigIntConvertToOctetString function converts the absolute value of
+ * an integer in TEE_BigInt format into an octet string. The octet string is
+ * written in a most significant byte first representation.
+ * @param buffer Output buffer where converted octet string representation
+ * of the integer is written
+ * @param sz_buffer_out The length of *buffer in bytes
+ * @param value Pointer to the integer that will be converted to an octet
+ * string
+ */
+TEE_Result TEE_BigIntConvertToOctetString(void* buffer, size_t* sz_buffer_out,
+ const TEE_BigInt* value) {
+
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ LOGD(TAG, "TEE_BigIntConvertToOctetString - buffer:%p value:%p", buffer,
+ value);
+ TEE_Result result = TEE_SUCCESS;
+ SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)value;
+ if (*sz_buffer_out == 0) {
+ if (bn->Length != 0) {
+ *sz_buffer_out = bn->Length * 4;
+ result = TEE_ERROR_SHORT_BUFFER;
+ }
+ return result;
+ }
+ int ret = SDRM_BN2OS(bn, *sz_buffer_out, (cc_u8 *)buffer);
+ if (ret == CRYPTO_BUFFER_TOO_SMALL || ret == CRYPTO_NULL_POINTER) {
+ LOGD(TAG, "Fail Reason: CRYPTO_BUFFER_TOO_SMALL or CRYPTO_NULL_POINTER");
+ *sz_buffer_out = bn->Length * 4;
+ result = TEE_ERROR_SHORT_BUFFER;
+ } else if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN2OS fail(%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ return result;
+}
+
+/**
+ * The TEE_BigIntConvertFromS32 function sets *result to the value input.
+ * @param result Pointer to a TEE_BigInt to store the result
+ * @param input Input value
+ */
+void TEE_BigIntConvertFromS32(TEE_BigInt* result, const int32_t input) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)result;
+ bn->pData[0] = ((input < 0) ? (input * -1) : (input));
+ bn->Length = 1;
+ bn->sign = ((input < 0) ? 1 : 0);
+ LOGD(TAG, "Success");
+}
+
+/**
+ * The TEE_BigIntConvertToS32 function sets *result to the value of input,
+ * including the sign of input. If input does not fit within an int32_t,
+ * the value of *result is undefined.
+ * @param result Pointer to an int32_t to store the result
+ * @param input Pointer to the input value
+ */
+TEE_Result TEE_BigIntConvertToS32(int32_t* value_result,
+ const TEE_BigInt* input) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bn = (SDRM_BIG_NUM*)input;
+ *value_result = (bn->sign == 1) ? (bn->pData[0] * -1) : (bn->pData[0]);
+ LOGD(TAG, "Success");
+ return TEE_SUCCESS;
+}
+
+/**
+ * The TEE_BigIntCmp function checks whether op1>op2, op1==op2, or op1<op2.
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ */
+int32_t TEE_BigIntCmp(const TEE_BigInt* op1, const TEE_BigInt* op2) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
+ int ret = SDRM_BN_Cmp_sign(bn1, bn2);
+ LOGD(TAG, "Success");
+ return ret;
+}
+
+/**
+ * The TEE_BigIntCmpS32 function checks whether value1_raw>value2,
+ * value1_raw==value2, or value1_raw<value2.
+ * @param value1_raw Pointer to the first operand
+ * @param value2 Pointer to the second operand
+ */
+int32_t TEE_BigIntCmpS32(const TEE_BigInt* value1_raw, const int32_t value2) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ int32_t value1 = 0;
+ TEE_Result result = TEE_BigIntConvertToS32(&value1, value1_raw);
+ if (result != TEE_SUCCESS) {
+ LOGE(TAG, "Panic Reason: TEE_BigIntConvertToS32 fail");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ int ret = 0;
+ if (value1 == value2)
+ ret = 0;
+ else if (value1 > value2)
+ ret = 1;
+ else ret = -1;
+ return ret;
+}
+
+/**
+ * The TEE_BigIntShiftRight function computes
+ * |destination_raw| = |source_raw| >> bits and destination_raw will have the
+ * same sign as source_raw.4 If bits is greater than the bit length of
+ * source_raw then the result is zero. destination_raw and source_raw MAY
+ * point to the same memory region.
+ * @param destination_raw Pointer to TEE_BigInt to hold the shifted result
+ * @param source_raw Pointer to the operand to be shifted
+ * @param bits Number of bits to shift
+ */
+void TEE_BigIntShiftRight(TEE_BigInt* destination_raw,
+ const TEE_BigInt* source_raw, const size_t bits) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+
+ SDRM_BIG_NUM *dstBn = (SDRM_BIG_NUM*)destination_raw;
+ SDRM_BIG_NUM *srcBn = (SDRM_BIG_NUM*)source_raw;
+ int ret = SDRM_BN_SHR(dstBn, srcBn, bits);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_SHR fail");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntGetBit function returns the indexth bit of the natural binary
+ * representation of |object_raw|. A true return value indicates a “1” and a
+ * false return value indicates a “0” in the indexth position. If index is
+ * larger than the number of bits in object_raw, the return value is false,
+ * thus indicating a “0”.
+ * @param object_raw Pointer to the integer
+ * @param index The offset of the bit to be read, starting at offset 0 for the
+ * least significant bit
+ */
+bool TEE_BigIntGetBit(const TEE_BigInt* object_raw, const uint32_t index) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *objBn = (SDRM_BIG_NUM*)object_raw;
+ bool bitValue = (bool)SDRM_BN_num_bits_index(objBn, index);
+ LOGD(TAG, "Success");
+ return bitValue;
+
+}
+
+/**
+ * The TEE_BigIntGetBitCount function returns the number of bits in the
+ * natural binary representation of |object_raw|; that is, the magnitude of
+ * object_raw.
+ * @param object_raw Pointer to the integer
+ */
+uint32_t TEE_BigIntGetBitCount(const TEE_BigInt* object_raw) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *objBn = (SDRM_BIG_NUM*)object_raw;
+ int retCnt = SDRM_BN_num_bits(objBn);
+ LOGD(TAG, "Success");
+ return retCnt;
+}
+
+/**
+ * The TEE_BigIntAdd function computes dest = op1 + op2. All or some of dest,
+ * op1, and op2 MAY point to the same memory region.
+ * @param dest Pointer to TEE_BigInt to store the result op1 + op2
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ */
+void TEE_BigIntAdd(TEE_BigInt* dest, const TEE_BigInt* op1,
+ const TEE_BigInt* op2) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
+ SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
+ int ret = SDRM_BN_Add(dst, bn1, bn2);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_Add fail");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntSub function computes dest = op1 – op2. All or some of dest,
+ * op1, and op2 MAY point to the same memory region.
+ * @param dest Pointer to TEE_BigInt to store the result op1 - op2
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ */
+void TEE_BigIntSub(TEE_BigInt* dest, const TEE_BigInt* op1,
+ const TEE_BigInt* op2) {
+ SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
+ SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ int ret = SDRM_BN_Sub(dst, bn1, bn2);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_Sub fail");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntNeg function negates an operand: dest = -op. dest and op MAY
+ * point to the same memory region.
+ * @param dest Pointer to TEE_BigInt to store the result -op
+ * @param op Pointer to the operand to be negated
+ */
+void TEE_BigIntNeg(TEE_BigInt* dest, const TEE_BigInt* op) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnOp = (SDRM_BIG_NUM*)op;
+ if (dest == op)
+ bnOp->sign = ((bnOp->sign == 1) ? 0 : 1);
+ else {
+ SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
+ SDRM_BN_Copy(dst, bnOp);
+ dst->sign = ((dst->sign == 1) ? 0 : 1);
+ }
+ LOGD(TAG, "Success");
+}
+
+/**
+ * The TEE_BigIntMul function computes dest = op1 * op2. All or some of dest,
+ * op1, and op2 MAY point to the same memory region.
+ * @param dest Pointer to TEE_BigInt to store the result op1 * op2
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ */
+void TEE_BigIntMul(TEE_BigInt* dest, const TEE_BigInt* op1,
+ const TEE_BigInt* op2) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
+ SDRM_BIG_NUM *dst = (SDRM_BIG_NUM*)dest;
+ int ret = SDRM_BN_Mul(dst, bn1, bn2);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_Mul fail");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntSquare function computes dest = op * op. dest and op MAY point
+ * to the same memory region.
+ * @param dest Pointer to TEE_BigInt to store the result op * op
+ * @param op Pointer to the operand to be squared
+ */
+void TEE_BigIntSquare(TEE_BigInt* dest, const TEE_BigInt* op) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ TEE_BigIntMul(dest, op, op);
+ LOGD(TAG, "Called");
+}
+
+/**
+ * The TEE_BigIntDiv function computes dest_r and dest_q such that
+ * op1 = dest_q * op2 + dest_r. It will round dest_q towards zero and dest_r
+ * will have the same sign as op1.
+ * @param dest_q Pointer to a TEE_BigInt to store the quotient.
+ * dest_q can be NULL.
+ * @param dest_r Pointer to a TEE_BigInt to store the remainder.
+ * dest_r can be NULL.
+ * @param op1 Pointer to the first operand, the dividend
+ * @param op2 Pointer to the second operand, the divisor
+ */
+void TEE_BigIntDiv(TEE_BigInt* dest_q, TEE_BigInt* dest_r,
+ const TEE_BigInt* op1, const TEE_BigInt* op2) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *dst_q = (SDRM_BIG_NUM*)dest_q;
+ SDRM_BIG_NUM *dst_r = (SDRM_BIG_NUM*)dest_r;
+ SDRM_BIG_NUM *bn1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bn2 = (SDRM_BIG_NUM*)op2;
+
+ if (dst_q == NULL) {
+ SDRM_BIG_NUM *tmp = SDRM_BN_Init(bn1->Size);
+ if (tmp != NULL) {
+ SDRM_BN_Copy(tmp, bn1);
+ dst_q = tmp;
+ }
+ }
+ int ret = SDRM_BN_Div(dst_q, dst_r, bn1, bn2);
+ if ((void*)dst_q != (void*)dest_q) {
+ SDRM_BN_FREE(dst_q);
+ }
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_Div fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntMod function computes dest = op (mod n) such that
+ * 0 <= dest < n. dest and op MAY point to the same memory region but n MUST
+ * point to a unique memory region. For negative op the function follows the
+ * normal convention that -1 = (n-1) mod n.
+ * @param dest Pointer to TEE_BigInt to hold the result op (mod n). The
+ * result dest will be in the interval [0, n-1].
+ * @param op Pointer to the operand to be reduced mod n
+ * @param n Pointer to the modulus. Modulus MUST be larger than 1.
+ */
+void TEE_BigIntMod(TEE_BigInt* dest, const TEE_BigInt* op, const TEE_BigInt* n) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
+ SDRM_BIG_NUM *bnOp = (SDRM_BIG_NUM*)op;
+ SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
+ int32_t integerN = 0;
+ TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
+ if (integerN < 2) {
+ LOGE(TAG, "Panic Reason: Modulus should be large than 2");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ int ret = SDRM_BN_ModRed(bnDst, bnOp, bnN);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_ModRed fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntAddMod function computes dest = (op1 + op2) (mod n). All or
+ * some of dest, op1, and op2 MAY point to the same memory region but n MUST
+ * point to a unique memory region.
+ * @param dest Pointer to TEE_BigInt to hold the result (op1 + op2) (mod n)
+ * @param op1 Pointer to the first operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param op2 Pointer to the second operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param n Pointer to the modulus. Modulus MUST be larger than 1.
+ */
+void TEE_BigIntAddMod(TEE_BigInt* dest, const TEE_BigInt* op1,
+ const TEE_BigInt* op2, const TEE_BigInt* n) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
+ SDRM_BIG_NUM *bnOp1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bnOp2 = (SDRM_BIG_NUM*)op2;
+ SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
+ int32_t integerN = 0;
+ TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
+ if (integerN < 2) {
+ LOGE(TAG, "Panic Reason: Modulus should be large than 2");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ int ret = SDRM_BN_ModAdd(bnDst, bnOp1, bnOp2, bnN);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_ModAdd fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntSubMod function computes dest = (op1 - op2) (mod n). All or
+ * some of dest, op1, and op2 MAY point to the same memory region but n MUST
+ * point to a unique memory region.
+ * @param dest Pointer to TEE_BigInt to hold the result (op1 - op2) (mod n)
+ * @param op1 Pointer to the first operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param op2 Pointer to the second operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param n Pointer to the modulus. Modulus MUST be larger than 1.
+ */
+void TEE_BigIntSubMod(TEE_BigInt* dest, const TEE_BigInt* op1,
+ const TEE_BigInt* op2, const TEE_BigInt* n) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
+ SDRM_BIG_NUM *bnOp1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bnOp2 = (SDRM_BIG_NUM*)op2;
+ SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
+ int32_t integerN = 0;
+ TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
+ if (integerN < 2) {
+ LOGE(TAG, "Panic Reason: Modulus should be large than 2");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ int ret = SDRM_BN_ModSub(bnDst, bnOp1, bnOp2, bnN);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_ModSub fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntMulMod function computes dest = (op1 * op2) (mod n). All or
+ * some of dest, op1, and op2 MAY point to the same memory region but n MUST
+ * point to a unique memory region.
+ * @param dest Pointer to TEE_BigInt to hold the result (op1 * op2) (mod n)
+ * @param op1 Pointer to the first operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param op2 Pointer to the second operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param n Pointer to the modulus. Modulus MUST be larger than 1.
+ */
+void TEE_BigIntMulMod(TEE_BigInt* dest, const TEE_BigInt* op1,
+ const TEE_BigInt* op2, const TEE_BigInt* n) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
+ SDRM_BIG_NUM *bnOp1 = (SDRM_BIG_NUM*)op1;
+ SDRM_BIG_NUM *bnOp2 = (SDRM_BIG_NUM*)op2;
+ SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
+ int32_t integerN = 0;
+ TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
+ if (integerN < 2) {
+ LOGE(TAG, "Panic Reason: Modulus should be large than 2");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ int ret = SDRM_BN_ModMul(bnDst, bnOp1, bnOp2, bnN);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_ModMul fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/**
+ * The TEE_BigIntSquareMod function computes dest = (op * op) (mod n).
+ * dest and op MAY point to the same memory region but n MUST
+ * point to a unique memory region.
+ * @param dest Pointer to TEE_BigInt to hold the result (op * op) (mod n)
+ * @param op Pointer to the operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param n Pointer to the modulus. Modulus MUST be larger than 1.
+ */
+void TEE_BigIntSquareMod(TEE_BigInt* dest, const TEE_BigInt* op,
+ const TEE_BigInt* n) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
+ int32_t integerN = 0;
+ TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
+ if (integerN < 2) {
+ LOGE(TAG, "Panic Reason: Modulus should be large than 2");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ TEE_BigIntMulMod(dest, op, op, n);
+ LOGD(TAG, "Called");
+}
+
+/**
+ * The TEE_BigIntInvMod function computes dest such that dest * op = 1 (mod n).
+ * dest and op MAY point to the same memory region. This function assumes that
+ * gcd(op,n) is equal to 1. If gcd(op,n) is greater than 1 then the result is
+ * unreliable.
+ * @param dest Pointer to TEE_BigInt to hold the result (op^-1) (mod n)
+ * @param op Pointer to the operand. Operand MUST be in the interval
+ * [0,n-1].
+ * @param n Pointer to the modulus. Modulus MUST be larger than 1.
+ */
+void TEE_BigIntInvMod(TEE_BigInt* dest, const TEE_BigInt* op,
+ const TEE_BigInt* n) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ SDRM_BIG_NUM *bnDst = (SDRM_BIG_NUM*)dest;
+ SDRM_BIG_NUM *bnOp = (SDRM_BIG_NUM*)op;
+ SDRM_BIG_NUM *bnN = (SDRM_BIG_NUM*)n;
+
+ int32_t integerOp = 0;
+ int32_t integerN = 0;
+ TEE_BigIntConvertToS32(&integerN, (TEE_BigInt*)bnN);
+ TEE_BigIntConvertToS32(&integerOp, (TEE_BigInt*)bnOp);
+ if (integerN < 2 || integerOp == 0) {
+ LOGE(TAG, "Panic Reason: Modulus should be large than 2");
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+ int ret = SDRM_BN_ModInv(bnDst, bnOp, bnN);
+ if (ret == CRYPTO_SUCCESS) {
+ LOGD(TAG, "Success");
+ } else {
+ LOGE(TAG, "Panic Reason: SDRM_BN_ModInv fail(ret:%d)", ret);
+ TEE_Panic(TEE_ERROR_GENERIC);
+ }
+}
+
+/* TODO : NOT IMPLEMENTED */
+/**
+ * The TEE_BigIntRelativePrime function determines whether gcd(op1, op2)==1.
+ * op1 and op2 MAY point to the same memory region.
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ */
+bool TEE_BigIntRelativePrime(const TEE_BigInt* op1, const TEE_BigInt* op2) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ (void)op1;
+ (void)op2;
+ return false;
+}
+
+/* TODO : NOT IMPLEMENTED */
+/**
+ * The TEE_BigIntComputeExtendedGcd function computes the greatest common
+ * divisor of the input parameters op1 and op2. Furthermore it computes the
+ * coefficients u and v such that u*op1+v*op2==gcd. op1 and op2 MAY point to
+ * the same memory region. u, v, or both can be NULL. If both are NULL then
+ * the function only computes the gcd of op1 and op2.
+ * @param gcd Pointer to TEE_BigInt to hold the greatest common divisor of
+ * op1 and op2
+ * @param u Pointer to TEE_BigInt to hold the first coefficient
+ * @param v Pointer to TEE_BigInt to hold the second coefficient
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ */
+void TEE_BigIntComputeExtendedGcd(TEE_BigInt* gcd, TEE_BigInt* u, TEE_BigInt* v,
+ const TEE_BigInt* op1, const TEE_BigInt* op2) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ (void)gcd;
+ (void)u;
+ (void)v;
+ (void)op1;
+ (void)op2;
+}
+
+/* TODO : NOT IMPLEMENTED */
+/**
+ * The TEE_BigIntIsProbablePrime function performs a probabilistic primality
+ * test on op. The parameter confidenceLevel is used to specify the probability
+ * of a non-conclusive answer. If the function cannot guarantee that op is
+ * prime or composite, it MUST iterate the test until the probability that op
+ * is composite is less than 2^(-confidenceLevel). Values smaller than 80 for
+ * confidenceLevel will not be recognized and will default to 80. The maximum
+ * honored value of confidenceLevel is implementation-specific, but MUST be at
+ * least 80.
+ * The algorithm for performing the primality test is implementation-specific,
+ * but its correctness and efficiency MUST be equal to or better than the
+ * Miller-Rabin test.
+ * @param op Candidate number that is tested for primality
+ * @param confidenceLevel The desired confidence level for a non-conclusive
+ * test. This parameter (usually) maps to the number of iterations and thus to
+ * the running time of the test. Values smaller than 80 will be treated as 80.
+ */
+int32_t TEE_BigIntIsProbablePrime(const TEE_BigInt* op,
+ uint32_t confidenceLevel) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ (void)op;
+ (void)confidenceLevel;
+ return 0;
+}
+
+/**
+ * The TEE_BigIntFMMSizeInU32 function returns the size of the array of
+ * uint32_t values needed to represent an integer in the fast modular
+ * multiplication representation, given the size of the modulus in bits.
+ * This function MUST never fail.
+ * @param modulusSizeInBits Size of modulus in bits
+ */
+size_t TEE_BigIntFMMSizeInU32(size_t modulusSizeInBits) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ return TEE_BigIntSizeInU32(modulusSizeInBits);
+}
+
+/**
+ * The TEE_BigIntInitFMM function initializes bigIntFMM and sets its
+ * represented value to zero. This function assumes that bigIntFMM points to
+ * a memory area of len uint32_t.
+ * @param object A pointer to the TEE_BigIntFMM to be initialized
+ * @param len The size in uint32_t of the memory pointed to by bigIntFMM
+ */
+void TEE_BigIntInitFMM(TEE_BigIntFMM* object, const size_t len) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+ TEE_BigIntInit((TEE_BigInt*)object, len);
+}
+
+/**
+ * The TEE_BigIntFMMContextSizeInU32 function returns the size of the array
+ * of uint32_t values needed to represent a fast modular context using a
+ * given modulus size. This function MUST never fail.
+ * @param modulusSizeInBits Size of modulus in bits
+ */
+size_t TEE_BigIntFMMContextSizeInU32(const size_t modulusSizeInBits) {
+ PERMISSION_CHECK(PERM_ARITHMETIC);
+ return TEE_BigIntSizeInU32(modulusSizeInBits);
+}
+
+/**
+ * The TEE_BigIntInitFMMContext function calculates the necessary
+ * prerequisites for the fast modular multiplication and stores them in a
+ * context. This function assumes that context points to a memory area of
+ * len uint32_t.
+ * @param context A pointer to the TEE_BigIntFMMContext to be initialized
+ * @param len The size in uint32_t of the memory pointed to by context
+ * @param modulus The modulus, an odd integer larger than 2 and less than 2
+ * to the power of gpd.tee.arith.maxBigIntSize
+ */
+void TEE_BigIntInitFMMContext(TEE_BigIntFMMContext* context, const size_t len,
+ const TEE_BigInt* modulus) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+}
+
+/**
+ * The TEE_BigIntConvertToFMM function converts src into a representation
+ * suitable for doing fast modular multiplication. If the operation is
+ * successful, the result will be written in implementation-specific format
+ * into the buffer dest, which MUST have been allocated by the TA and
+ * initialized using TEE_BigIntInitFMM.
+ * @param dest Pointer to an initialized TEE_BigIntFMM memory area
+ * @param src Pointer to the TEE_BigInt to convert
+ * @param n Pointer to the modulus
+ * @param context Pointer to a context previously initialized using
+ * TEE_BigIntInitFMMContext
+ */
+void TEE_BigIntConvertToFMM(TEE_BigIntFMM* dest, const TEE_BigInt* src,
+ const TEE_BigInt* n, const TEE_BigIntFMMContext* context) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+}
+
+/**
+ * The TEE_BigIntConvertFromFMM function converts src in the fast modular
+ * multiplication representation back to a TEE_BigInt representation.
+ * @param dest Pointer to an initialized TEE_BigInt memory area to hold
+ * the converted result
+ * @param src Pointer to a TEE_BigIntFMM holding the value in the fast
+ * modular multiplication representation
+ * @param n Pointer to the modulus
+ * @param context Pointer to a context previously initialized using
+ * TEE_BigIntInitFMMContext
+ */
+void TEE_BigIntConvertFromFMM(TEE_BigInt* dest, const TEE_BigIntFMM* src,
+ const TEE_BigInt* n, const TEE_BigIntFMMContext* context) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+}
+
+/**
+ * The TEE_BigIntComputeFMM function calculates dest = op1 * op2 in the fast
+ * modular multiplication representation. The pointers dest, op1, and op2 MUST
+ * each point to a TEE_BigIntFMM which has been previously initialized with
+ * the same modulus and context as used in this function call; otherwise the
+ * result is undefined. All or some of dest, op1, and op2 MAY point to the
+ * same memory region.
+ * @param dest Pointer to TEE_BigIntFMM to hold the result op1 * op2 in the
+ * fast modular multiplication representation
+ * @param op1 Pointer to the first operand
+ * @param op2 Pointer to the second operand
+ * @param n Pointer to the modulus
+ * @param context Pointer to a context previously initialized using
+ * TEE_BigIntInitFMMContext
+ */
+void TEE_BigIntComputeFMM(TEE_BigIntFMM* dest, const TEE_BigIntFMM* op1,
+ const TEE_BigIntFMM* op2, const TEE_BigInt* n,
+ const TEE_BigIntFMMContext* context) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_ARITHMETIC);
+}
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssfclient.c
- *
- * Description: SSF client functions
- *
- * Version: 1.0
- * Created: 20 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: Cheryl (cb), cheryl.b@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include "teestub_command_data.h"
-#include "tee_internal_api.h"
-#include <errno.h>
-#include <assert.h>
-#include "ssf_client.h"
-#include <unistd.h>
-
-/*-----------------------------------------------------------------------------
- * MACROS
- *-----------------------------------------------------------------------------*/
-#define SOCKPATH "/tmp/simdaemon" //path to be updated
-
-//#define TEST
-
-/*-----------------------------------------------------------------------------
- * local functions
- *-----------------------------------------------------------------------------*/
-/**
- * API (Interface for TEECAPI) implementation for connecting to
- * the Simulator daemon through socket
- * @return socket file descriptor to connected server
- */
-int32_t connecttoServer(void) {
- LOGD(SSF_LIB, "Entry");
- int serverSocket, socklen;
- size_t sock_path_len = 0;
- struct sockaddr* sockptr;
- struct sockaddr_un daemonsock;
-
- if ((serverSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
- LOGE(SSF_LIB, "No socket for simdaemon");
- return -1;
- }
- daemonsock.sun_family = AF_UNIX;
-
- sock_path_len = strlen(SOCKPATH);
- strncpy(daemonsock.sun_path, SOCKPATH, sock_path_len+1);
-
- socklen = sizeof(daemonsock);
- sockptr = (struct sockaddr*)&daemonsock;
- if (connect(serverSocket, sockptr, socklen) == -1) {
- LOGE(SSF_LIB, "connection to simdaemon failed");
- close(serverSocket);
- return -1;
- }
- return serverSocket;
-}
-
-/**
- * API (Interface for TEECAPI) implementation for disconnecting
- * from the Simulator daemon through socket
- * @param ServerSocket
- */
-void disconnectfromServer(int32_t serverSocket) {
- int32_t result;
- LOGD(SSF_LIB, "Entry");
- if (serverSocket > 0) {
- result = shutdown(serverSocket, SHUT_WR);
- if (result != 0) LOGE(SSF_LIB, "disconnectfromServer failed");
- close(serverSocket);
- } else {
- LOGE(SSF_LIB, "Invalid socket, disconnectfromServer failed");
- }
-}
-
-/**
- * Function implementation for sending data to Simulator daemon
- * through socket
- * @param sockfd file descriptor
- * @param fdata structured data to daemon
- * @param size size of fdata in bytes
- * @return
- */
-static uint32_t sendCommandtoDaemon(int32_t sockfd, char* fdata, size_t size) {
- LOGD(SSF_LIB, "Entry");
- ssize_t nwrite = 0;
- size_t nbytes = 0;
- if (sockfd > 0) {
- do {
- nwrite = send(sockfd, fdata + nbytes, size - nbytes, 0);
- } while ((nwrite == -1 && errno == EINTR) || (nwrite > 0 && ((nbytes +=
- nwrite) < size)));
- return (size != nbytes) ? errno : 0;
- }
- LOGE(SSF_LIB, "failed");
- return TEEC_ERROR_COMMUNICATION;
-}
-
-/**
- * Function implementation for recieving data from Simulator
- * daemon through socket
- * @param sockfd file descriptor
- * @param fdata structured data to be received
- * @param size size of fdata in bytes
- * @return
- */
-static uint32_t receiveResponse(int32_t sockfd, char* fdata, size_t size) {
- LOGD(SSF_LIB, "Entry");
- ssize_t nread = 0;
- size_t nbytes = 0;
- if (sockfd > 0) {
- do {
- nread = recv(sockfd, fdata + nbytes, size - nbytes, 0);
- } while ((nread == -1 && errno == EINTR)
- || (nread > 0 && ((nbytes += nread) < size)));
- return (size != nbytes) ? errno : 0;
- }
- LOGE(SSF_LIB, "failed");
- return TEEC_ERROR_COMMUNICATION;
-}
-
-/**
- * Test function to test the daemon
- * @param cmd
- * @param fdata
- * @param size
- * @param in
- * @return
- */
-#ifdef TEST
-static uint32_t Test(char cmd, char* fdata, size_t size, uint32_t in) {
- //TODO: Implementation
- return TEE_SUCCESS;
-}
-#endif
-
-/**
- * API (Interface for TEECAPI) implementation for sending a
- * command to Simulator daemon
- * @param sockfd file descriptor
- * @param cmd command to simulator daemon
- * @param data structured data to daemon
- * @param size size of data
- * @return
- */
-uint32_t sendCommand(int32_t sockfd, TEE_CMD cmd, void* data, size_t size) {
- LOGD(SSF_LIB, "Entry");
- TEE_Result result = TEE_SUCCESS;
- char command = (char)cmd;
-#ifdef TEST
- result = Test(command, (char*)data, size, 1);
- if (result != TEE_SUCCESS) {
- return TEE_ERROR_GENERIC;
- }
-#endif
- result = sendCommandtoDaemon(sockfd, (char*)&command, sizeof(char));
- if (result != TEE_SUCCESS) {
- return TEE_ERROR_GENERIC;
- }
- result = sendCommandtoDaemon(sockfd, (char*)data, size);
- if (result != TEE_SUCCESS) {
- return TEE_ERROR_GENERIC;
- }
- result = receiveResponse(sockfd, (char*)&command, sizeof(char));
- if (result != TEE_SUCCESS) {
- return TEE_ERROR_GENERIC;
- }
- result = receiveResponse(sockfd, (char*)data, size);
- if (result != TEE_SUCCESS) {
- return TEE_ERROR_GENERIC;
- }
-#ifdef TEST
- result = Test(command, (char*)data, size, 0);
- if (result != TEE_SUCCESS) {
- return TEE_ERROR_GENERIC;
- }
-#endif
- return result;
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssfclient.c
+ *
+ * Description: SSF client functions
+ *
+ * Version: 1.0
+ * Created: 20 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: Cheryl (cb), cheryl.b@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include "teestub_command_data.h"
+#include "tee_internal_api.h"
+#include <errno.h>
+#include <assert.h>
+#include "ssf_client.h"
+#include <unistd.h>
+
+/*-----------------------------------------------------------------------------
+ * MACROS
+ *-----------------------------------------------------------------------------*/
+#define SOCKPATH "/tmp/simdaemon" //path to be updated
+
+//#define TEST
+
+/*-----------------------------------------------------------------------------
+ * local functions
+ *-----------------------------------------------------------------------------*/
+/**
+ * API (Interface for TEECAPI) implementation for connecting to
+ * the Simulator daemon through socket
+ * @return socket file descriptor to connected server
+ */
+int32_t connecttoServer(void) {
+ LOGD(SSF_LIB, "Entry");
+ int serverSocket, socklen;
+ size_t sock_path_len = 0;
+ struct sockaddr* sockptr;
+ struct sockaddr_un daemonsock;
+
+ if ((serverSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
+ LOGE(SSF_LIB, "No socket for simdaemon");
+ return -1;
+ }
+ daemonsock.sun_family = AF_UNIX;
+
+ sock_path_len = strlen(SOCKPATH);
+ strncpy(daemonsock.sun_path, SOCKPATH, sock_path_len+1);
+
+ socklen = sizeof(daemonsock);
+ sockptr = (struct sockaddr*)&daemonsock;
+ if (connect(serverSocket, sockptr, socklen) == -1) {
+ LOGE(SSF_LIB, "connection to simdaemon failed");
+ close(serverSocket);
+ return -1;
+ }
+ return serverSocket;
+}
+
+/**
+ * API (Interface for TEECAPI) implementation for disconnecting
+ * from the Simulator daemon through socket
+ * @param ServerSocket
+ */
+void disconnectfromServer(int32_t serverSocket) {
+ int32_t result;
+ LOGD(SSF_LIB, "Entry");
+ if (serverSocket > 0) {
+ result = shutdown(serverSocket, SHUT_WR);
+ if (result != 0) LOGE(SSF_LIB, "disconnectfromServer failed");
+ close(serverSocket);
+ } else {
+ LOGE(SSF_LIB, "Invalid socket, disconnectfromServer failed");
+ }
+}
+
+/**
+ * Function implementation for sending data to Simulator daemon
+ * through socket
+ * @param sockfd file descriptor
+ * @param fdata structured data to daemon
+ * @param size size of fdata in bytes
+ * @return
+ */
+static uint32_t sendCommandtoDaemon(int32_t sockfd, char* fdata, size_t size) {
+ LOGD(SSF_LIB, "Entry");
+ ssize_t nwrite = 0;
+ size_t nbytes = 0;
+ if (sockfd > 0) {
+ do {
+ nwrite = send(sockfd, fdata + nbytes, size - nbytes, 0);
+ } while ((nwrite == -1 && errno == EINTR) || (nwrite > 0 && ((nbytes +=
+ nwrite) < size)));
+ return (size != nbytes) ? errno : 0;
+ }
+ LOGE(SSF_LIB, "failed");
+ return TEEC_ERROR_COMMUNICATION;
+}
+
+/**
+ * Function implementation for recieving data from Simulator
+ * daemon through socket
+ * @param sockfd file descriptor
+ * @param fdata structured data to be received
+ * @param size size of fdata in bytes
+ * @return
+ */
+static uint32_t receiveResponse(int32_t sockfd, char* fdata, size_t size) {
+ LOGD(SSF_LIB, "Entry");
+ ssize_t nread = 0;
+ size_t nbytes = 0;
+ if (sockfd > 0) {
+ do {
+ nread = recv(sockfd, fdata + nbytes, size - nbytes, 0);
+ } while ((nread == -1 && errno == EINTR)
+ || (nread > 0 && ((nbytes += nread) < size)));
+ return (size != nbytes) ? errno : 0;
+ }
+ LOGE(SSF_LIB, "failed");
+ return TEEC_ERROR_COMMUNICATION;
+}
+
+/**
+ * Test function to test the daemon
+ * @param cmd
+ * @param fdata
+ * @param size
+ * @param in
+ * @return
+ */
+#ifdef TEST
+static uint32_t Test(char cmd, char* fdata, size_t size, uint32_t in) {
+ //TODO: Implementation
+ return TEE_SUCCESS;
+}
+#endif
+
+/**
+ * API (Interface for TEECAPI) implementation for sending a
+ * command to Simulator daemon
+ * @param sockfd file descriptor
+ * @param cmd command to simulator daemon
+ * @param data structured data to daemon
+ * @param size size of data
+ * @return
+ */
+uint32_t sendCommand(int32_t sockfd, TEE_CMD cmd, void* data, size_t size) {
+ LOGD(SSF_LIB, "Entry");
+ TEE_Result result = TEE_SUCCESS;
+ char command = (char)cmd;
+#ifdef TEST
+ result = Test(command, (char*)data, size, 1);
+ if (result != TEE_SUCCESS) {
+ return TEE_ERROR_GENERIC;
+ }
+#endif
+ result = sendCommandtoDaemon(sockfd, (char*)&command, sizeof(char));
+ if (result != TEE_SUCCESS) {
+ return TEE_ERROR_GENERIC;
+ }
+ result = sendCommandtoDaemon(sockfd, (char*)data, size);
+ if (result != TEE_SUCCESS) {
+ return TEE_ERROR_GENERIC;
+ }
+ result = receiveResponse(sockfd, (char*)&command, sizeof(char));
+ if (result != TEE_SUCCESS) {
+ return TEE_ERROR_GENERIC;
+ }
+ result = receiveResponse(sockfd, (char*)data, size);
+ if (result != TEE_SUCCESS) {
+ return TEE_ERROR_GENERIC;
+ }
+#ifdef TEST
+ result = Test(command, (char*)data, size, 0);
+ if (result != TEE_SUCCESS) {
+ return TEE_ERROR_GENERIC;
+ }
+#endif
+ return result;
+}
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssf_crypto.c
- *
- * Description: SSF crypto functions
- *
- * Version: 1.0
- * Created: 23 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: krishna (Kr), k.devale@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-#define _CRT_RAND_S
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include "uci_api.h"
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include "unistd.h"
-#include "uci_internal.h"
-#include "tee_internal_api.h"
-#include <time.h>
-#include <sys/time.h>
-
-
-/*-----------------------------------------------------------------------------
- * MACROS
- *-----------------------------------------------------------------------------*/
-#define g_bTAdbug 1
-#define TZ_PRINT(fmt...) \
- do {if (g_bTAdbug) printf("[SSFLIB] ");printf(fmt);}while(0)
-#define TZ_ERROR(fmt...) \
- do {if (g_bTAdbug) printf("[SSFLIB] ");printf(fmt);}while(0)
-#undef PrintBYTE
-#define PrintBYTE(msg, Data, DataLen) { \
- int idx; \
- TZ_PRINT("%10s =", msg); \
- for(idx=0; idx<(int)DataLen; idx++) { \
- if((idx!=0) && ((idx%16)==0)) TZ_PRINT("\n"); \
- if((idx % 4) == 0) TZ_PRINT(" 0x"); \
- TZ_PRINT("%.2x", Data[idx]); \
- } \
- TZ_PRINT("\n"); \
- }
-
-/*-----------------------------------------------------------------------------
- * Definitions
- *-----------------------------------------------------------------------------*/
-struct __TEE_ObjectHandle {
- TEE_ObjectInfo info;
-};
-
-struct __TEE_OperationHandle {
- TEE_OperationInfo info;
-};
-
-struct TEE_Operation {
- TEE_OperationInfo info;
- TEE_ObjectHandle key1;
- TEE_ObjectHandle key2;
- int crypto; // handle to crypto driver or ponter to crypto library context
-};
-
-static long getClock(void) {
- struct timeval tv;
- gettimeofday (&tv, NULL);
- return (tv.tv_sec * 1000 + tv.tv_usec / 1000);
-}
-
-/*-----------------------------------------------------------------------------
- * Local functions
- *-----------------------------------------------------------------------------*/
-static uint32_t object_type_from_algorithm(uint32_t alg, uint32_t *obj_type,
- uint32_t * uci_type) {
- switch (alg) {
-
- // KRISHNA: ADDED BELOW, VERIFY ONCE
- case TEE_ALG_AES_ECB_PKCS5:
- case TEE_ALG_AES_ECB_PKCS7:
- case TEE_ALG_AES_ECB_ISO9797_M1:
- case TEE_ALG_AES_ECB_ISO9797_M2:
- case TEE_ALG_AES_CBC_PKCS5:
- case TEE_ALG_AES_CBC_PKCS7:
- case TEE_ALG_AES_CBC_ISO9797_M1:
- case TEE_ALG_AES_CBC_ISO9797_M2:
- // OLD CODE
- case TEE_ALG_AES_ECB_NOPAD:
- case TEE_ALG_AES_CBC_NOPAD:
- case TEE_ALG_AES_CTR:
- case TEE_ALG_AES_CTR_NOPAD:
- case TEE_ALG_AES_CTS:
- case TEE_ALG_AES_XTS:
- case TEE_ALG_AES_CCM:
- case TEE_ALG_AES_GCM:
- *obj_type = TEE_TYPE_AES;
- *uci_type = ID_UCI_AES;
- break;
- case TEE_ALG_AES_CBC_MAC_NOPAD:
- *obj_type = TEE_TYPE_AES;
- *uci_type = ID_UCI_XCBCMAC;
- break;
- case TEE_ALG_AES_CBC_MAC_PKCS5:
- case TEE_ALG_AES_CMAC:
- case TEE_ALG_DES_CBC_MAC_NOPAD:
- case TEE_ALG_DES_CBC_MAC_PKCS5:
- case TEE_ALG_DES3_CBC_MAC_NOPAD:
- case TEE_ALG_DES3_CBC_MAC_PKCS5:
- *obj_type = TEE_TYPE_AES;
- *uci_type = ID_UCI_CMAC;
- break;
- case TEE_ALG_DES_ECB_NOPAD:
- case TEE_ALG_DES_CBC_NOPAD:
- *obj_type = TEE_TYPE_DES;
- *uci_type = ID_UCI_DES;
- break;
- case TEE_ALG_DES3_ECB_NOPAD:
- case TEE_ALG_DES3_CBC_NOPAD:
- *obj_type = TEE_TYPE_DES3;
- *uci_type = ID_UCI_TDES;
- break;
- case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
- case TEE_ALG_RSAES_PKCS1_V1_5:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
- case TEE_ALG_RSA_NOPAD:
- *obj_type = TEE_TYPE_RSA_KEYPAIR;
- *uci_type = 0;
- break;
- case TEE_ALG_DSA_SHA1:
- *obj_type = TEE_TYPE_DSA_KEYPAIR;
- *uci_type = ID_UCI_DSA;
- break;
-#ifdef ECC_IMPLEMENTATION
- case TEE_ALG_ECDSA_P160:
- case TEE_ALG_ECDSA_P192:
- case TEE_ALG_ECDSA_P224:
- case TEE_ALG_ECDSA_P256:
- case TEE_ALG_ECDSA_P384:
- case TEE_ALG_ECDSA_P521:
- *obj_type = TEE_TYPE_ECDSA_KEYPAIR;
- *uci_type = ID_UCI_ECDSA;
- break;
- case TEE_ALG_ECDH_P192:
- case TEE_ALG_ECDH_P224:
- case TEE_ALG_ECDH_P256:
- case TEE_ALG_ECDH_P384:
- case TEE_ALG_ECDH_P521:
- *obj_type = TEE_TYPE_ECDH_KEYPAIR;
- *uci_type = ID_UCI_ECDH;
- break;
-#endif
- case TEE_ALG_DH_DERIVE_SHARED_SECRET:
- *obj_type = TEE_TYPE_DH_KEYPAIR;
- *uci_type = ID_UCI_DH;
- break;
- case TEE_ALG_HMAC_MD5:
- *obj_type = TEE_TYPE_HMAC_MD5;
- *uci_type = ID_UCI_HMD5;
- break;
- case TEE_ALG_HMAC_SHA1:
- *obj_type = TEE_TYPE_HMAC_SHA1;
- *uci_type = ID_UCI_HSHA1;
- break;
- case TEE_ALG_HMAC_SHA224:
- *obj_type = TEE_TYPE_HMAC_SHA224;
- *uci_type = ID_UCI_HSHA224;
- break;
- case TEE_ALG_HMAC_SHA256:
- *obj_type = TEE_TYPE_HMAC_SHA256;
- *uci_type = ID_UCI_HSHA256;
- break;
- case TEE_ALG_HMAC_SHA384:
- *obj_type = TEE_TYPE_HMAC_SHA384;
- *uci_type = ID_UCI_HSHA384;
- break;
- case TEE_ALG_HMAC_SHA512:
- *obj_type = TEE_TYPE_HMAC_SHA512;
- *uci_type = ID_UCI_HSHA512;
- break;
- case TEE_ALG_MD5:
- *uci_type = ID_UCI_MD5;
- break;
- case TEE_ALG_SHA1:
- *uci_type = ID_UCI_SHA1;
- break;
- case TEE_ALG_SHA224:
- *uci_type = ID_UCI_SHA224;
- break;
- case TEE_ALG_SHA256:
- *uci_type = ID_UCI_SHA256;
- break;
- case TEE_ALG_SHA384:
- *uci_type = ID_UCI_SHA384;
- break;
- case TEE_ALG_SHA512:
- *uci_type = ID_UCI_SHA512;
- break;
- }
- return *obj_type;
-}
-
-static int crypto_lib_init_operation(TEE_OperationHandle operation) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
- if (uci_md_init(op->crypto) != UCI_SUCCESS) {
- TEE_Panic(0);
- }
- return 0;
-}
-
-/*-----------------------------------------------------------------------------
- * TEE API implementation
- *-----------------------------------------------------------------------------*/
-// Generic Operation Functions
-TEE_Result TEE_AllocateOperation(TEE_OperationHandle *operation,
- uint32_t algorithm, uint32_t mode, uint32_t maxKeySize) {
- struct TEE_Operation * op;
- uint32_t alg_class = 0;
- uint32_t object_type = 0;
- uint32_t uci_type = 0;
- TEE_Result rc;
- TEE_ObjectHandle key1 = TEE_HANDLE_NULL;
- TEE_ObjectHandle key2 = TEE_HANDLE_NULL;
- int digest_len = 0;
- uint32_t block_len = 0;
- uint32_t key_object_type = 0;
- /* NEW CODE FROM PLATFORM CODE BASE OF SECURE OS */
- // check parameters compatibility
- switch(algorithm)
- {
- /* Algorithm Class is SYMMETRIC CIPHER */
- case TEE_ALG_AES_ECB_NOPAD:
- case TEE_ALG_AES_CBC_NOPAD:
- case TEE_ALG_AES_CTR:
- case TEE_ALG_AES_CTR_NOPAD:
- case TEE_ALG_AES_ECB_PKCS5:
- case TEE_ALG_AES_ECB_PKCS7:
- case TEE_ALG_AES_ECB_ISO9797_M1:
- case TEE_ALG_AES_ECB_ISO9797_M2:
- case TEE_ALG_AES_CBC_PKCS5:
- case TEE_ALG_AES_CBC_PKCS7:
- case TEE_ALG_AES_CBC_ISO9797_M1:
- case TEE_ALG_AES_CBC_ISO9797_M2:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_AES;
- block_len = 16;
- digest_len = 0;
- break;
-
- case TEE_ALG_AES_XTS:
- case TEE_ALG_AES_CTS:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
-
- case TEE_ALG_DES_ECB_NOPAD:
- case TEE_ALG_DES_CBC_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_DES;
- block_len = 8;
- digest_len = 0;
- break;
-
- case TEE_ALG_DES3_ECB_NOPAD:
- case TEE_ALG_DES3_CBC_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_DES3;
- block_len = 8;
- digest_len = 0;
- break;
-
- /* Algorithm Class is AE */
- case TEE_ALG_AES_CCM:
- case TEE_ALG_AES_GCM:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
-
- /* Algorithm Class is MAC */
- case TEE_ALG_AES_CBC_MAC_NOPAD:
- case TEE_ALG_AES_CBC_MAC_PKCS5:
- case TEE_ALG_DES_CBC_MAC_NOPAD:
- case TEE_ALG_DES_CBC_MAC_PKCS5:
- case TEE_ALG_AES_CMAC:
- case TEE_ALG_DES3_CBC_MAC_NOPAD:
- case TEE_ALG_DES3_CBC_MAC_PKCS5:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
-
-
-
- case TEE_ALG_HMAC_MD5:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_MD5;
- block_len = 64;
- digest_len = 16;
- break;
-
- case TEE_ALG_HMAC_SHA1:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA1;
- block_len = 64;
- digest_len = 20;
- break;
-
- case TEE_ALG_HMAC_SHA224:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA224;
- block_len = 64;
- digest_len = 28;
- break;
-
- case TEE_ALG_HMAC_SHA256:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA256;
- block_len = 64;
- digest_len = 32;
- break;
-
- case TEE_ALG_HMAC_SHA384:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA384;
- block_len = 64;
- digest_len = 48;
- break;
-
- case TEE_ALG_HMAC_SHA512:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA512;
- block_len = 64;
- digest_len = 64;
- break;
-
- /* Algorithm Class is DIGIT */
- case TEE_ALG_MD5:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 16;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA1:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 20;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA224:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 28;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA256:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 32;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA384:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 48;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA512:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 64;
- block_len = 64;
- break;
-
- /* Algorithm Class is ASYMMETRIC CIPHER */
- case TEE_ALG_RSAES_PKCS1_V1_5:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
- case TEE_ALG_RSA_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_CIPHER;
- key_object_type = TEE_TYPE_RSA_KEYPAIR;
- block_len = 0;
- digest_len = 0;
- break;
-
- /* Algorithm Class is SIGNATURE */
- case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
- if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
- key_object_type = TEE_TYPE_RSA_KEYPAIR;
- break;
-
- case TEE_ALG_ECDSA_P160:
- case TEE_ALG_ECDSA_P192:
- case TEE_ALG_ECDSA_P224:
- case TEE_ALG_ECDSA_P256:
- case TEE_ALG_ECDSA_P384:
- case TEE_ALG_ECDSA_P521:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
-
- case TEE_ALG_DSA_SHA1:
- case TEE_ALG_ECDH_P192:
- case TEE_ALG_ECDH_P224:
- case TEE_ALG_ECDH_P256:
- case TEE_ALG_ECDH_P384:
- case TEE_ALG_ECDH_P521:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
-
- /* Algorithm Class is KEY DERIVATION */
- case TEE_ALG_DH_DERIVE_SHARED_SECRET:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
-
- default:
- //printf("Not Support Algorithm : %X", algorithm);
- TZ_ERROR("Not Support Algorithm %d,%s %X\n", __LINE__, __func__, algorithm);
- rc = TEE_ERROR_NOT_SUPPORTED;
- goto exit;
- break;
- }
-
-
-
-
-
-
- /*
- // OLD SWITCH
- switch (algorithm) {
- case TEE_ALG_AES_XTS:
- return TEE_ERROR_NOT_SUPPORTED;
- break;
- case TEE_ALG_AES_ECB_NOPAD:
- case TEE_ALG_AES_CBC_NOPAD:
- case TEE_ALG_AES_CTR:
- case TEE_ALG_AES_CTS:
- case TEE_ALG_DES_ECB_NOPAD:
- case TEE_ALG_DES_CBC_NOPAD:
- case TEE_ALG_DES3_ECB_NOPAD:
- case TEE_ALG_DES3_CBC_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- alg_class = TEE_OPERATION_CIPHER;
- break;
- case TEE_ALG_AES_CCM:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 0; // will be set during initialisation
- alg_class = TEE_OPERATION_AE;
- break;
- case TEE_ALG_AES_GCM:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 0; // will be set during initialisation
- alg_class = TEE_OPERATION_AE;
- break;
- case TEE_ALG_AES_CBC_MAC_NOPAD:
- case TEE_ALG_AES_CBC_MAC_PKCS5:
- case TEE_ALG_AES_CMAC:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- alg_class = TEE_OPERATION_MAC;
- break;
- case TEE_ALG_DES_CBC_MAC_NOPAD:
- case TEE_ALG_DES_CBC_MAC_PKCS5:
- case TEE_ALG_DES3_CBC_MAC_NOPAD:
- case TEE_ALG_DES3_CBC_MAC_PKCS5:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- alg_class = TEE_OPERATION_MAC;
- return TEE_ERROR_NOT_SUPPORTED;
- case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
- case TEE_ALG_DSA_SHA1:
-#ifdef ECC_IMPLEMENTATION
- case TEE_ALG_ECDSA_P160:
- case TEE_ALG_ECDSA_P192:
- case TEE_ALG_ECDSA_P224:
- case TEE_ALG_ECDSA_P256:
- case TEE_ALG_ECDSA_P384:
- case TEE_ALG_ECDSA_P521:
-#endif
- if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
- break;
- case TEE_ALG_RSAES_PKCS1_V1_5:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
- case TEE_ALG_RSA_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- alg_class = TEE_OPERATION_ASYMMETRIC_CIPHER;
- break;
- case TEE_ALG_DH_DERIVE_SHARED_SECRET:
- if (mode != TEE_MODE_DERIVE) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- alg_class = TEE_OPERATION_KEY_DERIVATION;
- break;
- case TEE_ALG_MD5:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 16;
- alg_class = TEE_OPERATION_DIGEST;
- break;
- case TEE_ALG_SHA1:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 20;
- alg_class = TEE_OPERATION_DIGEST;
- break;
- case TEE_ALG_SHA224:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 28;
- alg_class = TEE_OPERATION_DIGEST;
- break;
- case TEE_ALG_SHA256:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 32;
- alg_class = TEE_OPERATION_DIGEST;
- break;
- case TEE_ALG_SHA384:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 48;
- alg_class = TEE_OPERATION_DIGEST;
- break;
- case TEE_ALG_SHA512:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 64;
- alg_class = TEE_OPERATION_DIGEST;
- break;
- case TEE_ALG_HMAC_MD5:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 16;
- alg_class = TEE_OPERATION_MAC;
- break;
- case TEE_ALG_HMAC_SHA1:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 20;
- alg_class = TEE_OPERATION_MAC;
- break;
- case TEE_ALG_HMAC_SHA224:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 28;
- alg_class = TEE_OPERATION_MAC;
- break;
- case TEE_ALG_HMAC_SHA256:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 32;
- alg_class = TEE_OPERATION_MAC;
- break;
- case TEE_ALG_HMAC_SHA384:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 48;
- alg_class = TEE_OPERATION_MAC;
- break;
- case TEE_ALG_HMAC_SHA512:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- digest_len = 64;
- alg_class = TEE_OPERATION_MAC;
- break;
- default:
- TZ_ERROR("algorithm error %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_NOT_SUPPORTED;
- }
- */
- object_type = object_type_from_algorithm(algorithm, &object_type, &uci_type);
- if (alg_class != TEE_OPERATION_DIGEST) {
- rc = TEE_AllocateTransientObject(object_type, maxKeySize, &key1);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_AllocateTransientObject error %d,%s\n", __LINE__, __func__);
- return rc;
- }
-#if 0
- // TODO: TEE_ALG_AES_XTS not supported
- if (algorithm == TEE_ALG_AES_XTS)// 2 keys for TEE_ALG_AES_XTS
- {
- rc = TEE_AllocateTransientObject(object_type, maxKeySize, &key2);
- if (rc != TEE_SUCCESS) {
- TEE_CloseObject(key1);
- TZ_ERROR("TEE_AllocateTransientObject error %d,%s\n",
- __LINE__,
- __func__);
- return rc;
- }
- }
-#endif
- }
- //ALLOC MEMORY
- op = (TEE_Operation*)OsaMalloc(sizeof(struct TEE_Operation));
- if (!op) {
- if (key1) {
- TEE_CloseObject(key1);
- }
-#if 0
- // TODO: TEE_ALG_AES_XTS not supported
- if (key2) {
- TEE_CloseObject(key2);
- }
-#endif
- TZ_ERROR("malloc error %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memset(op, 0, sizeof(struct TEE_Operation));
- op->info.algorithm = algorithm;
- op->info.mode = mode;
- op->info.maxKeySize = maxKeySize;
- op->info.digestLength = digest_len;
- op->info.keySize = 0;
- op->info.operationClass = alg_class;
- op->info.requiredKeyUsage = 0;
- switch (mode) {
- case TEE_MODE_ENCRYPT:
- op->info.requiredKeyUsage |= TEE_USAGE_ENCRYPT;
- break;
- case TEE_MODE_DECRYPT:
- op->info.requiredKeyUsage |= TEE_USAGE_DECRYPT;
- break;
- case TEE_MODE_MAC:
- op->info.requiredKeyUsage |= TEE_USAGE_MAC;
- break;
- case TEE_MODE_DERIVE:
- op->info.requiredKeyUsage |= TEE_USAGE_DERIVE;
- break;
- case TEE_MODE_SIGN:
- op->info.requiredKeyUsage |= TEE_USAGE_SIGN;
- break;
- case TEE_MODE_VERIFY:
- op->info.requiredKeyUsage |= TEE_USAGE_VERIFY;
- break;
- }
- op->info.handleState = 0;
- if (alg_class == TEE_OPERATION_DIGEST) {
- op->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
- }
-#if 1
- // TODO: TEE_ALG_AES_XTS not supported
- if (algorithm == TEE_ALG_AES_XTS) {
- op->info.handleState |= TEE_HANDLE_FLAG_EXPECT_TWO_KEYS;
- }
-
- /* key1 alloc */
- if (key_object_type) {
- if (TEE_AllocateTransientObject(key_object_type, maxKeySize, &key1) != TEE_SUCCESS) {
- rc = TEE_ERROR_OUT_OF_MEMORY;
- goto error;
- }
- }
-
- /* key2 alloc for XTS */
- if (algorithm == TEE_ALG_AES_XTS) {
- if (TEE_AllocateTransientObject(key_object_type, maxKeySize, &key2) != TEE_SUCCESS) {
- rc = TEE_ERROR_OUT_OF_MEMORY;
- goto error;
- }
- }
-#endif
- op->key1 = key1;
- op->key2 = key2;
- // [TODO] NEED TO FIX THIS STRUCTURE TO INCLUDE BLOCK_LEN MEMBER
- //op->block_len = block_len;
- if (uci_type != 0) {
- op->crypto = uci_context_alloc(uci_type, UCI_SW);
- } else {
- op->crypto = 0;
- }
- *operation = (TEE_OperationHandle)&op->info;
-
- if (alg_class == TEE_OPERATION_DIGEST) {
- crypto_lib_init_operation(*operation); //in case hash contex will not inited.
- }
- return TEE_SUCCESS;
-
-
-error:
- if (key1) {
- TEE_CloseObject(key1);
- }
- if (key2) {
- TEE_CloseObject(key2);
- }
- if (op) {
- free(op);
- }
-exit:
- *operation = TEE_HANDLE_NULL;
- printf("Error : %X", rc);
-
- return rc;
-
-}
-// KRISHNA - OLD CODE
-
-
-/*TEE_Result TEE_AllocateOperation(TEE_OperationHandle *operation, uint32_t algorithm, uint32_t mode, uint32_t maxKeySize)
-{
- //PERMISSION_CHECK(PERM_CRYPTO);
-
- crypto_internal_operation * op;
- TEE_Result rc=TEE_SUCCESS;
- uint32_t alg_class = 0;
- uint32_t key_object_type = 0;
- uint32_t digest_len = 0;
- uint32_t block_len = 0;
- TEE_ObjectHandle key1 = TEE_HANDLE_NULL;
- TEE_ObjectHandle key2 = TEE_HANDLE_NULL;
-
- // check parameters compatibility
- switch(algorithm)
- {
- // Algorithm Class is SYMMETRIC CIPHER
- case TEE_ALG_AES_ECB_NOPAD:
- case TEE_ALG_AES_CBC_NOPAD:
- case TEE_ALG_AES_CTR:
- case TEE_ALG_AES_CTR_NOPAD:
- case TEE_ALG_AES_ECB_PKCS5:
- case TEE_ALG_AES_ECB_PKCS7:
- case TEE_ALG_AES_ECB_ISO9797_M1:
- case TEE_ALG_AES_ECB_ISO9797_M2:
- case TEE_ALG_AES_CBC_PKCS5:
- case TEE_ALG_AES_CBC_PKCS7:
- case TEE_ALG_AES_CBC_ISO9797_M1:
- case TEE_ALG_AES_CBC_ISO9797_M2:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_AES;
- block_len = 16;
- digest_len = 0;
- break;
-
- case TEE_ALG_AES_XTS:
- case TEE_ALG_AES_CTS:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_AES;
- block_len = 32; // for CTS & XTS need 2 AES blocks
- digest_len = 0;
- break;
-
- case TEE_ALG_DES_ECB_NOPAD:
- case TEE_ALG_DES_CBC_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_DES;
- block_len = 8;
- digest_len = 0;
- break;
-
- case TEE_ALG_DES3_ECB_NOPAD:
- case TEE_ALG_DES3_CBC_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_CIPHER;
- key_object_type = TEE_TYPE_DES3;
- block_len = 8;
- digest_len = 0;
- break;
-
- // Algorithm Class is AE
- case TEE_ALG_AES_CCM:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_AE;
- key_object_type = TEE_TYPE_AES;
- block_len = 16;
- digest_len = 0;
- break;
-
- case TEE_ALG_AES_GCM:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_AE;
- key_object_type = TEE_TYPE_AES;
- block_len = 16;
- digest_len = 0;
- break;
-
- // Algorithm Class is MAC
- case TEE_ALG_AES_CBC_MAC_NOPAD:
- case TEE_ALG_AES_CBC_MAC_PKCS5:
- case TEE_ALG_AES_CMAC:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_AES;
- block_len = 16;
- digest_len = 16;
- break;
-
- case TEE_ALG_DES_CBC_MAC_NOPAD:
- case TEE_ALG_DES_CBC_MAC_PKCS5:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_DES;
- block_len = 8;
- digest_len = 8;
- break;
-
- case TEE_ALG_DES3_CBC_MAC_NOPAD:
- case TEE_ALG_DES3_CBC_MAC_PKCS5:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_DES3;
- block_len = 8;
- digest_len = 8;
- break;
-
- case TEE_ALG_HMAC_MD5:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_MD5;
- block_len = 64;
- digest_len = 16;
- break;
-
- case TEE_ALG_HMAC_SHA1:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA1;
- block_len = 64;
- digest_len = 20;
- break;
-
- case TEE_ALG_HMAC_SHA224:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA224;
- block_len = 64;
- digest_len = 28;
- break;
-
- case TEE_ALG_HMAC_SHA256:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA256;
- block_len = 64;
- digest_len = 32;
- break;
-
- case TEE_ALG_HMAC_SHA384:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA384;
- block_len = 64;
- digest_len = 48;
- break;
-
- case TEE_ALG_HMAC_SHA512:
- if (mode != TEE_MODE_MAC) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_MAC;
- key_object_type = TEE_TYPE_HMAC_SHA512;
- block_len = 64;
- digest_len = 64;
- break;
-
- // Algorithm Class is DIGIT
- case TEE_ALG_MD5:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 16;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA1:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 20;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA224:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 28;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA256:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 32;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA384:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 48;
- block_len = 64;
- break;
-
- case TEE_ALG_SHA512:
- if (mode != TEE_MODE_DIGEST) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_DIGEST;
- key_object_type = 0;
- digest_len = 64;
- block_len = 64;
- break;
-
- // Algorithm Class is ASYMMETRIC CIPHER
- case TEE_ALG_RSAES_PKCS1_V1_5:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
- case TEE_ALG_RSA_NOPAD:
- if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_CIPHER;
- key_object_type = TEE_TYPE_RSA_KEYPAIR;
- block_len = 0;
- digest_len = 0;
- break;
-
- // Algorithm Class is SIGNATURE
- case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
- if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
- key_object_type = TEE_TYPE_RSA_KEYPAIR;
- break;
-
- case TEE_ALG_ECDSA_P160:
- case TEE_ALG_ECDSA_P192:
- case TEE_ALG_ECDSA_P224:
- case TEE_ALG_ECDSA_P256:
- case TEE_ALG_ECDSA_P384:
- case TEE_ALG_ECDSA_P521:
- if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
- key_object_type = TEE_TYPE_RSA_KEYPAIR;
- break;
-
- case TEE_ALG_DSA_SHA1:
- if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
- key_object_type = TEE_TYPE_DSA_KEYPAIR;
- break;
-
- case TEE_ALG_ECDH_P192:
- case TEE_ALG_ECDH_P224:
- case TEE_ALG_ECDH_P256:
- case TEE_ALG_ECDH_P384:
- case TEE_ALG_ECDH_P521:
- if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
- key_object_type = TEE_TYPE_ECDH_KEYPAIR;
- break;
-
- // Algorithm Class is KEY DERIVATION
- case TEE_ALG_DH_DERIVE_SHARED_SECRET:
- if (mode != TEE_MODE_DERIVE) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
-
- alg_class = TEE_OPERATION_KEY_DERIVATION;
- key_object_type = TEE_TYPE_DH_KEYPAIR;
- break;
-
- default:
- LOGE(TAG, "Not Support Algorithm : %X", algorithm);
- rc = TEE_ERROR_NOT_SUPPORTED;
- goto exit;
- break;
- }
-
- // first malloc for crypto operation
- op = malloc(sizeof (crypto_internal_operation));
- if (!op) {
- rc = TEE_ERROR_OUT_OF_MEMORY;
- goto exit;
- }
-
- memset(op, 0, sizeof (crypto_internal_operation));
-
- // Set TEE_OperationInfo
- op->info.algorithm = algorithm;
- op->info.operationClass = alg_class;
- op->info.mode = mode;
- op->info.digestLength = digest_len;
- op->info.maxKeySize = maxKeySize;
- op->info.keySize = maxKeySize;
-
- if (mode == TEE_MODE_ENCRYPT) {
- op->info.requiredKeyUsage |= TEE_USAGE_ENCRYPT;
- }
- if (mode == TEE_MODE_DECRYPT) {
- op->info.requiredKeyUsage |= TEE_USAGE_DECRYPT;
- }
- if (mode == TEE_MODE_MAC) {
- op->info.requiredKeyUsage |= TEE_USAGE_MAC;
- }
- if (mode == TEE_MODE_DERIVE) {
- op->info.requiredKeyUsage |= TEE_USAGE_DERIVE;
- }
- if (mode == TEE_MODE_SIGN) {
- op->info.requiredKeyUsage |= TEE_USAGE_SIGN;
- }
- if (mode == TEE_MODE_VERIFY) {
- op->info.requiredKeyUsage |= TEE_USAGE_VERIFY;
- }
- if (algorithm == TEE_ALG_RSA_NOPAD)
- {
- if (mode == TEE_MODE_ENCRYPT) {
- op->info.requiredKeyUsage |= TEE_USAGE_VERIFY;
- }
- else if (mode == TEE_MODE_DECRYPT) {
- op->info.requiredKeyUsage |= TEE_USAGE_SIGN;
- }
- }
-
- if (algorithm == TEE_ALG_AES_XTS) {
- op->info.handleState |= TEE_HANDLE_FLAG_EXPECT_TWO_KEYS;
- }
-
- // get handle
- if(crypto_internal_open(op)!=0) {
- rc = TEE_ERROR_NOT_SUPPORTED;
- goto error;
- }
-
- // key1 alloc
- if (key_object_type) {
- if (TEE_AllocateTransientObject(key_object_type, maxKeySize, &key1) != TEE_SUCCESS) {
- rc = TEE_ERROR_OUT_OF_MEMORY;
- goto error;
- }
- }
-
- // key2 alloc for XTS
- if (algorithm == TEE_ALG_AES_XTS) {
- if (TEE_AllocateTransientObject(key_object_type, maxKeySize, &key2) != TEE_SUCCESS) {
- rc = TEE_ERROR_OUT_OF_MEMORY;
- goto error;
- }
- }
-
- // key map for crypto operation
- op->key1 = key1;
- op->key2 = key2;
- op->block_len = block_len;
-
- *operation = (TEE_OperationHandle) &op->info;
- if (alg_class == TEE_OPERATION_DIGEST) {
- TEE_DigestInit(*operation);
- }
-
- return TEE_SUCCESS;
-
-error:
- crypto_internal_close(op);
- if (key1) {
- TEE_CloseObject(key1);
- }
- if (key2) {
- TEE_CloseObject(key2);
- }
- if (op) {
- free(op);
- }
-exit:
- *operation = TEE_HANDLE_NULL;
- LOGE(TAG, "Error : %X", rc);
- return rc;
-}
-*/
-
-
-
-void TEE_FreeOperation(TEE_OperationHandle operation) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
- if (op->key1) {
- TEE_CloseObject(op->key1);
- }
- if (op->key2) {
- TEE_CloseObject(op->key2);
- }
- if (uci_context_free(op->crypto) != UCI_SUCCESS) {
- TZ_ERROR("free error %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- OsaFree(op);
-}
-
-void TEE_GetOperationInfo(TEE_OperationHandle operation,
- TEE_OperationInfo* operationInfo) {
- operationInfo->algorithm = operation->info.algorithm;
- operationInfo->digestLength = operation->info.digestLength;
- operationInfo->handleState = operation->info.handleState;
- operationInfo->keySize = operation->info.keySize;
- operationInfo->maxKeySize = operation->info.maxKeySize;
- operationInfo->mode = operation->info.mode;
- operationInfo->operationClass = operation->info.operationClass;
- operationInfo->requiredKeyUsage = operation->info.requiredKeyUsage;
-}
-
-void TEE_ResetOperation(TEE_OperationHandle operation) {
- operation->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
-}
-
-TEE_Result TEE_SetOperationKey(TEE_OperationHandle operation,
- TEE_ObjectHandle key) {
- uci_key_s ucikey;
- uci_param_s uciparam;
- TEE_Result rc;
- unsigned char pub[384];
- unsigned char priv[384];
- unsigned char module[384];
- size_t pubLen = 384;
- size_t privLen = 384;
- size_t moduleLen = 384;
- unsigned int alg;
- memset(&ucikey, 0, sizeof(uci_key_s));
- memset(&uciparam, 0, sizeof(uci_param_s));
-
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass == TEE_OPERATION_DIGEST
- || operation->info.algorithm == TEE_ALG_AES_XTS) {
- TZ_ERROR("operation error %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (key == TEE_HANDLE_NULL) {
- TEE_CloseObject(op->key1);
- op->key1 = TEE_HANDLE_NULL;
- return TEE_SUCCESS;
- }
- // check key usage flags
- if ((key->info.objectUsage | ~op->info.requiredKeyUsage) != 0xffffffff) {
- TZ_ERROR("Usage don't match line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-
- //set key pair
- switch (op->info.algorithm) {
- //SIGN OR VERIFY
- case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PKCS15_MD5;
- break;
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PKCS15_SHA1;
- break;
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PKCS15_SHA224;
- break;
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PKCS15_SHA256;
- break;
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PKCS15_SHA384;
- break;
- case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PKCS15_SHA512;
- break;
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PSS_SHA1;
- break;
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PSS_SHA224;
- break;
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PSS_SHA256;
- break;
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PSS_SHA384;
- break;
- case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
- uciparam.ucip_rsa_padding = ID_UCI_RSASSA_PSS_SHA512;
- break;
- case TEE_ALG_DSA_SHA1:
- break;
- //ENCRYPT OR DECRYPT
- case TEE_ALG_RSAES_PKCS1_V1_5:
- uciparam.ucip_rsa_padding = ID_UCI_RSAES_PKCS15;
- break;
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
- uciparam.ucip_rsa_padding = ID_UCI_RSAES_OAEP_SHA1;
- break;
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
- uciparam.ucip_rsa_padding = ID_UCI_RSAES_OAEP_SHA224;
- break;
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
- uciparam.ucip_rsa_padding = ID_UCI_RSAES_OAEP_SHA256;
- break;
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
- uciparam.ucip_rsa_padding = ID_UCI_RSAES_OAEP_SHA384;
- break;
- case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
- uciparam.ucip_rsa_padding = ID_UCI_RSAES_OAEP_SHA512;
- break;
- case TEE_ALG_RSA_NOPAD:
- uciparam.ucip_rsa_padding = ID_UCI_NO_PADDING;
- break;
- }
- size_t obj_size = (size_t)(key->info.objectSize);
- switch (key->info.objectType) {
- case TEE_TYPE_RSA_PUBLIC_KEY:
- case TEE_TYPE_RSA_KEYPAIR:
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_RSA_MODULUS, module,
- &moduleLen);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_RSA_PUBLIC_EXPONENT, pub,
- &pubLen);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- ucikey.ucik_rsa_n = module;
- ucikey.ucik_rsa_n_len = moduleLen;
- ucikey.ucik_rsa_e = pub;
- ucikey.ucik_rsa_e_len = pubLen;
- ucikey.ucik_rsa_d = NULL;
- ucikey.ucik_rsa_d_len = 0;
-
- if (key->info.objectType == TEE_TYPE_RSA_KEYPAIR) {
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_RSA_PRIVATE_EXPONENT,
- priv, &privLen);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n",
- __LINE__, __func__);
- return rc;
- }
- ucikey.ucik_rsa_d = priv;
- ucikey.ucik_rsa_d_len = privLen;
- }
- switch (key->info.objectSize) {
- case 512:
- alg = ID_UCI_RSA512;
- break;
- case 1024:
- alg = ID_UCI_RSA1024;
- break;
- case 2048:
- alg = ID_UCI_RSA2048;
- break;
- case 3072:
- alg = ID_UCI_RSA3072;
- break;
- default:
- TZ_ERROR("key->info.objectSize = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_BAD_PARAMETERS;
- }
-
- //PrintBYTE("N",module,moduleLen);
- //PrintBYTE("E",pub,pubLen);
- op->crypto = uci_context_alloc(alg, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_BAD_PARAMETERS;
- }
-
- if (uci_ae_set_keypair(op->crypto, &ucikey, &uciparam) != UCI_SUCCESS) {
- TZ_ERROR("uci_ae_set_keypair error line = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_BAD_PARAMETERS;
- }
-
- break;
- case TEE_TYPE_DSA_PUBLIC_KEY:
- case TEE_TYPE_DSA_KEYPAIR:
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DSA_PUBLIC_VALUE, pub,
- &pubLen);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
-
- if (key->info.objectType == TEE_TYPE_DSA_KEYPAIR) {
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DSA_PRIVATE_VALUE, priv,
- &privLen);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n",
- __LINE__, __func__);
- return rc;
- }
- ucikey.ucik_dsa_privkey = priv;
- ucikey.ucik_dsa_privk_len = privLen;
- }
- ucikey.ucik_dsa_pubkey = pub;
- ucikey.ucik_dsa_pubk_len = pubLen;
-
- uciparam.ucip_dsa_tsize = 0;
- uciparam.ucip_dsa_p = (unsigned char*)OsaMalloc(key->info.objectSize);
- uciparam.ucip_dsa_q = (unsigned char*)OsaMalloc(key->info.objectSize);
- uciparam.ucip_dsa_g = (unsigned char*)OsaMalloc(key->info.objectSize);
- uciparam.ucip_dsa_p_len = key->info.objectSize;
- uciparam.ucip_dsa_g_len = key->info.objectSize;
- uciparam.ucip_dsa_q_len = key->info.objectSize;
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DSA_PRIME,
- uciparam.ucip_dsa_p, &obj_size);
- if (rc != TEE_SUCCESS) {
- OsaFree(uciparam.ucip_dsa_p);
- OsaFree(uciparam.ucip_dsa_q);
- OsaFree(uciparam.ucip_dsa_g);
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DSA_BASE,
- uciparam.ucip_dsa_g, &obj_size);
- if (rc != TEE_SUCCESS) {
- OsaFree(uciparam.ucip_dsa_p);
- OsaFree(uciparam.ucip_dsa_q);
- OsaFree(uciparam.ucip_dsa_g);
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DSA_SUBPRIME,
- uciparam.ucip_dsa_q, &obj_size);
- if (rc != TEE_SUCCESS) {
- OsaFree(uciparam.ucip_dsa_p);
- OsaFree(uciparam.ucip_dsa_q);
- OsaFree(uciparam.ucip_dsa_g);
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- if (uci_ae_set_keypair(op->crypto, &ucikey, &uciparam) != UCI_SUCCESS) {
- OsaFree(uciparam.ucip_dsa_p);
- OsaFree(uciparam.ucip_dsa_q);
- OsaFree(uciparam.ucip_dsa_g);
- TZ_ERROR("uci_ae_set_keypair error line = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_BAD_PARAMETERS;
- }
-
- OsaFree(uciparam.ucip_dsa_p);
- OsaFree(uciparam.ucip_dsa_q);
- OsaFree(uciparam.ucip_dsa_g);
- break;
- case TEE_TYPE_DH_KEYPAIR:
- uciparam.ucip_dh_prime = (unsigned char*)OsaMalloc(key->info.objectSize);
- uciparam.ucip_dh_generator = (unsigned char*)OsaMalloc(
- key->info.objectSize);
- uciparam.ucip_dh_len = key->info.objectSize;
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DH_PRIME,
- uciparam.ucip_dh_prime, &obj_size);
- if (rc != TEE_SUCCESS) {
- OsaFree(uciparam.ucip_dh_prime);
- OsaFree(uciparam.ucip_dh_generator);
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- rc = TEE_GetObjectBufferAttribute(key, TEE_ATTR_DH_BASE,
- uciparam.ucip_dh_generator, &obj_size);
- if (rc != TEE_SUCCESS) {
- OsaFree(uciparam.ucip_dh_prime);
- OsaFree(uciparam.ucip_dh_generator);
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return rc;
- }
- if (uci_ae_set_keypair(op->crypto, &ucikey, &uciparam) != UCI_SUCCESS) {
- OsaFree(uciparam.ucip_dh_prime);
- OsaFree(uciparam.ucip_dh_generator);
- TZ_ERROR("uci_ae_set_keypair error line = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_BAD_PARAMETERS;
- }
- OsaFree(uciparam.ucip_dh_prime);
- OsaFree(uciparam.ucip_dh_generator);
- }
- if ((key->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY
- && op->key1->info.objectType == TEE_TYPE_RSA_KEYPAIR)
- || (key->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY
- && op->key1->info.objectType == TEE_TYPE_DSA_KEYPAIR)) {
-
- op->key1->info.objectType = key->info.objectType; // change object object type of key1 in DSA or RSA case
- }
- TEE_CopyObjectAttributes(op->key1, key); // will Panic inside in the case of incompatible objects
- operation->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_SetOperationKey2(TEE_OperationHandle operation,
- TEE_ObjectHandle key1, TEE_ObjectHandle key2) {
-
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
- if ((key1 && !key2) || (!key1 && key2)) {
- TZ_ERROR("key error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (operation->info.algorithm != TEE_ALG_AES_XTS) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!key1 && !key2) {
- TEE_CloseObject(op->key1);
- op->key1 = TEE_HANDLE_NULL;
- TEE_CloseObject(op->key2);
- op->key2 = TEE_HANDLE_NULL;
- return TEE_SUCCESS;
- }
- // check key usage flags
- if (key1 && (key1->info.objectUsage | ~op->info.requiredKeyUsage) != 0xffffffff) {
- TZ_ERROR("Usage don't match line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (key2 && (key2->info.objectUsage | ~op->info.requiredKeyUsage) != 0xffffffff) {
- TZ_ERROR("Usage don't match line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if(key1 != NULL) {
- TEE_CopyObjectAttributes(op->key1, key1);
- }
- if(key2 != NULL) {
- TEE_CopyObjectAttributes(op->key2, key2);
- }
- operation->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
- return TEE_SUCCESS;
-}
-
-void TEE_CopyOperation(TEE_OperationHandle dstOperation,
- TEE_OperationHandle srcOperation) {
-
- struct TEE_Operation * dstOp = (struct TEE_Operation*)dstOperation;
- struct TEE_Operation * srcOp = (struct TEE_Operation*)srcOperation;
-
- if (dstOperation->info.mode != srcOperation->info.mode
- || dstOperation->info.algorithm != srcOperation->info.algorithm) {
- TZ_ERROR("Operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (dstOperation->info.maxKeySize < srcOperation->info.maxKeySize) {
- TZ_ERROR("Operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- dstOperation->info.algorithm = srcOperation->info.algorithm;
- dstOperation->info.digestLength = srcOperation->info.digestLength;
- dstOperation->info.handleState = srcOperation->info.handleState;
- dstOperation->info.keySize = srcOperation->info.keySize;
- dstOperation->info.maxKeySize = srcOperation->info.maxKeySize;
- dstOperation->info.mode = srcOperation->info.mode;
- dstOperation->info.operationClass = srcOperation->info.operationClass;
- dstOperation->info.requiredKeyUsage = srcOperation->info.requiredKeyUsage;
-
- if (dstOp->key1) {
- TEE_CopyObjectAttributes(dstOp->key1, srcOp->key1);
- }
- if (dstOp->key2) {
- TEE_CopyObjectAttributes(dstOp->key2, srcOp->key2);
- }
- if (uci_dup_handle(srcOp->crypto, dstOp->crypto) != UCI_SUCCESS) {
- TZ_ERROR("uci_dup_handle error , line = %d, %s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-}
-
-// Message Digest Functions
-void TEE_DigestUpdate(TEE_OperationHandle operation, const void* chunk,
- size_t chunkSize) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_DIGEST) {
- TZ_ERROR("param error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_md_update(op->crypto, (unsigned char*)chunk, chunkSize) != UCI_SUCCESS) {
- TZ_ERROR("uci_md_update error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-}
-
-TEE_Result TEE_DigestDoFinal(TEE_OperationHandle operation, const void* chunk,
- size_t chunkLen, void* hash, size_t *hashLen) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (!hash || !hashLen) {
- return TEE_ERROR_SHORT_BUFFER;
- }
- if (operation->info.operationClass != TEE_OPERATION_DIGEST) {
- TZ_ERROR("param error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (chunk
- != NULL&& uci_md_update(op->crypto, (unsigned char*)chunk, chunkLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_md_update error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_md_final(op->crypto, (unsigned char*)hash) != UCI_SUCCESS) {
- TZ_ERROR("uci_md_final error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- *hashLen = op->info.digestLength;
- return TEE_SUCCESS;
-}
-
-// Symmetric Cipher Functions
-void TEE_CipherInit(TEE_OperationHandle operation, const void* IV, size_t IVLen) {
- int ret;
- unsigned int mode;
- unsigned char key1[32] = {0x0, };
- //unsigned char key2[32] = {0x0, };
- size_t key_len1 = sizeof(key1);
- //unsigned int key_len2 = sizeof(key2);
- size_t uci_alg;
- TEE_Result rc;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_CIPHER) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (op->key1) {
- rc = TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_SECRET_VALUE, key1,
- &key_len1);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- }
- switch (op->info.algorithm) {
- case TEE_ALG_AES_ECB_NOPAD:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_ECB;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_ECB;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- switch (key_len1) {
- case 16:
- uci_alg = ID_UCI_AES128;
- break;
- case 24:
- uci_alg = ID_UCI_AES192;
- break;
- case 32:
- uci_alg = ID_UCI_AES256;
- break;
- default:
- TZ_ERROR("key len error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(uci_alg, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
-
-
- // KRISHNA - ADDED NEW ALGO
- case TEE_ALG_AES_ECB_PKCS7:
- case TEE_ALG_AES_ECB_PKCS5:
- case TEE_ALG_AES_ECB_ISO9797_M1 :
- case TEE_ALG_AES_ECB_ISO9797_M2 :
-
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_ECB;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_ECB;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- switch (key_len1) {
- case 16:
- uci_alg = ID_UCI_AES128;
- break;
- case 24:
- uci_alg = ID_UCI_AES192;
- break;
- case 32:
- uci_alg = ID_UCI_AES256;
- break;
- default:
- TZ_ERROR("key len error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-
- op->crypto = uci_context_alloc(uci_alg, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
-
-
-
-
- case TEE_ALG_AES_CBC_NOPAD:
- case TEE_ALG_AES_CBC_PKCS5:
- case TEE_ALG_AES_CBC_PKCS7:
- case TEE_ALG_AES_CBC_ISO9797_M1:
- case TEE_ALG_AES_CBC_ISO9797_M2:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_CBC;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_CBC;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- switch (key_len1) {
- case 16:
- uci_alg = ID_UCI_AES128;
- break;
- case 24:
- uci_alg = ID_UCI_AES192;
- break;
- case 32:
- uci_alg = ID_UCI_AES256;
- break;
- default:
- TZ_ERROR("key len error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(uci_alg, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_ALG_AES_CTR:
- case TEE_ALG_AES_CTR_NOPAD:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_CTR;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_CTR;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- switch (key_len1) {
- case 16:
- uci_alg = ID_UCI_AES128;
- break;
- case 24:
- uci_alg = ID_UCI_AES192;
- break;
- case 32:
- uci_alg = ID_UCI_AES256;
- break;
- default:
- TZ_ERROR("key len error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(uci_alg, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_ALG_AES_CTS:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_CTS;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_CTS;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- switch (key_len1) {
- case 16:
- uci_alg = ID_UCI_AES128;
- break;
- case 24:
- uci_alg = ID_UCI_AES192;
- break;
- case 32:
- uci_alg = ID_UCI_AES256;
- break;
- default:
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(uci_alg, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_ZERO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_ALG_AES_XTS:
- TZ_ERROR("TEE_ALG_AES_XTS not support NOW!!");
- TEE_Panic(0);
- break;
- case TEE_ALG_DES_ECB_NOPAD:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_ECB;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_ECB;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(ID_UCI_DES, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_ALG_DES_CBC_NOPAD:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_CBC;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_CBC;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(ID_UCI_DES, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_ALG_DES3_ECB_NOPAD:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_ECB;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_ECB;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(ID_UCI_TDES, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_ALG_DES3_CBC_NOPAD:
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = ID_UCI_ENC_CBC;
- } else if (op->info.mode == TEE_MODE_DECRYPT) {
- mode = ID_UCI_DEC_CBC;
- } else {
- TZ_ERROR("Invalid mode error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op->crypto = uci_context_alloc(ID_UCI_TDES, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_se_init(op->crypto, mode, ID_UCI_NO_PADDING, key1, key_len1,
- (unsigned char *)IV);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- default:
- TZ_ERROR("algorithm error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
-}
-
-TEE_Result TEE_CipherUpdate(TEE_OperationHandle operation, const void* srcData,
- size_t srcLen, void* destData, size_t *destLen) {
- int ret;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_CIPHER) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (destData == NULL) {
- return TEE_ERROR_SHORT_BUFFER;
- }
- ret = uci_se_process(op->crypto, (unsigned char *)srcData, srcLen,
- (unsigned char*)destData, (unsigned int*)destLen);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_process error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- ;
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_CipherDoFinal(TEE_OperationHandle operation, const void* srcData,
- size_t srcLen, void* destData, size_t *destLen) {
- int ret;
- size_t blocksize = 8;
- int tmp = 0;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_CIPHER) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (destData == NULL) {
- return TEE_ERROR_SHORT_BUFFER;
- }
- *destLen = 0;
- if (op->info.algorithm == TEE_ALG_AES_CTS) {
-
- ret = uci_se_final(op->crypto, (unsigned char *)srcData, srcLen,
- (unsigned char*)destData, (unsigned int*)destLen);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_final error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- ;
- }
- return TEE_SUCCESS;
- }
- if (op->info.algorithm == TEE_ALG_AES_ECB_NOPAD
- || op->info.algorithm == TEE_ALG_AES_CBC_NOPAD
- || op->info.algorithm == TEE_ALG_AES_CTR
- || op->info.algorithm == TEE_ALG_AES_XTS
- ) {
-
- blocksize = 16;
- }
- // printf("srcLen is %d, blocksize is %d\n",srcLen, blocksize);
- if (srcLen > blocksize) {
- ret = uci_se_process(op->crypto, (unsigned char *)srcData,
- srcLen - blocksize, (unsigned char*)destData, (unsigned int*)&tmp);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_final error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-
- *destLen = tmp;
- ret = uci_se_final(op->crypto, (unsigned char *)srcData + tmp, blocksize,
- (unsigned char*)destData + tmp, (unsigned int*)&tmp);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_final error line = %d,%s,ret=%d\n", __LINE__, __func__, ret);
- TEE_Panic(0);
- ;
- }
- *destLen += tmp;
- } else {
-
- ret = uci_se_final(op->crypto, (unsigned char *)srcData, srcLen,
- (unsigned char*)destData, (unsigned int*)destLen);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_se_final error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- ;
- }
- }
- return TEE_SUCCESS;
-}
-
-// MAC Functions
-void TEE_MACInit(TEE_OperationHandle operation, const void* IV, size_t IVLen) {
- TEE_Result rc = TEE_SUCCESS;
- unsigned char key[128] = {0x0, };
- size_t key_len = sizeof(key);
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_MAC) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (op->key1) {
- rc = TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_SECRET_VALUE, key,
- &key_len);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- TEE_Panic(0);
- }
- }
- if (uci_mac_init(op->crypto, key, key_len) != UCI_SUCCESS) {
- TZ_ERROR("uci_mac_init error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
-}
-
-void TEE_MACUpdate(TEE_OperationHandle operation, const void* chunk,
- size_t chunkSize) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_MAC) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_mac_update(op->crypto, (unsigned char *)chunk,
- chunkSize) != UCI_SUCCESS) {
- TZ_ERROR("uci_mac_update error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-}
-
-TEE_Result TEE_MACComputeFinal(TEE_OperationHandle operation,
- const void* message, size_t messageLen, void* mac, size_t *macLen) {
-
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_MAC) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_mac_update(op->crypto, (unsigned char *)message,
- messageLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_mac_update error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_mac_final(op->crypto, (unsigned char*)mac, macLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_mac_final error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_MACCompareFinal(TEE_OperationHandle operation,
- const void* message, size_t messageLen, const void* mac, size_t *macLen) {
- unsigned char tmpmac[128];
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_MAC) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_mac_update(op->crypto, (unsigned char*)message,
- messageLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_mac_update error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_mac_final(op->crypto, tmpmac, macLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_mac_final error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (memcmp(mac, tmpmac, *macLen) != 0) {
- return TEE_ERROR_MAC_INVALID;
- }
- return TEE_SUCCESS;
-}
-
-// Authenticated Encryption Functions
-
-TEE_Result TEE_AEInit(TEE_OperationHandle operation, const void* nonce,
- size_t nonceLen, uint32_t tagLen, uint32_t AADLen, uint32_t payloadLen) {
-
- TEE_Result rc = TEE_SUCCESS;
- unsigned char key[128];
- size_t key_len = sizeof(key);
- int ret;
- int mode;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_AE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (op->key1) {
- rc = TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_SECRET_VALUE, key,
- &key_len);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- TEE_Panic(0);
- }
- }
- if (op->info.mode == TEE_MODE_ENCRYPT) {
- mode = 1;
- } else {
- mode = 0;
- }
- if (operation->info.algorithm == TEE_ALG_AES_CCM) {
- if (tagLen != 128 && tagLen != 112 && tagLen != 96 && tagLen != 64
- && tagLen != 48 && tagLen != 32) {
- TZ_ERROR("tagLen error line = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_NOT_SUPPORTED;
- }
- op->crypto = uci_context_alloc(ID_UCI_AE_CCM, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
-
- ret = uci_authcrypt_init(op->crypto, mode, (unsigned char*)nonce, nonceLen,
- tagLen / 8, AADLen, payloadLen, key, key_len);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_authcrypt_init error line = %d,%s \n", __LINE__, __func__);
- TEE_Panic(0);
- }
- } else if (operation->info.algorithm == TEE_ALG_AES_GCM) {
- if (tagLen != 128 && tagLen != 120 && tagLen != 112 && tagLen != 104
- && tagLen != 96) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- return TEE_ERROR_NOT_SUPPORTED;
- }
- op->crypto = uci_context_alloc(ID_UCI_AE_GCM, UCI_SW);
- if (op->crypto == UCI_ERROR || op->crypto == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_authcrypt_init(op->crypto, mode, (unsigned char*)nonce, nonceLen,
- tagLen / 8, 0, 0, key, key_len);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_authcrypt_init error line = %d,%s \n", __LINE__, __func__);
- TEE_Panic(0);
- }
- }
- operation->info.digestLength = tagLen;
- operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
- return TEE_SUCCESS;
-}
-
-void TEE_AEUpdateAAD(TEE_OperationHandle operation, const void* AADdata,
- size_t AADdataLen) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_AE) {
- TZ_ERROR("operation error line = %d,%s \n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s \n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (operation->info.algorithm == TEE_ALG_AES_CCM
- || operation->info.algorithm == TEE_ALG_AES_GCM) {
- if (uci_authcrypt_update_aad(op->crypto, (unsigned char*)AADdata,
- AADdataLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_authcrypt_update_aad error line = %d,%s \n", __LINE__,
- __func__);
- TEE_Panic(0);
- }
- }
-}
-
-TEE_Result TEE_AEUpdate(TEE_OperationHandle operation, const void* srcData,
- size_t srcLen, void* destData, size_t *destLen) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_AE) {
- TZ_ERROR("operation error line = %d,%s \n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s \n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (*destLen < srcLen) {
- return TEE_ERROR_SHORT_BUFFER;
- }
- if (operation->info.algorithm == TEE_ALG_AES_CCM
- || operation->info.algorithm == TEE_ALG_AES_GCM) {
- if (uci_authcrypt_update(op->crypto, (unsigned char*)srcData, srcLen,
- (unsigned char*)destData, destLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_authcrypt_update_aad error line = %d,%s \n", __LINE__,
- __func__);
- TEE_Panic(0);
- }
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_AEEncryptFinal(TEE_OperationHandle operation,
- const void* srcData, size_t srcLen, void* destData, size_t* destLen,
- void* tag, size_t* tagLen) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_AE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (*destLen < srcLen) {
- return TEE_ERROR_SHORT_BUFFER;
- }
- if (uci_authcrypt_encryptfinal(op->crypto, (unsigned char*)srcData, srcLen,
- (unsigned char*)destData, destLen, (unsigned char*)tag,
- tagLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_authcrypt_encryptfinal error line = %d,%s \n", __LINE__,
- __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_AEDecryptFinal(TEE_OperationHandle operation,
- const void* srcData, size_t srcLen, void* destData, size_t *destLen,
- void* tag, size_t tagLen) {
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_AE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (*destLen < srcLen) {
- TZ_ERROR("destLen error line = %d,%s \n", __LINE__, __func__);
- return TEE_ERROR_SHORT_BUFFER;
- }
- if (uci_authcrypt_decryptfinal(op->crypto, (unsigned char*)srcData, srcLen,
- (unsigned char*)destData, destLen, (unsigned char*)tag,
- tagLen) != UCI_SUCCESS) {
- TZ_ERROR("uci_authcrypt_decryptfinal error line = %d,%s \n", __LINE__,
- __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_AsymmetricEncrypt(TEE_OperationHandle operation,
- const TEE_Attribute* params, uint32_t paramCount, const void* srcData,
- size_t srcLen, void* destData, size_t *destLen) {
- int ret;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_ASYMMETRIC_CIPHER) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_ae_encrypt(op->crypto, (unsigned char *)srcData, srcLen,
- (unsigned char*)destData, destLen);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_ae_encrypt error. ret= %d,line = %d,%s\n", ret, __LINE__,
- __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_AsymmetricDecrypt(TEE_OperationHandle operation,
- const TEE_Attribute* params, uint32_t paramCount, const void* srcData,
- size_t srcLen, void* destData, size_t *destLen) {
- int ret;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_ASYMMETRIC_CIPHER) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_ae_decrypt(op->crypto, (unsigned char *)srcData, srcLen,
- (unsigned char*)destData, destLen);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_ae_decrypt error. ret= %d,line = %d,%s\n", ret, __LINE__,
- __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_AsymmetricSignDigest(TEE_OperationHandle operation,
- const TEE_Attribute* params, uint32_t paramCount, const void* digest,
- size_t digestLen, void* signature, size_t *signatureLen) {
- int ret;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_ASYMMETRIC_SIGNATURE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_ds_sign(op->crypto, (unsigned char *)digest, digestLen,
- (unsigned char*)signature, signatureLen);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_ds_sign error. ret= %d,line = %d,%s\n", ret, __LINE__,
- __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_AsymmetricVerifyDigest(TEE_OperationHandle operation,
- const TEE_Attribute* params, uint32_t paramCount, const void* digest,
- size_t digestLen, void* signature, size_t signatureLen) {
- int ret = UCI_ERROR;
- int result = -1;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (operation->info.operationClass != TEE_OPERATION_ASYMMETRIC_SIGNATURE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- ret = uci_ds_verify(op->crypto, (unsigned char *)digest, digestLen,
- (unsigned char*)signature, signatureLen, &result);
- if (ret != UCI_SUCCESS) {
- TZ_ERROR("uci_ds_verify error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (result != UCI_VALID_SIGN) {
- TZ_ERROR("uci_ds_verify error. ret= %d,line = %d,%s\n", result, __LINE__,
- __func__);
- TEE_Panic(0);
- }
- return TEE_SUCCESS;
-}
-
-void TEE_DeriveKey(TEE_OperationHandle operation, const TEE_Attribute* params,
- uint32_t paramCount, TEE_ObjectHandle derivedKey) {
- uint32_t i = 0;
- unsigned char authkey[512];
- unsigned char privkey[512];
- unsigned char *pubkey = NULL;
- size_t pubkey_len = 0;
- size_t privkey_len = sizeof(privkey);
- TEE_Attribute attrs[1];
- TEE_Result rc;
- struct TEE_Operation * op = (struct TEE_Operation*)operation;
-
- if (op->info.operationClass != TEE_OPERATION_KEY_DERIVATION) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!params) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (op->info.mode != TEE_MODE_DERIVE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- for (i = 0; i < paramCount; i++) {
- if (params[i].attributeID == TEE_ATTR_DH_PUBLIC_VALUE) {
- pubkey = (unsigned char*)params[i].content.ref.buffer;
- pubkey_len = params[i].content.ref.length / 8;
- break;
- }
- }
- rc = TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_DH_PRIVATE_VALUE,
- privkey, &privkey_len);
- if (rc != TEE_SUCCESS) {
- TZ_ERROR("TEE_GetObjectBufferAttribute error line = %d,%s\n", __LINE__,
- __func__);
- return;
- }
- if (pubkey_len == 0 || !pubkey || privkey_len == 0) {
- TZ_ERROR("params error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if ((i = uci_dh_gen_authkey(op->crypto, privkey, pubkey, authkey))
- != UCI_SUCCESS) {
- TZ_ERROR(" uci_dh_gen_authkey error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- PrintBYTE("privkey", privkey, privkey_len);
- PrintBYTE("pubkey", pubkey, privkey_len);
- TEE_InitRefAttribute(&attrs[0], TEE_ATTR_SECRET_VALUE, authkey, pubkey_len);
- TEE_PopulateTransientObject(derivedKey, attrs, 1);
-}
-
-void TEE_GenerateRandom(void* randomBuffer, size_t randomBufferLen) {
- int i = 0;
- unsigned char seed[16];
- //unsigned int seedLen = 16;
- unsigned int res;
- unsigned long get_time = getClock();
-
- srand(get_time);
-
- for (i = 0; i < 16; i++) {
- res = rand();
- seed[i] = res & 0xFF;
- }
- UCI_HANDLE oh = uci_context_alloc(ID_UCI_X931, UCI_SW);
- if (oh == UCI_ERROR || oh == UCI_MEM_ALLOR_ERROR) {
- TZ_ERROR("uci_context_alloc error line = %d, %s", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_prng_seed(oh, seed) != UCI_SUCCESS) {
- TZ_ERROR("uci_prng_seed line = %d, %s", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (uci_prng_get(oh, randomBufferLen,
- (unsigned char*)randomBuffer) != UCI_SUCCESS) {
- TZ_ERROR("uci_prng_get line = %d, %s", __LINE__, __func__);
- TEE_Panic(0);
- }
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssf_crypto.c
+ *
+ * Description: SSF crypto functions
+ *
+ * Version: 1.0
+ * Created: 23 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: krishna (Kr), k.devale@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <crypto_internal.h>
+#include <error.h>
+#include <log.h>
+#include <permission.h>
+
+#include "CC_API.h"
+
+// #include <config.h>
+
+#define TAG "TEE:Crypto"
+
+#define CRYPTO_PANIC do{LOGE(SSF_LIB, "This Line!");TEE_Panic(0);}while(0)
+
+#define MAX_ATTRIBUTE_NUMBER 35 // Maximum number of attributes for each object
+
+#if 0 //ndef NDEBUG
+#define CRYPTO_INTERNAL_LOG(_f, _a...) printf("[%s]%d: " _f "\n", __func__ , __LINE__ , ## _a)
+#define CRYPTO_INTERNAL_LOG_BYTE(msg, Data, DataLen) { \
+ int idx; \
+ printf("%10s =", msg); \
+ printf("\n"); \
+ for( idx=0; idx<(int)DataLen; idx++) { \
+ if( (idx!=0) && ((idx%16)==0) ) printf("\n"); \
+ if((idx % 16) == 0) printf("\t\""); \
+ printf("%.2X", Data[idx]); \
+ if( (idx!=0) && ((idx%16)==15) ) printf("\""); \
+ } \
+ printf("\n"); \
+}
+#else
+#define CRYPTO_INTERNAL_LOG(_f, _a...)
+#define CRYPTO_INTERNAL_LOG_BYTE(msg, Data, DataLen)
+#endif
+
+struct __TEE_Attributees
+{
+ int attr_number;
+ TEE_Attribute attr_array[MAX_ATTRIBUTE_NUMBER];
+};
+
+struct TransientObject
+{
+ TEE_ObjectInfo info;
+ struct __TEE_Attributees attr;
+};
+
+struct __TEE_ObjectHandle
+{
+ struct TransientObject tr;
+ int drv_hndl;
+};
+
+struct __TEE_OperationHandle
+{
+ TEE_OperationInfo info;
+};
+
+//static int crypto_engine_type = CRYPTO_USE_SW_ENGINE;
+
+static int sw_crypto_ioctl_init(crypto_internal_operation *operation, crypto_internal_keystruct *key, unsigned char *ivec, unsigned int ivec_len)
+{
+ (void)ivec_len; /* actually always==16 */
+ int rc=0;
+ int mode;
+ unsigned int padding=ID_NO_PADDING;
+ CryptoCoreContainer *handle=(CryptoCoreContainer *)operation->crypto;
+
+ switch(operation->info.algorithm)
+ {
+ /* TEE_OPERATION_CIPHER */
+ case TEE_ALG_AES_ECB_NOPAD:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_ECB;
+ else mode=ID_DEC_ECB;
+ padding = ID_NO_PADDING;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_ECB_PKCS5:
+ case TEE_ALG_AES_ECB_PKCS7:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_ECB;
+ else mode=ID_DEC_ECB;
+ padding = ID_NO_PADDING /* ID_PKCS5 */;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_ECB_ISO9797_M1:
+ case TEE_ALG_AES_ECB_ISO9797_M2:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_ECB;
+ else mode=ID_DEC_ECB;
+ padding = ID_NO_PADDING /* ID_PKCS5 */;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_CBC_NOPAD:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_CBC;
+ else mode=ID_DEC_CBC;
+ padding = ID_NO_PADDING;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_CBC_PKCS5:
+ case TEE_ALG_AES_CBC_PKCS7:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_CBC;
+ else mode=ID_DEC_CBC;
+ padding = ID_NO_PADDING/* ID_PKCS5 */;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_CBC_ISO9797_M1:
+ case TEE_ALG_AES_CBC_ISO9797_M2:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_CBC;
+ else mode=ID_DEC_CBC;
+ padding = ID_NO_PADDING /* ID_PKCS5 */;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_CTR:
+ case TEE_ALG_AES_CTR_NOPAD:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) mode=ID_ENC_CTR;
+ else mode=ID_DEC_CTR;
+ padding = ID_NO_PADDING;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_AES_CTS:
+ case TEE_ALG_AES_XTS:
+ break;
+
+ case TEE_ALG_DES_ECB_NOPAD:
+ case TEE_ALG_DES3_ECB_NOPAD:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) {
+ mode=ID_ENC_ECB;
+ }
+ else {
+ mode=ID_DEC_ECB;
+ }
+ padding = ID_NO_PADDING;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_DES_CBC_NOPAD:
+ case TEE_ALG_DES3_CBC_NOPAD:
+ if(operation->info.mode == TEE_MODE_ENCRYPT) {
+ mode=ID_ENC_CBC;
+ }
+ else {
+ mode=ID_DEC_CBC;
+ }
+ padding = ID_NO_PADDING;
+ rc=handle->SE_init(handle, mode, padding, key->secret.buffer, key->secret.size, ivec);
+ break;
+
+ case TEE_ALG_HMAC_MD5:
+ case TEE_ALG_HMAC_SHA1:
+ case TEE_ALG_HMAC_SHA224:
+ case TEE_ALG_HMAC_SHA256:
+ case TEE_ALG_HMAC_SHA384:
+ case TEE_ALG_HMAC_SHA512:
+ case TEE_ALG_AES_CBC_MAC_NOPAD:
+ case TEE_ALG_AES_CBC_MAC_PKCS5:
+ case TEE_ALG_DES_CBC_MAC_NOPAD:
+ case TEE_ALG_DES_CBC_MAC_PKCS5:
+ case TEE_ALG_AES_CMAC:
+ case TEE_ALG_DES3_CBC_MAC_NOPAD:
+ case TEE_ALG_DES3_CBC_MAC_PKCS5:
+ rc=handle->MAC_init(handle, key->secret.buffer, key->secret.size);
+ break;
+
+ case TEE_ALG_AES_CCM:
+ case TEE_ALG_AES_GCM:
+ break;
+
+ case TEE_ALG_MD5:
+ case TEE_ALG_SHA1:
+ case TEE_ALG_SHA224:
+ case TEE_ALG_SHA256:
+ case TEE_ALG_SHA384:
+ case TEE_ALG_SHA512:
+ rc=handle->MD_init(handle);
+ break;
+
+ case TEE_ALG_RSA_NOPAD:
+ padding = ID_NO_PADDING;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSAES_PKCS1_V1_5:
+ padding = ID_RSAES_PKCS15;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
+ padding = ID_RSAES_OAEP_SHA1;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
+ padding = ID_RSAES_OAEP_SHA224;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
+ padding = ID_RSAES_OAEP_SHA256;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
+ padding = ID_RSAES_OAEP_SHA384;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
+ padding = ID_RSAES_OAEP_SHA512;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
+ padding = ID_RSASSA_PKCS15_MD5;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
+ padding = ID_RSASSA_PKCS15_SHA1;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
+ padding = ID_RSASSA_PKCS15_SHA224;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
+ padding = ID_RSASSA_PKCS15_SHA256;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
+ padding = ID_RSASSA_PKCS15_SHA384;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
+ padding = ID_RSASSA_PKCS15_SHA512;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
+ padding = ID_RSASSA_PSS_SHA1;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
+ padding = ID_RSASSA_PSS_SHA224;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
+ padding = ID_RSASSA_PSS_SHA256;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
+ padding = ID_RSASSA_PSS_SHA384;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
+ padding = ID_RSASSA_PSS_SHA512;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_DSA_SHA1:
+ padding = 0;
+ rc=handle->RSA_setKeypairForCRT(handle, padding,
+ key->rsa_modulus.buffer, key->rsa_modulus.size,
+ key->rsa_public.buffer, key->rsa_public.size,
+ key->rsa_private.buffer, key->rsa_private.size,
+ key->rsa_prime1.buffer, key->rsa_prime1.size,
+ key->rsa_prime2.buffer, key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, key->rsa_coefficient.size);
+ break;
+
+ case TEE_ALG_GENERATE_SECRET_KEY:
+ rc=handle->PRNG_get(handle, key->secret.size, key->secret.buffer);
+ /* Ignore return value to avoid CRYPTO_PANIC. Only SDRM_X931_ConditionalTest() can return TEE_ERROR.*/
+ rc = TEE_SUCCESS;
+ break;
+
+ case TEE_ALG_GENERATE_RSA_KEY:
+ {
+ unsigned char E[3] = {0x01, 0x00, 0x01};
+ unsigned int ELen = 3;
+
+ rc=handle->RSA_genKeypairWithEforCRT(handle, padding,
+ E, ELen,
+ key->rsa_modulus.buffer, &key->rsa_modulus.size,
+ key->rsa_private.buffer, &key->rsa_private.size,
+ key->rsa_prime1.buffer, &key->rsa_prime1.size,
+ key->rsa_prime2.buffer, &key->rsa_prime2.size,
+ key->rsa_exponent1.buffer, &key->rsa_exponent1.size,
+ key->rsa_exponent2.buffer, &key->rsa_exponent2.size,
+ key->rsa_coefficient.buffer, &key->rsa_coefficient.size);
+
+ /*if(rc == (-ETIMEDOUT))
+ {
+ LOGE(SSF_LIB, "Algorithm - %X : TIMEOUT \n", operation->info.algorithm);
+ rc = TEE_ERROR_TIMEOUT;
+ }*/
+
+ memcpy(key->rsa_public.buffer, E, ELen);
+ key->rsa_public.size = ELen;
+ }
+ break;
+
+ default:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X ", operation->info.algorithm);
+ break;
+ }
+
+ CRYPTO_INTERNAL_LOG("rc=%d ", rc);
+ return rc;
+}
+
+static int sw_crypto_ioctl_update (crypto_internal_operation *operation, unsigned char* src_addr, unsigned int src_size, unsigned char* dst_addr, unsigned int* dst_size)
+{
+ int rc;
+ CryptoCoreContainer *handle=(CryptoCoreContainer *)operation->crypto;
+
+ switch(operation->info.algorithm)
+ {
+ /* TEE_OPERATION_CIPHER */
+ case TEE_ALG_AES_ECB_NOPAD:
+ case TEE_ALG_AES_ECB_PKCS5:
+ case TEE_ALG_AES_ECB_PKCS7:
+ case TEE_ALG_AES_ECB_ISO9797_M1:
+ case TEE_ALG_AES_ECB_ISO9797_M2:
+ case TEE_ALG_AES_CBC_NOPAD:
+ case TEE_ALG_AES_CBC_PKCS5:
+ case TEE_ALG_AES_CBC_PKCS7:
+ case TEE_ALG_AES_CBC_ISO9797_M1:
+ case TEE_ALG_AES_CBC_ISO9797_M2:
+ case TEE_ALG_AES_CTR:
+ case TEE_ALG_AES_CTR_NOPAD:
+ case TEE_ALG_DES_ECB_NOPAD:
+ case TEE_ALG_DES3_ECB_NOPAD:
+ case TEE_ALG_DES_CBC_NOPAD:
+ case TEE_ALG_DES3_CBC_NOPAD:
+ rc=handle->SE_process(handle, src_addr, src_size, dst_addr, dst_size);
+ break;
+
+ case TEE_ALG_HMAC_MD5:
+ case TEE_ALG_HMAC_SHA1:
+ case TEE_ALG_HMAC_SHA224:
+ case TEE_ALG_HMAC_SHA256:
+ case TEE_ALG_HMAC_SHA384:
+ case TEE_ALG_HMAC_SHA512:
+ case TEE_ALG_AES_CBC_MAC_NOPAD:
+ case TEE_ALG_AES_CBC_MAC_PKCS5:
+ case TEE_ALG_DES_CBC_MAC_NOPAD:
+ case TEE_ALG_DES_CBC_MAC_PKCS5:
+ case TEE_ALG_AES_CMAC:
+ case TEE_ALG_DES3_CBC_MAC_NOPAD:
+ case TEE_ALG_DES3_CBC_MAC_PKCS5:
+ rc=handle->MAC_update(handle, src_addr, src_size);
+ break;
+
+ case TEE_ALG_MD5:
+ case TEE_ALG_SHA1:
+ case TEE_ALG_SHA224:
+ case TEE_ALG_SHA256:
+ case TEE_ALG_SHA384:
+ case TEE_ALG_SHA512:
+ rc=handle->MD_update(handle, src_addr, src_size);
+ break;
+
+ default:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X", operation->info.algorithm);
+ rc=-1;
+ break;
+ }
+
+ if(src_size && dst_size) {CRYPTO_INTERNAL_LOG("rc=%d src_size=%d dst_size=%d", rc, src_size, *dst_size);}
+ else {CRYPTO_INTERNAL_LOG("rc=%d", rc);}
+ return rc;
+}
+
+static int sw_crypto_ioctl_final (crypto_internal_operation *operation, unsigned char* src_addr, unsigned int src_size, unsigned char* dst_addr, unsigned int* dst_size)
+{
+ int rc=-1;
+ int result=0;
+ CryptoCoreContainer *handle=(CryptoCoreContainer *)operation->crypto;
+
+ switch(operation->info.algorithm)
+ {
+ /* TEE_OPERATION_CIPHER */
+ case TEE_ALG_AES_ECB_NOPAD:
+ case TEE_ALG_AES_ECB_PKCS5:
+ case TEE_ALG_AES_ECB_PKCS7:
+ case TEE_ALG_AES_ECB_ISO9797_M1:
+ case TEE_ALG_AES_ECB_ISO9797_M2:
+ case TEE_ALG_AES_CBC_NOPAD:
+ case TEE_ALG_AES_CBC_PKCS5:
+ case TEE_ALG_AES_CBC_PKCS7:
+ case TEE_ALG_AES_CBC_ISO9797_M1:
+ case TEE_ALG_AES_CBC_ISO9797_M2:
+ case TEE_ALG_AES_CTR_NOPAD:
+ case TEE_ALG_AES_CTR:
+ rc=handle->SE_final(handle, src_addr, src_size, dst_addr, dst_size);
+ break;
+
+ case TEE_ALG_AES_CTS:
+ case TEE_ALG_AES_XTS:
+ break;
+
+ case TEE_ALG_DES_ECB_NOPAD:
+ case TEE_ALG_DES3_ECB_NOPAD:
+ case TEE_ALG_DES_CBC_NOPAD:
+ case TEE_ALG_DES3_CBC_NOPAD:
+ rc=handle->SE_final(handle, src_addr, src_size, dst_addr, dst_size);
+ break;
+
+ /* TEE_OPERATION_MAC */
+ case TEE_ALG_HMAC_MD5:
+ case TEE_ALG_HMAC_SHA1:
+ case TEE_ALG_HMAC_SHA224:
+ case TEE_ALG_HMAC_SHA256:
+ case TEE_ALG_HMAC_SHA384:
+ case TEE_ALG_HMAC_SHA512:
+ case TEE_ALG_AES_CBC_MAC_NOPAD:
+ case TEE_ALG_AES_CBC_MAC_PKCS5:
+ case TEE_ALG_DES_CBC_MAC_NOPAD:
+ case TEE_ALG_DES_CBC_MAC_PKCS5:
+ case TEE_ALG_AES_CMAC:
+ case TEE_ALG_DES3_CBC_MAC_NOPAD:
+ case TEE_ALG_DES3_CBC_MAC_PKCS5:
+ if(src_addr && src_size!=0) {
+ handle->MAC_update(handle, src_addr, src_size);
+ }
+ rc=handle->MAC_final(handle, dst_addr, dst_size);
+ break;
+
+ /* TEE_OPERATION_AE */
+ case TEE_ALG_AES_CCM:
+ case TEE_ALG_AES_GCM:
+ break;
+
+ /* TEE_OPERATION_DIGEST */
+ case TEE_ALG_MD5:
+ case TEE_ALG_SHA1:
+ case TEE_ALG_SHA224:
+ case TEE_ALG_SHA256:
+ case TEE_ALG_SHA384:
+ case TEE_ALG_SHA512:
+ if(src_addr && src_size!=0) {
+ handle->MD_update(handle, src_addr, src_size);
+ }
+ rc=handle->MD_final(handle, dst_addr);
+ *dst_size = operation->info.digestLength;
+ break;
+
+ /* TEE_OPERATION_ASYMMETRIC_CIPHER */
+ case TEE_ALG_RSA_NOPAD:
+ case TEE_ALG_RSAES_PKCS1_V1_5:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
+ if (operation->info.mode == TEE_MODE_ENCRYPT ) {
+ rc=handle->AE_encrypt(handle, src_addr, src_size, dst_addr, dst_size);
+ }
+ else{
+ rc=handle->AE_decrypt(handle, src_addr, src_size, dst_addr, dst_size);
+ }
+ break;
+
+ /* TEE_OPERATION_ASYMMETRIC_SIGNATURE */
+ case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
+ if (operation->info.mode == TEE_MODE_SIGN ) {
+ rc=handle->DS_sign(handle, src_addr, src_size, dst_addr, dst_size);
+ }
+ else {
+ rc=handle->DS_verify(handle, src_addr, src_size, dst_addr, *dst_size, &result);
+ if(result != rc) {
+ rc=result;
+ }
+ }
+ break;
+
+ case TEE_ALG_GENERATE_SECRET_KEY:
+ rc=0;
+ break;
+
+ case TEE_ALG_GENERATE_RSA_KEY:
+ rc=0;
+ break;
+
+ default:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X", operation->info.algorithm);
+ break;
+ }
+
+ if(src_size && dst_size) {CRYPTO_INTERNAL_LOG("rc=%d src_size=%d dst_size=%d", rc, src_size, *dst_size);}
+ else {CRYPTO_INTERNAL_LOG("rc=%d", rc);}
+ return rc;
+}
+
+static int sw_crypto_open(crypto_internal_operation *operation)
+{
+ unsigned int alg;
+
+ switch(operation->info.algorithm)
+ {
+ /* TEE_OPERATION_CIPHER */
+ case TEE_ALG_AES_ECB_NOPAD:
+ case TEE_ALG_AES_CBC_NOPAD:
+ case TEE_ALG_AES_CTR:
+ case TEE_ALG_AES_CTR_NOPAD:
+ case TEE_ALG_AES_ECB_PKCS5:
+ case TEE_ALG_AES_ECB_PKCS7:
+ case TEE_ALG_AES_ECB_ISO9797_M1:
+ case TEE_ALG_AES_ECB_ISO9797_M2:
+ case TEE_ALG_AES_CBC_PKCS5:
+ case TEE_ALG_AES_CBC_PKCS7:
+ case TEE_ALG_AES_CBC_ISO9797_M1:
+ case TEE_ALG_AES_CBC_ISO9797_M2:
+ if (operation->info.keySize== 128) {
+ alg=ID_AES128;
+ }
+ else if (operation->info.keySize== 192) {
+ alg=ID_AES192;
+ }
+ else if (operation->info.keySize== 256) {
+ alg=ID_AES256;
+ }
+ else {
+ goto error;
+ }
+ break;
+ case TEE_ALG_AES_XTS:
+ case TEE_ALG_AES_CTS:
+ goto error;
+ break;
+ case TEE_ALG_DES_ECB_NOPAD:
+ case TEE_ALG_DES_CBC_NOPAD:
+ alg=ID_DES;
+ break;
+ case TEE_ALG_DES3_ECB_NOPAD:
+ case TEE_ALG_DES3_CBC_NOPAD:
+ alg=ID_TDES;
+ break;
+
+ /* TEE_OPERATION_MAC */
+ case TEE_ALG_AES_CBC_MAC_NOPAD:
+ case TEE_ALG_AES_CBC_MAC_PKCS5:
+ case TEE_ALG_AES_CMAC:
+ case TEE_ALG_DES_CBC_MAC_NOPAD:
+ case TEE_ALG_DES_CBC_MAC_PKCS5:
+ case TEE_ALG_DES3_CBC_MAC_NOPAD:
+ case TEE_ALG_DES3_CBC_MAC_PKCS5:
+ goto error;
+ break;
+ case TEE_ALG_HMAC_MD5:
+ alg = ID_HMD5;
+ break;
+ case TEE_ALG_HMAC_SHA1:
+ alg = ID_HSHA1;
+ break;
+ case TEE_ALG_HMAC_SHA224:
+ alg = ID_HSHA224;
+ break;
+ case TEE_ALG_HMAC_SHA256:
+ alg = ID_HSHA256;
+ break;
+ case TEE_ALG_HMAC_SHA384:
+ alg = ID_HSHA384;
+ break;
+ case TEE_ALG_HMAC_SHA512:
+ alg = ID_HSHA512;
+ break;
+
+ /* TEE_OPERATION_AE */
+ case TEE_ALG_AES_CCM:
+ case TEE_ALG_AES_GCM:
+ goto error;
+ break;
+
+ /* TEE_OPERATION_DIGEST */
+ case TEE_ALG_MD5:
+ alg = ID_MD5;
+ break;
+ case TEE_ALG_SHA1:
+ alg = ID_SHA1;
+ break;
+ case TEE_ALG_SHA224:
+ alg = ID_SHA224;
+ break;
+ case TEE_ALG_SHA256:
+ alg = ID_SHA256;
+ break;
+ case TEE_ALG_SHA384:
+ alg = ID_SHA384;
+ break;
+ case TEE_ALG_SHA512:
+ alg = ID_SHA512;
+ break;
+
+ /* TEE_OPERATION_ASYMMETRIC_CIPHER */
+ case TEE_ALG_RSA_NOPAD:
+ case TEE_ALG_RSAES_PKCS1_V1_5:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
+ if (operation->info.keySize== 1024) {
+ alg=ID_RSA1024;
+ }
+ else if (operation->info.keySize== 2048) {
+ alg=ID_RSA2048;
+ }
+ else if (operation->info.keySize== 3072) {
+ alg=ID_RSA3072;
+ }
+ else {
+ goto error;
+ }
+ break;
+
+ /* TEE_OPERATION_ASYMMETRIC_SIGNATURE */
+ case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
+ if (operation->info.keySize== 1024) {
+ alg=ID_RSA1024;
+ }
+ else if (operation->info.keySize== 2048) {
+ alg=ID_RSA2048;
+ }
+ else if (operation->info.keySize== 3072) {
+ alg=ID_RSA3072;
+ }
+ else {
+ goto error;
+ }
+ break;
+
+ case TEE_ALG_DSA_SHA1:
+ goto error;
+ break;
+
+ case TEE_ALG_ECDSA_P160:
+ case TEE_ALG_ECDSA_P192:
+ case TEE_ALG_ECDSA_P224:
+ case TEE_ALG_ECDSA_P256:
+ case TEE_ALG_ECDSA_P384:
+ case TEE_ALG_ECDSA_P521:
+ goto error;
+ break;
+
+ /* TEE_OPERATION_KEY_DERIVATION */
+ case TEE_ALG_DH_DERIVE_SHARED_SECRET:
+ goto error;
+ break;
+
+ case TEE_ALG_ECDH_P192:
+ case TEE_ALG_ECDH_P224:
+ case TEE_ALG_ECDH_P256:
+ case TEE_ALG_ECDH_P384:
+ case TEE_ALG_ECDH_P521:
+ goto error;
+ break;
+
+ case TEE_ALG_GENERATE_SECRET_KEY:
+ alg=ID_X931;
+ break;
+
+ case TEE_ALG_GENERATE_RSA_KEY:
+ if (operation->info.keySize== 1024) {
+ alg=ID_RSA1024;
+ }
+ else if (operation->info.keySize== 2048) {
+ alg=ID_RSA2048;
+ }
+ else if (operation->info.keySize== 3072) {
+ alg=ID_RSA3072;
+ }
+ else {
+ goto error;
+ }
+ break;
+
+ default:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X ", operation->info.algorithm);
+ goto error;
+ break;
+ }
+
+ operation->crypto=(int)create_CryptoCoreContainer(alg);
+
+ if(operation->crypto==0) {
+ goto error;
+ }
+ return 0;
+
+error:
+ return -1;
+}
+
+static int sw_crypto_close(crypto_internal_operation *operation)
+{
+ int rc = 0;
+ if(operation->crypto) {
+ destroy_CryptoCoreContainer((CryptoCoreContainer*)operation->crypto);
+ }
+ operation->crypto = -1;
+ return rc;
+}
+
+#if 0
+static int hw_crypto_ioctl_init(crypto_internal_operation *operation, crypto_internal_keystruct *key, unsigned char *ivec, unsigned int ivec_len)
+{
+ int rc;
+ unsigned int mode = 0;
+ struct crypt_info info;
+ memset(&info, 0, sizeof(info));
+
+ switch(operation->info.algorithm)
+ {
+ /* TEE_OPERATION_CIPHER */
+ case TEE_ALG_AES_ECB_NOPAD:
+ case TEE_ALG_AES_ECB_PKCS5:
+ case TEE_ALG_AES_ECB_PKCS7:
+ case TEE_ALG_AES_ECB_ISO9797_M1:
+ case TEE_ALG_AES_ECB_ISO9797_M2:
+ mode=MI_AES_ECB;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_AES_CBC_NOPAD:
+ case TEE_ALG_AES_CBC_PKCS5:
+ case TEE_ALG_AES_CBC_PKCS7:
+ case TEE_ALG_AES_CBC_ISO9797_M1:
+ case TEE_ALG_AES_CBC_ISO9797_M2:
+ mode=MI_AES_CBC;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_AES_CTR:
+ case TEE_ALG_AES_CTR_NOPAD:
+ mode=MI_AES_CTR;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_AES_CTS:
+ case TEE_ALG_AES_XTS:
+ break;
+
+ case TEE_ALG_DES_ECB_NOPAD:
+ mode=MI_DES_ECB;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_DES3_ECB_NOPAD:
+ mode=MI_TDES_ECB;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_DES_CBC_NOPAD:
+ mode=MI_DES_CBC;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_DES3_CBC_NOPAD:
+ mode=MI_TDES_CBC;
+ if (operation->info.mode == TEE_MODE_DECRYPT) {
+ mode |= _MODE_DEC_;
+ }
+ break;
+
+ case TEE_ALG_MD5:
+ mode=MI_MD5;
+ break;
+
+ case TEE_ALG_SHA1:
+ mode=MI_SHA1;
+ break;
+
+ case TEE_ALG_SHA224:
+ mode=MI_SHA224;
+ break;
+
+ case TEE_ALG_SHA256:
+ mode=MI_HMAC_SHA256;
+ break;
+
+ case TEE_ALG_SHA384:
+ mode=MI_SHA384;
+ break;
+
+ case TEE_ALG_SHA512:
+ mode=MI_SHA512;
+ break;
+
+ case TEE_ALG_RSA_NOPAD:
+ case TEE_ALG_RSAES_PKCS1_V1_5:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
+ case TEE_ALG_DSA_SHA1:
+ case TEE_ALG_GENERATE_SECRET_KEY:
+ case TEE_ALG_GENERATE_RSA_KEY:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X ", operation->info.algorithm);
+ break;
+
+ default:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X ", operation->info.algorithm);
+ break;
+ }
+
+ if(mode==0)
+ {
+ rc = -1;
+ }
+ else
+ {
+ /* Set Key Type */
+ info.keytype = KEYID_USER_KEY;
+ info.mode = mode;
+ /* Set Key */
+ if(key->secret.buffer && key->secret.size !=0 && key->secret.size < MAX_KEY_LEN) {
+ info.keylen = key->secret.size;
+ memcpy(info.key, key->secret.buffer, key->secret.size);
+ }
+ /* Set IV */
+ if(ivec && ivec_len !=0 && ivec_len < MAX_IV_LEN) {
+ info.ivlen = ivec_len;
+ memcpy(info.iv, ivec, ivec_len);
+ }
+ rc= ioctl(operation->crypto, IOCTL_CRYPTO_INIT, (unsigned long)&info);
+ }
+
+ CRYPTO_INTERNAL_LOG("rc=%d ", rc);
+ return rc;
+}
+
+static int hw_crypto_ioctl_update(crypto_internal_operation *operation, unsigned char* src_addr, unsigned int src_size, unsigned char* dst_addr, unsigned int* dst_size)
+{
+ int ret;
+ struct crypt_oper oper;
+
+ oper.src_addr=src_addr;
+ oper.dst_addr=dst_addr;
+ oper.src_len=src_size;
+ oper.dst_len=dst_size;
+ oper.final=0;
+
+ ret = ioctl(operation->crypto, IOCTL_CRYPTO_CRYPT, (unsigned long)&oper);
+ return ret;
+}
+
+static int hw_crypto_ioctl_final(crypto_internal_operation *operation, unsigned char* src_addr, unsigned int src_size, unsigned char* dst_addr, unsigned int* dst_size)
+{
+ int ret;
+ struct crypt_oper oper;
+
+ oper.src_addr=src_addr;
+ oper.dst_addr=dst_addr;
+ oper.src_len=src_size;
+ oper.dst_len=dst_size;
+ oper.final=1;
+
+ ret = ioctl(operation->crypto, IOCTL_CRYPTO_CRYPT, (unsigned long)&oper);
+ return ret;
+}
+
+static int hw_crypto_open(crypto_internal_operation *operation)
+{
+ operation->crypto = open("/dev/crypto", 0, 0);
+ if(operation->crypto) {
+ return 0;
+ }
+ return -1;
+}
+
+static int hw_crypto_close(crypto_internal_operation *operation)
+{
+ close(operation->crypto);
+ operation->crypto=-1;
+ return 0;
+}
+
+static crypto_internal_engine crypto_internal_select_engine(uint32_t alg)
+{
+ return CRYPTO_SW_ENGINE;
+}
+
+void crypto_internal_set_engine(int set)
+{
+ crypto_engine_type=set;
+}
+#endif
+
+int crypto_internal_open(crypto_internal_operation *operation)
+{
+ int rc = -1;
+ /*crypto_internal_engine engine;
+
+ engine=crypto_internal_select_engine(operation->info.algorithm);
+ if (engine==CRYPTO_HW_ENGINE) {
+ rc=hw_crypto_open(operation);
+ }
+ else if (engine==CRYPTO_SW_ENGINE) {*/
+ rc=sw_crypto_open(operation);
+ //}
+ return rc;
+}
+
+int crypto_internal_close(crypto_internal_operation *operation)
+{
+ int rc = -1;
+ /*crypto_internal_engine engine;
+
+ engine=crypto_internal_select_engine(operation->info.algorithm);
+ if (engine==CRYPTO_HW_ENGINE) {
+ rc=hw_crypto_close(operation);
+ }
+ else if (engine==CRYPTO_SW_ENGINE) {*/
+ rc=sw_crypto_close(operation);
+ //}
+ return rc;
+}
+
+int crypto_internal_init(crypto_internal_operation *operation, crypto_internal_keystruct *key, unsigned char *ivec, size_t ivec_len)
+{
+ int rc = -1;
+ /*crypto_internal_engine engine;
+
+ engine=crypto_internal_select_engine(operation->info.algorithm);
+ if (engine==CRYPTO_HW_ENGINE) {
+ rc = hw_crypto_ioctl_init(operation, key, ivec, ivec_len);
+ }
+ else if (engine==CRYPTO_SW_ENGINE) {*/
+ rc=sw_crypto_ioctl_init(operation, key, ivec, ivec_len);
+ //}
+ return rc;
+}
+
+int crypto_internal_update(crypto_internal_operation *operation, unsigned char *src_data, size_t src_len, unsigned char *dst_data, size_t *dst_len)
+{
+ //crypto_internal_engine engine;
+ unsigned char* in_data=NULL;
+ unsigned char* out_data=NULL;
+ unsigned int in_size=0;
+ unsigned int out_size=0;
+ unsigned int num=0;
+ unsigned int processing_len=0;
+ unsigned int total_processing_len=0;
+ int (*crypto_update_engine)(crypto_internal_operation *, unsigned char *, unsigned int, unsigned char *, unsigned int*);
+
+ /*engine=crypto_internal_select_engine(operation->info.algorithm);
+ if (engine==CRYPTO_HW_ENGINE) {
+ crypto_update_engine=hw_crypto_ioctl_update;
+ }
+ else if (engine==CRYPTO_SW_ENGINE) {*/
+ crypto_update_engine=sw_crypto_ioctl_update;
+ //}
+ //else {
+ // goto error;
+ //}
+
+ if(src_data) {
+ in_data=(unsigned char*)src_data;
+ }
+ if(dst_data) {
+ out_data=(unsigned char*)dst_data;
+ }
+ if(src_len) {
+ in_size=(unsigned int)src_len;
+ }
+ if(dst_len) {
+ out_size=(unsigned int)*dst_len;
+ }
+
+ CRYPTO_INTERNAL_LOG("--------------------------------------------------------------");
+ CRYPTO_INTERNAL_LOG("in_size=%d out_size=%d op->data_len=%d, processed=%d", in_size, out_size, operation->data_len, total_processing_len);
+
+ if(operation->info.operationClass == TEE_OPERATION_CIPHER)
+ {
+ if (operation->data_len != 0)
+ {
+ if (in_size < (size_t)(operation->block_len - operation->data_len)) {
+ num = in_size;
+ }
+ else {
+ num = (size_t)(operation->block_len - operation->data_len);
+ }
+
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d out_size=%d processed=%d", num, in_size, out_size, total_processing_len);
+ if(num != 0) {
+ memcpy(operation->data + operation->data_len, in_data, num);
+
+ operation->data_len += num;
+ in_size -= num;
+ in_data = (unsigned char*)((unsigned long)in_data + num);
+
+ /* accumulated data is full */
+ if (operation->data_len == operation->block_len)
+ {
+ processing_len = out_size;
+ if (crypto_update_engine(operation, operation->data, operation->data_len, out_data, &processing_len)) {
+ goto error;
+ }
+ total_processing_len += processing_len;
+ out_size -= processing_len;
+ out_data = (unsigned char*)((unsigned long) out_data + processing_len);
+ operation->data_len = 0;
+ }
+ }
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d out_size=%d processed=%d", num, in_size, out_size, total_processing_len);
+ }
+
+ if (in_size != 0)
+ {
+ size_t should_be_processed_of_bytes = (size_t)in_size/operation->block_len*operation->block_len;
+ size_t remaining_number_of_bytes = in_size-should_be_processed_of_bytes;
+
+ CRYPTO_INTERNAL_LOG("should_be_processed_of_bytes=%d remaining_number_of_bytes=%d processed=%d", should_be_processed_of_bytes, remaining_number_of_bytes, total_processing_len);
+ if (should_be_processed_of_bytes != 0)
+ {
+ processing_len = out_size-total_processing_len;
+ if (crypto_update_engine(operation, in_data, should_be_processed_of_bytes, out_data, &processing_len)) {
+ goto error;
+ }
+ total_processing_len += processing_len;
+ in_size -= processing_len;
+ in_data = (unsigned char*)((unsigned long) in_data + processing_len);
+ }
+
+ if(remaining_number_of_bytes != 0) {
+ memcpy(operation->data, in_data, remaining_number_of_bytes);
+ operation->data_len = remaining_number_of_bytes;
+ }
+ }
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_MAC || operation->info.operationClass == TEE_OPERATION_DIGEST)
+ {
+ if (operation->data_len != 0)
+ {
+ if (in_size < (size_t)(operation->block_len - operation->data_len)) {
+ num = in_size;
+ }
+ else {
+ num = (size_t)(operation->block_len - operation->data_len);
+ }
+
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d processed=%d", num, in_size, total_processing_len);
+ if(num != 0) {
+ memcpy(operation->data + operation->data_len, in_data, num);
+
+ operation->data_len += num;
+ in_size -= num;
+ in_data = (unsigned char*)((unsigned long)in_data + num);
+
+ /* accumulated data is full */
+ if (operation->data_len == operation->block_len)
+ {
+ if (crypto_update_engine(operation, operation->data, operation->data_len, NULL, NULL)) {
+ goto error;
+ }
+ operation->data_len = 0;
+ }
+
+ total_processing_len += num;
+ }
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d processed=%d", num, in_size, total_processing_len);
+ }
+
+ if (in_size != 0)
+ {
+ size_t should_be_processed_of_bytes = (size_t)in_size/operation->block_len*operation->block_len;
+ size_t remaining_number_of_bytes = in_size-should_be_processed_of_bytes;
+
+ CRYPTO_INTERNAL_LOG("should_be_processed_of_bytes=%d remaining_number_of_bytes=%d processed=%d", should_be_processed_of_bytes, remaining_number_of_bytes, total_processing_len);
+ if (should_be_processed_of_bytes != 0)
+ {
+ if (crypto_update_engine(operation, in_data, should_be_processed_of_bytes, NULL, NULL)) {
+ goto error;
+ }
+ total_processing_len += should_be_processed_of_bytes;
+ in_size -= should_be_processed_of_bytes;
+ in_data = (unsigned char*)((unsigned long) in_data + should_be_processed_of_bytes);
+ }
+
+ if(remaining_number_of_bytes != 0) {
+ memcpy(operation->data, in_data, remaining_number_of_bytes);
+ total_processing_len += remaining_number_of_bytes;
+ operation->data_len = remaining_number_of_bytes;
+ in_size -= remaining_number_of_bytes;
+ }
+ }
+ }
+ else
+ {
+ if(crypto_update_engine(operation, in_data, in_size, out_data, &out_size)) {
+ goto error;
+ }
+ }
+
+ CRYPTO_INTERNAL_LOG("in_size=%d processed=%d", in_size, total_processing_len);
+ CRYPTO_INTERNAL_LOG("--------------------------------------------------------------");
+ if(operation->info.operationClass == TEE_OPERATION_CIPHER && dst_len) {
+ *dst_len = total_processing_len;
+ }
+ return 0;
+error:
+ return -1;
+}
+
+int crypto_internal_final(crypto_internal_operation *operation, unsigned char *src_data, size_t src_len, unsigned char *dst_data, size_t *dst_len)
+{
+ //crypto_internal_engine engine;
+ unsigned char* in_data=NULL;
+ unsigned char* out_data=NULL;
+ unsigned int in_size=0;
+ unsigned int out_size=0;
+ unsigned int num=0;
+ unsigned int processing_len=0;
+ unsigned int total_processing_len=0;
+ int (*crypto_update_engine)(crypto_internal_operation *, unsigned char *, unsigned int, unsigned char *, unsigned int*);
+ int (*crypto_final_engine)(crypto_internal_operation *, unsigned char *, unsigned int, unsigned char *, unsigned int*);
+
+ /*engine=crypto_internal_select_engine(operation->info.algorithm);
+ if (engine==CRYPTO_HW_ENGINE) {
+ crypto_update_engine=hw_crypto_ioctl_update;
+ crypto_final_engine=hw_crypto_ioctl_final;
+ }
+ else if (engine==CRYPTO_SW_ENGINE) {*/
+ crypto_update_engine=sw_crypto_ioctl_update;
+ crypto_final_engine=sw_crypto_ioctl_final;
+ /*}
+ else {
+ goto error;
+ }*/
+
+ if(src_data) {
+ in_data=(unsigned char*)src_data;
+ }
+ if(dst_data) {
+ out_data=(unsigned char*)dst_data;
+ }
+ if(src_len) {
+ in_size=(unsigned int)src_len;
+ }
+ if(dst_len) {
+ out_size=(unsigned int)*dst_len;
+ }
+
+ CRYPTO_INTERNAL_LOG("--------------------------------------------------------------");
+ CRYPTO_INTERNAL_LOG("in_size=%d out_size=%d op->data_len=%d processed=%d", in_size, out_size, operation->data_len, total_processing_len);
+
+ if(operation->info.operationClass == TEE_OPERATION_CIPHER)
+ {
+ if (operation->data_len != 0)
+ {
+ if (in_size < (size_t)(operation->block_len - operation->data_len)) {
+ num = in_size;
+ }
+ else {
+ num = (size_t)(operation->block_len - operation->data_len);
+ }
+
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d out_size=%d processed=%d", num, in_size, out_size, total_processing_len);
+ if(num != 0) {
+ memcpy(operation->data + operation->data_len, in_data, num);
+
+ operation->data_len += num;
+ in_size -= num;
+ in_data = (unsigned char*)((unsigned long)in_data + num);
+
+ /* accumulated data is full */
+ if (operation->data_len == operation->block_len)
+ {
+ processing_len = out_size;
+ if (crypto_update_engine(operation, operation->data, operation->data_len, out_data, &processing_len)) {
+ goto error;
+ }
+ total_processing_len += processing_len;
+ out_size -= processing_len;
+ out_data = (unsigned char*)((unsigned long) out_data + processing_len);
+ operation->data_len = 0;
+ }
+ }
+
+ if (in_size == 0 && operation->data_len != 0) {
+ in_size = operation->data_len;
+ in_data = operation->data;
+ operation->data_len = 0;
+ }
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d out_size=%d processed=%d", num, in_size, out_size, total_processing_len);
+ }
+
+ // process remaining data
+ {
+ size_t should_be_processed_of_bytes = (size_t)in_size/operation->block_len*operation->block_len;
+ size_t remaining_number_of_bytes = in_size-should_be_processed_of_bytes;
+
+ CRYPTO_INTERNAL_LOG("should_be_processed_of_bytes=%d remaining_number_of_bytes=%d processed=%d", should_be_processed_of_bytes, remaining_number_of_bytes, total_processing_len);
+ if (should_be_processed_of_bytes != 0)
+ {
+ processing_len = out_size-total_processing_len;
+ if (crypto_update_engine(operation, in_data, should_be_processed_of_bytes, out_data, &processing_len)) {
+ goto error;
+ }
+ total_processing_len += processing_len;
+ in_size -= processing_len;
+ in_data = (unsigned char*)((unsigned long) in_data + processing_len);
+ out_data = (unsigned char*)((unsigned long) out_data + processing_len);
+ }
+
+ if(operation->info.mode==TEE_MODE_ENCRYPT)
+ {
+ unsigned int pad_byte;
+ size_t should_be_processed_of_pad_bytes = 0;
+
+ /* NOPAD */
+ if (operation->info.algorithm==TEE_ALG_AES_ECB_NOPAD ||operation->info.algorithm==TEE_ALG_AES_CBC_NOPAD||
+ operation->info.algorithm==TEE_ALG_DES_ECB_NOPAD ||operation->info.algorithm==TEE_ALG_DES_CBC_NOPAD||
+ operation->info.algorithm==TEE_ALG_DES3_ECB_NOPAD || operation->info.algorithm==TEE_ALG_DES3_CBC_NOPAD)
+ {
+ CRYPTO_INTERNAL_LOG("ENC NOPAD : Ignore remaining_number_of_bytes=%d !!", remaining_number_of_bytes);
+ goto exit;
+ }
+
+ memcpy(operation->data, in_data, remaining_number_of_bytes);
+ operation->data_len += remaining_number_of_bytes;
+
+ if (dst_len && *dst_len < total_processing_len+operation->block_len) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+
+ pad_byte = operation->block_len - remaining_number_of_bytes;
+
+ if (operation->info.algorithm==TEE_ALG_AES_ECB_PKCS5 ||operation->info.algorithm==TEE_ALG_AES_ECB_PKCS7 ||
+ operation->info.algorithm==TEE_ALG_AES_CBC_PKCS5 ||operation->info.algorithm==TEE_ALG_AES_CBC_PKCS7)
+ {
+ should_be_processed_of_pad_bytes = operation->block_len;
+
+ memset(operation->data + operation->data_len, pad_byte, pad_byte);
+ CRYPTO_INTERNAL_LOG("ENC PKCS : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[0], operation->data[1], operation->data[2], operation->data[3], operation->data[4], operation->data[5], operation->data[6], operation->data[7]);
+ CRYPTO_INTERNAL_LOG("ENC PKCS : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[8], operation->data[9], operation->data[10], operation->data[11], operation->data[12], operation->data[13], operation->data[14], operation->data[15]);
+ }
+ else if(operation->info.algorithm==TEE_ALG_AES_ECB_ISO9797_M1 ||operation->info.algorithm==TEE_ALG_AES_CBC_ISO9797_M1)
+ {
+ if(pad_byte != 0 && (operation->block_len != pad_byte))
+ {
+ should_be_processed_of_pad_bytes = operation->block_len;
+
+ memset(operation->data + operation->data_len, 0x00, pad_byte);
+ CRYPTO_INTERNAL_LOG("ENC ZERO : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[0], operation->data[1], operation->data[2], operation->data[3], operation->data[4], operation->data[5], operation->data[6], operation->data[7]);
+ CRYPTO_INTERNAL_LOG("ENC ZERO : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[8], operation->data[9], operation->data[10], operation->data[11], operation->data[12], operation->data[13], operation->data[14], operation->data[15]);
+ }
+ else
+ {
+ should_be_processed_of_pad_bytes = 0;
+ }
+ }
+ else if (operation->info.algorithm==TEE_ALG_AES_ECB_ISO9797_M2 || operation->info.algorithm==TEE_ALG_AES_CBC_ISO9797_M2)
+ {
+ should_be_processed_of_pad_bytes = operation->block_len;
+
+ memset(operation->data + operation->data_len, 0x00, pad_byte);
+ CRYPTO_INTERNAL_LOG("ENC ZERO : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[0], operation->data[1], operation->data[2], operation->data[3], operation->data[4], operation->data[5], operation->data[6], operation->data[7]);
+ CRYPTO_INTERNAL_LOG("ENC ZERO : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[8], operation->data[9], operation->data[10], operation->data[11], operation->data[12], operation->data[13], operation->data[14], operation->data[15]);
+
+ operation->data[operation->data_len] = 0x80;
+ CRYPTO_INTERNAL_LOG("ENC ISO9797 : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[0], operation->data[1], operation->data[2], operation->data[3], operation->data[4], operation->data[5], operation->data[6], operation->data[7]);
+ CRYPTO_INTERNAL_LOG("ENC ISO9797 : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[8], operation->data[9], operation->data[10], operation->data[11], operation->data[12], operation->data[13], operation->data[14], operation->data[15]);
+ }
+ else if(operation->info.algorithm==TEE_ALG_AES_CTR || operation->info.algorithm==TEE_ALG_AES_CTR_NOPAD)
+ {
+ should_be_processed_of_pad_bytes = remaining_number_of_bytes;
+ }
+
+ if (crypto_final_engine(operation, operation->data, should_be_processed_of_pad_bytes, out_data, &processing_len)) {
+ goto error;
+ }
+
+ total_processing_len += processing_len;
+ }
+ else if(operation->info.mode==TEE_MODE_DECRYPT) {
+ unsigned char * pad = out_data;
+ unsigned int npad=0;
+
+ if (operation->info.algorithm==TEE_ALG_AES_ECB_NOPAD || operation->info.algorithm==TEE_ALG_AES_CBC_NOPAD||
+ operation->info.algorithm==TEE_ALG_DES_ECB_NOPAD || operation->info.algorithm==TEE_ALG_DES_CBC_NOPAD||
+ operation->info.algorithm==TEE_ALG_DES3_ECB_NOPAD || operation->info.algorithm==TEE_ALG_DES3_CBC_NOPAD)
+ {
+ CRYPTO_INTERNAL_LOG("DEC NOPAD : Ignore remaining_number_of_bytes=%d !!", remaining_number_of_bytes);
+ goto exit;
+ }
+ /* PAD */
+ else if (
+ operation->info.algorithm==TEE_ALG_AES_ECB_PKCS5 ||operation->info.algorithm==TEE_ALG_AES_ECB_PKCS7 ||
+ operation->info.algorithm==TEE_ALG_AES_CBC_PKCS5 ||operation->info.algorithm==TEE_ALG_AES_CBC_PKCS7)
+ {
+ memcpy(operation->data, pad-operation->block_len, operation->block_len);
+ CRYPTO_INTERNAL_LOG("DEC PKCS : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[0], operation->data[1], operation->data[2], operation->data[3], operation->data[4], operation->data[5], operation->data[6], operation->data[7]);
+ CRYPTO_INTERNAL_LOG("DEC PKCS : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[8], operation->data[9], operation->data[10], operation->data[11], operation->data[12], operation->data[13], operation->data[14], operation->data[15]);
+
+ pad--; //last byte
+ npad = *pad;
+
+ if (npad <= operation->block_len) // can't be more than block length
+ {
+ unsigned int i;
+ int ok = 1;
+ for(i = 0; i < npad; i++, pad--) {
+ if (*pad != npad) {
+ ok = 0;
+ break;
+ }
+ }
+
+ if (ok) {
+ total_processing_len -= npad; // padding OK. Othewise padding will not be removed
+ }
+ }
+ }
+ else if(operation->info.algorithm==TEE_ALG_AES_ECB_ISO9797_M1 ||operation->info.algorithm==TEE_ALG_AES_CBC_ISO9797_M1)
+ {
+ CRYPTO_INTERNAL_LOG("DEC ISO9797 M1 : Ignore remaining_number_of_bytes=%d !!", remaining_number_of_bytes);
+ goto exit;
+ }
+ else if (operation->info.algorithm==TEE_ALG_AES_ECB_ISO9797_M2 || operation->info.algorithm==TEE_ALG_AES_CBC_ISO9797_M2)
+ {
+ memcpy(operation->data, pad-operation->block_len, operation->block_len);
+ CRYPTO_INTERNAL_LOG("DEC ISO9797 M2 : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[0], operation->data[1], operation->data[2], operation->data[3], operation->data[4], operation->data[5], operation->data[6], operation->data[7]);
+ CRYPTO_INTERNAL_LOG("DEC ISO9797 M2 : op->data=%2X%2X%2X%2X%2X%2X%2X%2X", operation->data[8], operation->data[9], operation->data[10], operation->data[11], operation->data[12], operation->data[13], operation->data[14], operation->data[15]);
+
+ pad--; //last byte
+ npad = 0;
+
+ if (*pad==0x00) // remove 0s
+ for(; npad < operation->block_len-1 && *pad==0x00; npad++,pad--);
+
+ if (*pad==0x80) { // correct M2 padding
+ npad++; // remove 1st PAD byte 0x80
+ }
+ else { // M2 padding error
+ npad = 0; // don't remove any padding
+ }
+
+ total_processing_len -= npad;
+ }
+ else if(operation->info.algorithm==TEE_ALG_AES_CTR || operation->info.algorithm==TEE_ALG_AES_CTR_NOPAD)
+ {
+ memcpy(operation->data, in_data, remaining_number_of_bytes);
+ operation->data_len += remaining_number_of_bytes;
+
+ if (crypto_final_engine(operation, operation->data, remaining_number_of_bytes, out_data, &processing_len)) {
+ goto error;
+ }
+ total_processing_len += remaining_number_of_bytes;
+ }
+ }
+ else
+ {
+ goto error;
+ }
+ }
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_MAC || operation->info.operationClass == TEE_OPERATION_DIGEST)
+ {
+ if (operation->data_len != 0)
+ {
+ if (in_size < (size_t)(operation->block_len - operation->data_len)) {
+ num = in_size;
+ }
+ else {
+ num = (size_t)(operation->block_len - operation->data_len);
+ }
+
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d processed=%d", num, in_size, total_processing_len);
+ if(num != 0) {
+ memcpy(operation->data + operation->data_len, in_data, num);
+
+ operation->data_len += num;
+ in_size -= num;
+ in_data = (unsigned char*)((unsigned long)in_data + num);
+
+ /* accumulated data is full */
+ if (operation->data_len == operation->block_len)
+ {
+ if (crypto_update_engine(operation, operation->data, operation->data_len, NULL, NULL)) {
+ goto error;
+ }
+ operation->data_len = 0;
+ }
+ }
+
+ if (in_size == 0 && operation->data_len != 0) {
+ in_size = operation->data_len;
+ in_data = operation->data;
+ operation->data_len = 0;
+ }
+ CRYPTO_INTERNAL_LOG("num=%d in_size=%d op->data_len=%d", num, in_size, operation->data_len);
+ }
+
+ if (in_size != 0)
+ {
+ if(crypto_final_engine(operation, in_data, in_size, out_data, &out_size)) {
+ goto error;
+ }
+ total_processing_len += in_size;
+ }
+ }
+ else
+ {
+ if(crypto_final_engine(operation, in_data, in_size, out_data, &out_size)) {
+ goto error;
+ }
+ total_processing_len += in_size;
+ }
+exit:
+ CRYPTO_INTERNAL_LOG("in_size=%d out_size=%d processed=%d", in_size, out_size, total_processing_len);
+ CRYPTO_INTERNAL_LOG("--------------------------------------------------------------");
+ if(operation->info.operationClass == TEE_OPERATION_CIPHER && dst_len) {
+ *dst_len = total_processing_len;
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_MAC && dst_len) {
+ *dst_len = out_size;
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_AE && dst_len) {
+ *dst_len = total_processing_len;
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_DIGEST && dst_len) {
+ *dst_len = out_size;
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_ASYMMETRIC_CIPHER && dst_len) {
+ *dst_len = out_size;
+ }
+ else if(operation->info.operationClass == TEE_OPERATION_ASYMMETRIC_SIGNATURE && dst_len) {
+ *dst_len = out_size;
+ }
+ return 0;
+error:
+ LOGE(SSF_LIB, "THIS HERE!!!");
+ CRYPTO_INTERNAL_LOG("--------------------------------------------------------------");
+ return -1;
+}
+
+
+void TEE_DigestInit(TEE_OperationHandle operation);
+
+TEE_Result TEE_AllocateOperation(TEE_OperationHandle *operation, uint32_t algorithm, uint32_t mode, uint32_t maxKeySize)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op;
+ TEE_Result rc=TEE_SUCCESS;
+ uint32_t alg_class = 0;
+ uint32_t key_object_type = 0;
+ uint32_t digest_len = 0;
+ uint32_t block_len = 0;
+ TEE_ObjectHandle key1 = TEE_HANDLE_NULL;
+ TEE_ObjectHandle key2 = TEE_HANDLE_NULL;
+
+ // check parameters compatibility
+ switch(algorithm)
+ {
+ /* Algorithm Class is SYMMETRIC CIPHER */
+ case TEE_ALG_AES_ECB_NOPAD:
+ case TEE_ALG_AES_CBC_NOPAD:
+ case TEE_ALG_AES_CTR:
+ case TEE_ALG_AES_CTR_NOPAD:
+ case TEE_ALG_AES_ECB_PKCS5:
+ case TEE_ALG_AES_ECB_PKCS7:
+ case TEE_ALG_AES_ECB_ISO9797_M1:
+ case TEE_ALG_AES_ECB_ISO9797_M2:
+ case TEE_ALG_AES_CBC_PKCS5:
+ case TEE_ALG_AES_CBC_PKCS7:
+ case TEE_ALG_AES_CBC_ISO9797_M1:
+ case TEE_ALG_AES_CBC_ISO9797_M2:
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_CIPHER;
+ key_object_type = TEE_TYPE_AES;
+ block_len = 16;
+ digest_len = 0;
+ break;
+
+ case TEE_ALG_AES_XTS:
+ case TEE_ALG_AES_CTS:
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_CIPHER;
+ key_object_type = TEE_TYPE_AES;
+ block_len = 32; // for CTS & XTS need 2 AES blocks
+ digest_len = 0;
+ break;
+
+ case TEE_ALG_DES_ECB_NOPAD:
+ case TEE_ALG_DES_CBC_NOPAD:
+
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_CIPHER;
+ key_object_type = TEE_TYPE_DES;
+ block_len = 8;
+ digest_len = 0;
+ break;
+
+ case TEE_ALG_DES3_ECB_NOPAD:
+ case TEE_ALG_DES3_CBC_NOPAD:
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_CIPHER;
+ key_object_type = TEE_TYPE_DES3;
+ block_len = 8;
+ digest_len = 0;
+ break;
+
+ /* Algorithm Class is AE */
+ case TEE_ALG_AES_CCM:
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_AE;
+ key_object_type = TEE_TYPE_AES;
+ block_len = 16;
+ digest_len = 0;
+ break;
+
+ case TEE_ALG_AES_GCM:
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_AE;
+ key_object_type = TEE_TYPE_AES;
+ block_len = 16;
+ digest_len = 0;
+ break;
+
+ /* Algorithm Class is MAC */
+ case TEE_ALG_AES_CBC_MAC_NOPAD:
+ case TEE_ALG_AES_CBC_MAC_PKCS5:
+ case TEE_ALG_AES_CMAC:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_AES;
+ block_len = 16;
+ digest_len = 16;
+ break;
+
+ case TEE_ALG_DES_CBC_MAC_NOPAD:
+ case TEE_ALG_DES_CBC_MAC_PKCS5:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_DES;
+ block_len = 8;
+ digest_len = 8;
+ break;
+
+ case TEE_ALG_DES3_CBC_MAC_NOPAD:
+ case TEE_ALG_DES3_CBC_MAC_PKCS5:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_DES3;
+ block_len = 8;
+ digest_len = 8;
+ break;
+
+ case TEE_ALG_HMAC_MD5:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_HMAC_MD5;
+ block_len = 64;
+ digest_len = 16;
+ break;
+
+ case TEE_ALG_HMAC_SHA1:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_HMAC_SHA1;
+ block_len = 64;
+ digest_len = 20;
+ break;
+
+ case TEE_ALG_HMAC_SHA224:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_HMAC_SHA224;
+ block_len = 64;
+ digest_len = 28;
+ break;
+
+ case TEE_ALG_HMAC_SHA256:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_HMAC_SHA256;
+ block_len = 64;
+ digest_len = 32;
+ break;
+
+ case TEE_ALG_HMAC_SHA384:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_HMAC_SHA384;
+ block_len = 64;
+ digest_len = 48;
+ break;
+
+ case TEE_ALG_HMAC_SHA512:
+ if (mode != TEE_MODE_MAC) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_MAC;
+ key_object_type = TEE_TYPE_HMAC_SHA512;
+ block_len = 64;
+ digest_len = 64;
+ break;
+
+ /* Algorithm Class is DIGIT */
+ case TEE_ALG_MD5:
+ if (mode != TEE_MODE_DIGEST) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_DIGEST;
+ key_object_type = 0;
+ digest_len = 16;
+ block_len = 64;
+ break;
+
+ case TEE_ALG_SHA1:
+ if (mode != TEE_MODE_DIGEST) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_DIGEST;
+ key_object_type = 0;
+ digest_len = 20;
+ block_len = 64;
+ break;
+
+ case TEE_ALG_SHA224:
+ if (mode != TEE_MODE_DIGEST) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_DIGEST;
+ key_object_type = 0;
+ digest_len = 28;
+ block_len = 64;
+ break;
+
+ case TEE_ALG_SHA256:
+ if (mode != TEE_MODE_DIGEST) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_DIGEST;
+ key_object_type = 0;
+ digest_len = 32;
+ block_len = 64;
+ break;
+
+ case TEE_ALG_SHA384:
+ if (mode != TEE_MODE_DIGEST) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_DIGEST;
+ key_object_type = 0;
+ digest_len = 48;
+ block_len = 64;
+ break;
+
+ case TEE_ALG_SHA512:
+ if (mode != TEE_MODE_DIGEST) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_DIGEST;
+ key_object_type = 0;
+ digest_len = 64;
+ block_len = 64;
+ break;
+
+ /* Algorithm Class is ASYMMETRIC CIPHER */
+ case TEE_ALG_RSAES_PKCS1_V1_5:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
+ case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
+ case TEE_ALG_RSA_NOPAD:
+ if (mode != TEE_MODE_ENCRYPT && mode != TEE_MODE_DECRYPT) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_ASYMMETRIC_CIPHER;
+ key_object_type = TEE_TYPE_RSA_KEYPAIR;
+ block_len = 0;
+ digest_len = 0;
+ break;
+
+ /* Algorithm Class is SIGNATURE */
+ case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
+ case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
+ if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
+ key_object_type = TEE_TYPE_RSA_KEYPAIR;
+ break;
+
+ case TEE_ALG_ECDSA_P160:
+ case TEE_ALG_ECDSA_P192:
+ case TEE_ALG_ECDSA_P224:
+ case TEE_ALG_ECDSA_P256:
+ case TEE_ALG_ECDSA_P384:
+ case TEE_ALG_ECDSA_P521:
+ if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
+ key_object_type = TEE_TYPE_RSA_KEYPAIR;
+ break;
+
+ case TEE_ALG_DSA_SHA1:
+ if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
+ key_object_type = TEE_TYPE_DSA_KEYPAIR;
+ break;
+
+ case TEE_ALG_ECDH_P192:
+ case TEE_ALG_ECDH_P224:
+ case TEE_ALG_ECDH_P256:
+ case TEE_ALG_ECDH_P384:
+ case TEE_ALG_ECDH_P521:
+ if (mode != TEE_MODE_SIGN && mode != TEE_MODE_VERIFY) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
+ key_object_type = TEE_TYPE_ECDH_KEYPAIR;
+ break;
+
+ /* Algorithm Class is KEY DERIVATION */
+ case TEE_ALG_DH_DERIVE_SHARED_SECRET:
+ if (mode != TEE_MODE_DERIVE) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+
+ alg_class = TEE_OPERATION_KEY_DERIVATION;
+ key_object_type = TEE_TYPE_DH_KEYPAIR;
+ break;
+
+ default:
+ LOGE(SSF_LIB, "Not Support Algorithm : %X", algorithm);
+ rc = TEE_ERROR_NOT_SUPPORTED;
+ goto exit;
+ break;
+ }
+
+ /* first malloc for crypto operation */
+ op = (crypto_internal_operation *)malloc(sizeof (crypto_internal_operation));
+ if (!op) {
+ rc = TEE_ERROR_OUT_OF_MEMORY;
+ goto exit;
+ }
+
+ memset(op, 0, sizeof (crypto_internal_operation));
+
+ /* Set TEE_OperationInfo */
+ op->info.algorithm = algorithm;
+ op->info.operationClass = alg_class;
+ op->info.mode = mode;
+ op->info.digestLength = digest_len;
+ op->info.maxKeySize = maxKeySize;
+ op->info.keySize = maxKeySize;
+
+ if (mode == TEE_MODE_ENCRYPT) {
+ op->info.requiredKeyUsage |= TEE_USAGE_ENCRYPT;
+ }
+ if (mode == TEE_MODE_DECRYPT) {
+ op->info.requiredKeyUsage |= TEE_USAGE_DECRYPT;
+ }
+ if (mode == TEE_MODE_MAC) {
+ op->info.requiredKeyUsage |= TEE_USAGE_MAC;
+ }
+ if (mode == TEE_MODE_DERIVE) {
+ op->info.requiredKeyUsage |= TEE_USAGE_DERIVE;
+ }
+ if (mode == TEE_MODE_SIGN) {
+ op->info.requiredKeyUsage |= TEE_USAGE_SIGN;
+ }
+ if (mode == TEE_MODE_VERIFY) {
+ op->info.requiredKeyUsage |= TEE_USAGE_VERIFY;
+ }
+ if (algorithm == TEE_ALG_RSA_NOPAD)
+ {
+ if (mode == TEE_MODE_ENCRYPT) {
+ op->info.requiredKeyUsage |= TEE_USAGE_VERIFY;
+ }
+ else if (mode == TEE_MODE_DECRYPT) {
+ op->info.requiredKeyUsage |= TEE_USAGE_SIGN;
+ }
+ }
+
+ if (algorithm == TEE_ALG_AES_XTS) {
+ op->info.handleState |= TEE_HANDLE_FLAG_EXPECT_TWO_KEYS;
+ }
+
+ /* get handle */
+ if(crypto_internal_open(op)!=0) {
+ rc = TEE_ERROR_NOT_SUPPORTED;
+ goto error;
+ }
+
+ /* key1 alloc */
+ if (key_object_type) {
+ if (TEE_AllocateTransientObject(key_object_type, maxKeySize, &key1) != TEE_SUCCESS) {
+ rc = TEE_ERROR_OUT_OF_MEMORY;
+ goto error;
+ }
+ }
+
+ /* key2 alloc for XTS */
+ if (algorithm == TEE_ALG_AES_XTS) {
+ if (TEE_AllocateTransientObject(key_object_type, maxKeySize, &key2) != TEE_SUCCESS) {
+ rc = TEE_ERROR_OUT_OF_MEMORY;
+ goto error;
+ }
+ }
+
+ /* key map for crypto operation */
+ op->key1 = key1;
+ op->key2 = key2;
+ op->block_len = block_len;
+
+ *operation = (TEE_OperationHandle) &op->info;
+
+ if (alg_class == TEE_OPERATION_DIGEST) {
+ TEE_DigestInit(*operation);
+ }
+
+ return TEE_SUCCESS;
+
+error:
+ crypto_internal_close(op);
+ if (key1) {
+ TEE_CloseObject(key1);
+ }
+ if (key2) {
+ TEE_CloseObject(key2);
+ }
+ if (op) {
+ free(op);
+ }
+exit:
+ *operation = TEE_HANDLE_NULL;
+ LOGE(SSF_LIB, "Error : %X", rc);
+ return rc;
+}
+
+void TEE_FreeOperation(TEE_OperationHandle operation)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+
+ crypto_internal_operation * op;
+
+ if (operation == TEE_HANDLE_NULL) {
+ return;
+ }
+ op = (crypto_internal_operation*)operation;
+ if (op->key1) {
+ TEE_CloseObject(op->key1);
+ }
+ if (op->key2) {
+ TEE_CloseObject(op->key2);
+ }
+ crypto_internal_close(op);
+ free(op);
+ return;
+}
+
+void TEE_GetOperationInfo( TEE_OperationHandle operation, TEE_OperationInfo* operationInfo)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ operationInfo->algorithm = op->info.algorithm;
+ operationInfo->digestLength = op->info.digestLength;
+ operationInfo->handleState = op->info.handleState;
+ operationInfo->keySize = op->info.keySize;
+ operationInfo->maxKeySize = op->info.maxKeySize;
+ operationInfo->mode = op->info.mode;
+ operationInfo->operationClass = op->info.operationClass;
+ operationInfo->requiredKeyUsage = op->info.requiredKeyUsage;
+}
+
+void TEE_ResetOperation( TEE_OperationHandle operation)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+ op->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
+ return;
+}
+
+TEE_Result TEE_SetOperationKey( TEE_OperationHandle operation, TEE_ObjectHandle key)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+ if (!op || op->info.operationClass == TEE_OPERATION_DIGEST || op->info.algorithm == TEE_ALG_AES_XTS)
+ {
+ LOGE(SSF_LIB, "op->info.operationClass == TEE_OPERATION_DIGEST\n");
+ return TEE_ERROR_BAD_PARAMETERS;
+
+ };
+
+ if (key == TEE_HANDLE_NULL)
+ {
+ TEE_CloseObject(op->key1);
+ op->key1 = TEE_HANDLE_NULL;
+ return TEE_SUCCESS;
+ }
+
+ if ((key->tr.info.objectUsage | ~(op->info.requiredKeyUsage)) != 0xffffffff)
+ {
+ LOGE(SSF_LIB, "(key->tr.info.objectUsage | ~(op->info.requiredKeyUsage)) != 0xffffffff\n");
+ return TEE_ERROR_BAD_PARAMETERS;
+
+ };
+
+ TEE_CopyObjectAttributes(op->key1, key);
+
+ op->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_SetOperationKey2( TEE_OperationHandle operation, TEE_ObjectHandle key1, TEE_ObjectHandle key2)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if ( (key1 && !key2) || (!key1 && key2)) {
+ CRYPTO_PANIC;
+ }
+ if (!op || op->info.algorithm != TEE_ALG_AES_XTS) {
+ CRYPTO_PANIC;
+ }
+
+ if (!key1 && !key2)
+ {
+ TEE_CloseObject(op->key1);
+ TEE_CloseObject(op->key2);
+ op->key1 = TEE_HANDLE_NULL;
+ op->key2 = TEE_HANDLE_NULL;
+ return TEE_SUCCESS;
+ }
+
+ if ((key1->tr.info.objectUsage | ~op->info.requiredKeyUsage) != 0xffffffff) {
+ CRYPTO_PANIC;
+ }
+ if ((key2->tr.info.objectUsage | ~op->info.requiredKeyUsage) != 0xffffffff) {
+ CRYPTO_PANIC;
+ }
+
+ TEE_CopyObjectAttributes(op->key1, key1);
+ TEE_CopyObjectAttributes(op->key2, key2);
+
+ op->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
+ return TEE_SUCCESS;
+}
+
+
+void TEE_CopyOperation( TEE_OperationHandle dstOperation, TEE_OperationHandle srcOperation)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+
+ crypto_internal_operation * dstOp = (crypto_internal_operation*) dstOperation;
+ crypto_internal_operation * srcOp = (crypto_internal_operation*) srcOperation;
+
+ if (dstOp->info.mode != srcOp->info.mode || dstOp->info.algorithm != srcOp->info.algorithm) {
+ CRYPTO_PANIC;
+ }
+ if (dstOp->info.maxKeySize < srcOp->info.maxKeySize) {
+ CRYPTO_PANIC;
+ }
+
+ dstOp->info.algorithm = srcOp->info.algorithm;
+ dstOp->info.digestLength = srcOp->info.digestLength;
+ dstOp->info.handleState = srcOp->info.handleState;
+ dstOp->info.keySize = srcOp->info.keySize;
+ dstOp->info.maxKeySize = srcOp->info.maxKeySize;
+ dstOp->info.mode = srcOp->info.mode;
+ dstOp->info.operationClass = srcOp->info.operationClass;
+ dstOp->info.requiredKeyUsage = srcOp->info.requiredKeyUsage;
+
+ if (dstOp->key1) {
+ TEE_CopyObjectAttributes(dstOp->key1, srcOp->key1);
+ }
+ if (dstOp->key2) {
+ TEE_CopyObjectAttributes(dstOp->key2, srcOp->key2);
+ }
+ if (srcOp->crypto) {
+ if (crypto_internal_open(dstOp) != 0) {
+ CRYPTO_PANIC;
+ }
+ }
+ else {
+ dstOp->crypto = -1;
+ }
+ return;
+}
+
+// Message Digest Functions
+/*
+This is not GP Spec function. but I used this
+*/
+void TEE_DigestInit(TEE_OperationHandle operation)
+{
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (crypto_internal_init(op, NULL, NULL, 0)) {
+ CRYPTO_PANIC;
+ }
+ op->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
+ op->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
+ return;
+}
+
+void TEE_DigestUpdate( TEE_OperationHandle operation, const void* chunk, size_t chunkSize)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (!op || !chunk || !chunkSize) {
+ return;
+ }
+ if (op->info.operationClass != TEE_OPERATION_DIGEST) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
+ TEE_DigestInit(operation);
+ }
+ if (crypto_internal_update(op, (unsigned char*)chunk, chunkSize, NULL, NULL)) {
+ CRYPTO_PANIC;
+ }
+ return;
+}
+
+TEE_Result TEE_DigestDoFinal( TEE_OperationHandle operation, const void* chunk, size_t chunkLen, void* hash, size_t *hashLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (!hash || *hashLen < op->info.digestLength) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+ if (op->info.operationClass != TEE_OPERATION_DIGEST) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
+ TEE_DigestInit(operation);
+ }
+ if(crypto_internal_final(op, (unsigned char*)chunk, chunkLen, (unsigned char*)hash, hashLen)) {
+ CRYPTO_PANIC;
+ }
+ return TEE_SUCCESS;
+}
+
+// Symmetric Cipher Functions
+void TEE_CipherInit( TEE_OperationHandle operation, const void* IV, size_t IVLen)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+ crypto_internal_keystruct key;
+ unsigned char key_buf[32] = {0x0, };
+
+ memset(&key, 0x00, sizeof(crypto_internal_keystruct));
+ key.secret.size = sizeof(key_buf);
+ key.secret.buffer = key_buf;
+
+ if (op->info.operationClass != TEE_OPERATION_CIPHER) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_SECRET_VALUE,
+ (void*)key.secret.buffer, (size_t*)&key.secret.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (!key.secret.buffer) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(op, &key, (unsigned char*)IV, IVLen)) {
+ CRYPTO_PANIC;
+ }
+ op->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
+ return;
+}
+
+TEE_Result TEE_CipherUpdate( TEE_OperationHandle operation, const void* srcData, size_t srcLen, void* destData, size_t *destLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (*destLen < srcLen) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+ if (op->info.operationClass != TEE_OPERATION_CIPHER) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_update(op, (unsigned char*)srcData, srcLen, (unsigned char*)destData, destLen)) {
+ CRYPTO_PANIC;
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_CipherDoFinal( TEE_OperationHandle operation, const void* srcData, size_t srcLen, void* destData, size_t *destLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (*destLen < srcLen) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+ if (op->info.operationClass != TEE_OPERATION_CIPHER) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_final(op, (unsigned char*)srcData, srcLen, (unsigned char*)destData, destLen)) {
+ CRYPTO_PANIC;
+ }
+ return TEE_SUCCESS;
+}
+
+// MAC Functions
+void TEE_MACInit( TEE_OperationHandle operation, const void* IV, size_t IVLen)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+ crypto_internal_keystruct key;
+ unsigned char key_buf[128] = {0x0, };
+
+ memset(&key, 0x00, sizeof(crypto_internal_keystruct));
+ key.secret.size = sizeof(key_buf);
+ key.secret.buffer = key_buf;
+
+ if (op->info.operationClass != TEE_OPERATION_MAC) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_SECRET_VALUE,
+ (void*)key.secret.buffer, (size_t*)&key.secret.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (!key.secret.buffer) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(op, &key, (unsigned char*)IV, IVLen)) {
+ CRYPTO_PANIC;
+ }
+ op->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
+ return;
+}
+
+void TEE_MACUpdate( TEE_OperationHandle operation, const void* chunk, size_t chunkSize)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (!chunk || !chunkSize) {
+ return;
+ }
+ if (op->info.operationClass != TEE_OPERATION_MAC) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_update(op, (unsigned char*)chunk, chunkSize, NULL, NULL)) {
+ CRYPTO_PANIC;
+ }
+ return;
+}
+
+TEE_Result TEE_MACComputeFinal( TEE_OperationHandle operation, const void* message, size_t messageLen, void* mac, size_t *macLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (!mac || *macLen < op->info.digestLength) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+ if (op->info.operationClass != TEE_OPERATION_MAC) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_INITIALIZED)) {
+ CRYPTO_PANIC;
+ }
+ if(crypto_internal_final(op, (unsigned char*)message, messageLen, (unsigned char*)mac, macLen)) {
+ CRYPTO_PANIC;
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_MACCompareFinal( TEE_OperationHandle operation, void* message, size_t messageLen, void* mac, size_t *macLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+ char result[64];
+ size_t result_len = sizeof result;
+
+ if (!mac || !macLen || *macLen != op->info.digestLength) {
+ return TEE_ERROR_MAC_INVALID;
+ }
+ if (TEE_MACComputeFinal(operation, (unsigned char*)message, messageLen, result, &result_len) != TEE_SUCCESS) {
+ return TEE_ERROR_MAC_INVALID;
+ }
+ if (memcmp(mac, result, *macLen)) {
+ return TEE_ERROR_MAC_INVALID;
+ }
+
+ return TEE_SUCCESS;
+}
+
+// Authenticated Encryption Functions
+TEE_Result TEE_AEInit(TEE_OperationHandle operation, void* nonce, size_t nonceLen, uint32_t tagLen, uint32_t AADLen, uint32_t payloadLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ (void)operation;
+ (void)nonce;
+ (void)nonceLen;
+ (void)tagLen;
+ (void)AADLen;
+ (void)payloadLen;
+ return TEE_SUCCESS;
+}
+
+void TEE_AEUpdateAAD(TEE_OperationHandle operation, void* AADdata, size_t AADdataLen)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ (void)operation;
+ (void)AADdata;
+ (void)AADdataLen;
+ return;
+}
+
+TEE_Result TEE_AEUpdate(TEE_OperationHandle operation, void* srcData, size_t srcLen, void* destData, size_t *destLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ (void)operation;
+ (void)srcData;
+ (void)srcLen;
+ (void)destData;
+ (void)destLen;
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_AEEncryptFinal(TEE_OperationHandle operation, void* srcData, size_t srcLen, void* destData, size_t* destLen, void* tag, size_t* tagLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (op->info.operationClass != TEE_OPERATION_AE) {
+ CRYPTO_PANIC;
+ }
+ if (op->info.mode != TEE_MODE_ENCRYPT) {
+ CRYPTO_PANIC;
+ }
+ (void)srcData;
+ (void)srcLen;
+ (void)destData;
+ (void)destLen;
+ (void)tag;
+ (void)tagLen;
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_AEDecryptFinal(TEE_OperationHandle operation, void* srcData, size_t srcLen, void* destData, size_t *destLen, void* tag, size_t tagLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+
+ if (op->info.operationClass != TEE_OPERATION_AE) {
+ CRYPTO_PANIC;
+ }
+ if (op->info.mode != TEE_MODE_DECRYPT) {
+ CRYPTO_PANIC;
+ }
+ (void)srcData;
+ (void)srcLen;
+ (void)destData;
+ (void)destLen;
+ (void)tag;
+ (void)tagLen;
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_AsymmetricEncrypt( TEE_OperationHandle operation,const TEE_Attribute* params, uint32_t paramCount, const void* srcData, size_t srcLen, void* destData, size_t *destLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ (void)params;
+ (void)paramCount;
+ crypto_internal_operation *op = (crypto_internal_operation*) operation;
+ crypto_internal_keystruct key;
+ unsigned char module_buf[384] = {0x0, };
+ unsigned char pub_buf[384] = {0x0, };
+
+ memset(&key, 0x00, sizeof(crypto_internal_keystruct));
+ key.rsa_modulus.size = sizeof(module_buf);
+ key.rsa_modulus.buffer = module_buf;
+ key.rsa_public.size = sizeof(pub_buf);
+ key.rsa_public.buffer = pub_buf;
+
+ if (op->info.operationClass != TEE_OPERATION_ASYMMETRIC_CIPHER) {
+ CRYPTO_PANIC;
+ }
+ if (op->info.mode != TEE_MODE_ENCRYPT ) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_MODULUS,
+ (void*)key.rsa_modulus.buffer, (size_t*)&key.rsa_modulus.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PUBLIC_EXPONENT,
+ (void*)key.rsa_public.buffer, (size_t*)&key.rsa_public.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if(!key.rsa_modulus.buffer || !key.rsa_public.buffer ) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(op, &key, NULL, 0)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_final(op, (unsigned char*)srcData, srcLen, (unsigned char*)destData, destLen)) {
+ return TEE_ERROR_SIGNATURE_INVALID;
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_AsymmetricDecrypt( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* srcData, size_t srcLen, void* destData, size_t *destLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+
+ (void)params;
+ (void)paramCount;
+ crypto_internal_operation * op = (crypto_internal_operation*) operation;
+ crypto_internal_keystruct key;
+
+ unsigned char module_buf[384] = {0x0, };
+ unsigned char pub_buf[384] = {0x0, };
+ unsigned char priv_buf[384] = {0x0, };
+
+ memset(&key, 0x00, sizeof(crypto_internal_keystruct));
+ key.rsa_modulus.size = sizeof(module_buf);
+ key.rsa_modulus.buffer = module_buf;
+ key.rsa_public.size = sizeof(pub_buf);
+ key.rsa_public.buffer = pub_buf;
+ key.rsa_private.size = sizeof(priv_buf);
+ key.rsa_private.buffer = priv_buf;
+
+ if (op->info.operationClass != TEE_OPERATION_ASYMMETRIC_CIPHER) {
+ CRYPTO_PANIC;
+ }
+ if (op->info.mode != TEE_MODE_DECRYPT) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_MODULUS,
+ (void*)key.rsa_modulus.buffer, (size_t*)&key.rsa_modulus.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PUBLIC_EXPONENT,
+ (void*)key.rsa_public.buffer, (size_t*)&key.rsa_public.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PRIVATE_EXPONENT,
+ (void*)key.rsa_private.buffer, (size_t*)&key.rsa_private.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+#if 0 /* Not Support */
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PRIME1,
+ (void*)key.rsa_prime1.buffer, (size_t*)&key.rsa_prime1.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PRIME2,
+ (void*)key.rsa_prime2.buffer, (size_t*)&key.rsa_prime2.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_EXPONENT1,
+ (void*)key.rsa_exponent1.buffer, (size_t*)&key.rsa_exponent1.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_EXPONENT2,
+ (void*)key.rsa_exponent2.buffer, (size_t*)&key.rsa_exponent2.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_COEFFICIENT,
+ (void*)key.rsa_coefficient.buffer, (size_t*)&key.rsa_coefficient.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+#endif
+ if(!key.rsa_modulus.buffer || !key.rsa_public.buffer || !key.rsa_private.buffer
+ /*|| !key.rsa_prime1.buffer || !key.rsa_prime2.buffer || !key.rsa_exponent1.buffer
+ || !key.rsa_exponent2.buffer || !key.rsa_coefficient.buffer*/) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(op, &key, NULL, 0)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_final(op, (unsigned char*)srcData, srcLen, (unsigned char*)destData, destLen)) {
+ CRYPTO_PANIC;
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_AsymmetricSignDigest( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* digest, size_t digestLen, void* signature, size_t *signatureLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ (void)params;
+ (void)paramCount;
+ crypto_internal_operation *op = (crypto_internal_operation*) operation;
+ crypto_internal_keystruct key;
+
+ unsigned char module_buf[384] = {0x0, };
+ unsigned char pub_buf[384] = {0x0, };
+ unsigned char priv_buf[384] = {0x0, };
+
+ memset(&key, 0x00, sizeof(crypto_internal_keystruct));
+ key.rsa_modulus.size = sizeof(module_buf);
+ key.rsa_modulus.buffer = module_buf;
+ key.rsa_public.size = sizeof(pub_buf);
+ key.rsa_public.buffer = pub_buf;
+ key.rsa_private.size = sizeof(priv_buf);
+ key.rsa_private.buffer = priv_buf;
+
+ if (op->info.operationClass != TEE_OPERATION_ASYMMETRIC_SIGNATURE) {
+ CRYPTO_PANIC;
+ }
+ if (op->info.mode != TEE_MODE_SIGN ) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_MODULUS,
+ (void*)key.rsa_modulus.buffer, (size_t*)&key.rsa_modulus.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PUBLIC_EXPONENT,
+ (void*)key.rsa_public.buffer, (size_t*)&key.rsa_public.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PRIVATE_EXPONENT,
+ (void*)key.rsa_private.buffer, (size_t*)&key.rsa_private.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+#if 0 /* Not Support */
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PRIME1,
+ (void*)key.rsa_prime1.buffer, (size_t*)&key.rsa_prime1.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PRIME2,
+ (void*)key.rsa_prime2.buffer, (size_t*)&key.rsa_prime2.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_EXPONENT1,
+ (void*)key.rsa_exponent1.buffer, (size_t*)&key.rsa_exponent1.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_EXPONENT2,
+ (void*)key.rsa_exponent2.buffer, (size_t*)&key.rsa_exponent2.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_COEFFICIENT,
+ (void*)key.rsa_coefficient.buffer, (size_t*)&key.rsa_coefficient.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+#endif
+ if(!key.rsa_modulus.buffer || !key.rsa_public.buffer || !key.rsa_private.buffer
+ /*|| !key.rsa_prime1.buffer || !key.rsa_prime2.buffer || !key.rsa_exponent1.buffer
+ || !key.rsa_exponent2.buffer || !key.rsa_coefficient.buffer*/) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(op, &key, NULL, 0)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_final(op, (unsigned char*)digest, digestLen, (unsigned char*)signature, signatureLen)) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_AsymmetricVerifyDigest( TEE_OperationHandle operation, const TEE_Attribute* params, uint32_t paramCount, const void* digest, size_t digestLen, void* signature, size_t signatureLen)
+{
+ PERMISSION_CHECK(PERM_CRYPTO);
+ (void)params;
+ (void)paramCount;
+ crypto_internal_operation *op = (crypto_internal_operation*) operation;
+ crypto_internal_keystruct key;
+ size_t sign_len=signatureLen;
+
+ unsigned char module_buf[384] = {0x0, };
+ unsigned char pub_buf[384] = {0x0, };
+
+ memset(&key, 0x00, sizeof(crypto_internal_keystruct));
+ key.rsa_modulus.size = sizeof(module_buf);
+ key.rsa_modulus.buffer = module_buf;
+ key.rsa_public.size = sizeof(pub_buf);
+ key.rsa_public.buffer = pub_buf;
+
+ if (op->info.operationClass != TEE_OPERATION_ASYMMETRIC_SIGNATURE) {
+ CRYPTO_PANIC;
+ }
+ if (op->info.mode != TEE_MODE_VERIFY ) {
+ CRYPTO_PANIC;
+ }
+ if (!(op->info.handleState & TEE_HANDLE_FLAG_KEY_SET)) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_MODULUS,
+ (void*)key.rsa_modulus.buffer, (size_t*)&key.rsa_modulus.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if (TEE_GetObjectBufferAttribute(op->key1, TEE_ATTR_RSA_PUBLIC_EXPONENT,
+ (void*)key.rsa_public.buffer, (size_t*)&key.rsa_public.size) != TEE_SUCCESS) {
+ CRYPTO_PANIC;
+ }
+ if(!key.rsa_modulus.buffer || !key.rsa_public.buffer ) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(op, &key, NULL, 0)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_final(op, (unsigned char*)digest, digestLen, (unsigned char*)signature, &sign_len)) {
+ return TEE_ERROR_SIGNATURE_INVALID;
+ }
+ return TEE_SUCCESS;
+}
+
+// Key Derivation Functions
+void TEE_DeriveKey( TEE_OperationHandle operation, TEE_Attribute* params, uint32_t paramCount, TEE_ObjectHandle derivedKey)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ (void)operation;
+ (void)params;
+ (void)paramCount;
+ (void)derivedKey;
+ return;
+}
+
+void TEE_GenerateRandom(void* randomBuffer, size_t randomBufferLen)
+{
+ PERMISSION_CHECK_RETURN_VOID(PERM_CRYPTO);
+ crypto_internal_operation op;
+ crypto_internal_keystruct key;
+ unsigned char random[512] = {0};
+ size_t random_len=512;
+ memset((void *)&op,0,sizeof(op));
+ if(randomBufferLen > 512)
+ {
+ LOGE(SSF_LIB, "currently only support less than 512 byte random data");
+ return;
+ }
+ op.info.algorithm = TEE_ALG_GENERATE_SECRET_KEY;
+ op.info.keySize = randomBufferLen;
+ /*cryptocore need bit_length*/
+ key.secret.buffer = random;
+ key.secret.size = random_len*8;
+
+ if (crypto_internal_open(&op)!=0) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_init(&op, &key, NULL, 0)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_final(&op, NULL, 0, NULL, NULL)) {
+ CRYPTO_PANIC;
+ }
+ if (crypto_internal_close(&op)) {
+ CRYPTO_PANIC;
+ }
+ memcpy(randomBuffer, random, randomBufferLen);
+ return;
+}
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssflib.c
- *
- * Description: SSF Library functions
- *
- * Version: 1.0
- * Created: 20 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: krishna (Kr), k.devale@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include "ssf_lib.h"
-#include "ssf_client.h"
-#include <stdio.h>
-#include <assert.h>
-
-/*-----------------------------------------------------------------------------
- * Globals
- *-----------------------------------------------------------------------------*/
-extern TEE_UUID sharedthisTAUUID;
-int32_t socketSimulatorDaemonFD = 0;
-pthread_mutex_t socketLock = PTHREAD_MUTEX_INITIALIZER;
-TeeStubSSFSharedData sharedData = {false, false, true};
-
-/*-----------------------------------------------------------------------------
- * Local functions
- *-----------------------------------------------------------------------------*/
-extern "C"{
-
-/**
- * Initializes SSF for use by TA
- */
-__attribute__((constructor)) void initializeSSF() {
-
- socketSimulatorDaemonFD = connecttoServer();
- assert(socketSimulatorDaemonFD != -1);
- LOGD(SIM_DAEMON, "Done");}
-
-/**
- * Deinits SSF. Should be called by TA once
- */
-
-__attribute__((destructor)) void deinitializeSSF() {
- disconnectfromServer(socketSimulatorDaemonFD);
- LOGD(SIM_DAEMON, "Done"); }
-
-}
-/* =========================================================================
- * OPERATION CANCELLATION
- * =========================================================================
- */
-
-/**
- * Determines whether the current task's Cancellation Flag is set
- *
- * The TEE_GetCancellationFlag function determines whether the current task's
- * Cancellation Flag is set. If cancellations are masked, this function must
- * return false.
- *
- * @return 'false' if the cancellation flag is not set or if cancellations are
- * masked; 'true' if the cancellation flag is set and cancellations are not
- * masked
- */
-bool TEE_GetCancellationFlag(void) {
-return (sharedData.thisTaskMask ? false : sharedData.thisTaskCancel);
-}
-
-/**
- * Unmasks the effects of cancellation
- *
- * The TEE_UnmaskCancellation function unmasks the effects of cancellation for
- * the current task. When cancellation requests are unmasked, the Cancellation
- * Flag interrupts cancellable functions such as @ref TEE_Wait and requests the
- * cancellation of operations started with @ref TEE_OpenTASession or
- * @ref TEE_InvokeTACommand. By default, tasks created to handle a TA entry
- * point have cancellation masked, so that a TA does not have to cope with the
- * effects of cancellation requests.
- * @return 'true' if cancellations were masked prior to calling this function;
- * 'false' otherwise
- */
-bool TEE_UnmaskCancellation(void) {
-bool preState = sharedData.thisTaskMask;
-sharedData.thisTaskMask = false;
-return (preState ? true : false);
-}
-
-/**
- * Masks the effects of cancellation
- *
- * The TEE_MaskCancellation function masks the effects of cancellation for the
- * current task. When cancellation requests are masked, the Cancellation Flag
- * does not have an effect on the cancellable functions and cannot be retrieved
- * using @ref TEE_GetCancellationFlag. By default, tasks created to handle a TA
- * entry point have cancellation masked, so that a TA does not have to cope with
- * the effects of cancellation requests.
- *
- * @return 'true' if cancellations were masked prior to calling this function;
- * 'false' otherwise
- */
-bool TEE_MaskCancellation(void) {
-bool preState = sharedData.thisTaskMask;
-sharedData.thisTaskMask = true;
-return (preState ? true : false);
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssflib.c
+ *
+ * Description: SSF Library functions
+ *
+ * Version: 1.0
+ * Created: 20 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: krishna (Kr), k.devale@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include "ssf_lib.h"
+#include "ssf_client.h"
+#include <stdio.h>
+#include <assert.h>
+
+/*-----------------------------------------------------------------------------
+ * Globals
+ *-----------------------------------------------------------------------------*/
+extern TEE_UUID sharedthisTAUUID;
+int32_t socketSimulatorDaemonFD = 0;
+pthread_mutex_t socketLock = PTHREAD_MUTEX_INITIALIZER;
+TeeStubSSFSharedData sharedData = {false, false, true};
+
+/*-----------------------------------------------------------------------------
+ * Local functions
+ *-----------------------------------------------------------------------------*/
+
+extern "C"{
+
+/**
+ * Initializes SSF for use by TA
+ */
+__attribute__((constructor)) void initializeSSF() {
+
+ socketSimulatorDaemonFD = connecttoServer();
+ assert(socketSimulatorDaemonFD != -1);
+ LOGD(SIM_DAEMON, "Done");}
+
+/**
+ * Deinits SSF. Should be called by TA once
+ */
+
+__attribute__((destructor)) void deinitializeSSF() {
+ disconnectfromServer(socketSimulatorDaemonFD);
+ LOGD(SIM_DAEMON, "Done"); }
+
+}
+
+/* =========================================================================
+ * OPERATION CANCELLATION
+ * =========================================================================
+ */
+
+/**
+ * Determines whether the current task's Cancellation Flag is set
+ *
+ * The TEE_GetCancellationFlag function determines whether the current task's
+ * Cancellation Flag is set. If cancellations are masked, this function must
+ * return false.
+ *
+ * @return 'false' if the cancellation flag is not set or if cancellations are
+ * masked; 'true' if the cancellation flag is set and cancellations are not
+ * masked
+ */
+bool TEE_GetCancellationFlag(void) {
+return (sharedData.thisTaskMask ? false : sharedData.thisTaskCancel);
+}
+
+/**
+ * Unmasks the effects of cancellation
+ *
+ * The TEE_UnmaskCancellation function unmasks the effects of cancellation for
+ * the current task. When cancellation requests are unmasked, the Cancellation
+ * Flag interrupts cancellable functions such as @ref TEE_Wait and requests the
+ * cancellation of operations started with @ref TEE_OpenTASession or
+ * @ref TEE_InvokeTACommand. By default, tasks created to handle a TA entry
+ * point have cancellation masked, so that a TA does not have to cope with the
+ * effects of cancellation requests.
+ * @return 'true' if cancellations were masked prior to calling this function;
+ * 'false' otherwise
+ */
+bool TEE_UnmaskCancellation(void) {
+bool preState = sharedData.thisTaskMask;
+sharedData.thisTaskMask = false;
+return (preState ? true : false);
+}
+
+/**
+ * Masks the effects of cancellation
+ *
+ * The TEE_MaskCancellation function masks the effects of cancellation for the
+ * current task. When cancellation requests are masked, the Cancellation Flag
+ * does not have an effect on the cancellable functions and cannot be retrieved
+ * using @ref TEE_GetCancellationFlag. By default, tasks created to handle a TA
+ * entry point have cancellation masked, so that a TA does not have to cope with
+ * the effects of cancellation requests.
+ *
+ * @return 'true' if cancellations were masked prior to calling this function;
+ * 'false' otherwise
+ */
+bool TEE_MaskCancellation(void) {
+bool preState = sharedData.thisTaskMask;
+sharedData.thisTaskMask = true;
+return (preState ? true : false);
+}
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssf_malloc.c
- *
- * Description: SSF malloc functions
- *
- * Version: 1.0
- * Created: 23 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: krishna (Kr), k.devale@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include <tee_internal_api.h>
-#include <stdlib.h>
-#include <string.h>
-#include "ssf_lib.h"
-
-/*-----------------------------------------------------------------------------
- * Globals
- *-----------------------------------------------------------------------------*/
-/**
- * For use by: TEE_GetInstanceData and TEE_SetInstanceData
- */
-static void* globalTAInstanceData = 0;
-
-/*-----------------------------------------------------------------------------
- * TEE API implementation
- *-----------------------------------------------------------------------------*/
-/**
- * Allocates space for an object
- *
- * The TEE_Malloc function allocates space for an object whose size in bytes is
- * specified in the parameter size.
- *
- * @param[in] size The size of the buffer to be allocated.
- * @param[in] hint A hint to the allocator. Currently defined values are as
- * follows:
- *
- * + The default value, 0, guarantees that the returned block of memory is
- * filled with zeros.
- *
- * + Values in the range [0x00000001, 0x7FFFFFFF] are reserved for future
- * version of this specification.
- *
- * + Values in the range [0x80000000, 0xFFFFFFFF] can be used for
- * implementation-defined hints.
- *
- * @return Upon successful completion, with size not equal to zero, the function
- * returns a pointer to the allocated space. If the space cannot be allocated, a
- * NULL pointer is returned.
- */
-void* TEE_Malloc(size_t size, uint32_t hint) {
- void* buf = OsaMalloc(size);
- if (NULL == buf) {
- return NULL;
- }
- if (0 == hint) {
- memset(buf, 0, size);
- }
- return buf;
-}
-
-/**
- * Changes the size of the memory object
- *
- * The TEE_Realloc function changes the size of the memory object pointed to by
- * buffer to the size specified by nNewSize.
- *
- * @param[in] buffer: The pointer to the object to be reallocated
- * @param[in] newSize: The new size required for the object
- *
- * @return Upon successful completion, TEE_Realloc returns a pointer to the
- * (possibly moved) allocated space. If there is not enough available memory,
- * TEE_Realloc returns a NULL pointer.
- */
-void* TEE_Realloc(const void* buffer, uint32_t newSize) {
- return realloc((void*)buffer, newSize);
-}
-
-/**
- * Causes the space pointed to by buffer to be deallocated
- *
- * The TEE_Free function causes the space pointed to by buffer to be
- * deallocated; that is, made available for further allocation. If buffer is a
- * NULL pointer, TEE_Free does nothing. Otherwise, it is a Programmer Error
- * if the argument does not match a pointer previously returned by the
- * @ref TEE_Malloc or @ref TEE_Realloc, or if the space has been deallocated by
- * a call to TEE_Free or @ref TEE_Realloc.
- *
- * @param[in] buffer The pointer to the memory block to be freed
- */
-void TEE_Free(const void *buffer) {
- if (buffer) {
- OsaFree((void*)buffer);
- }
-}
-
-/**
- * Copies size bytes from one object to another
- *
- * The TEE_MemMove function copies size bytes from the object pointed to by src
- * into the object pointed to by dest. Note that the buffers dest and src can
- * reside in any kinds of memory, including shared memory.
- *
- * @param[in] dest A pointer to the destination buffer
- * @param[in] src A pointer to the source buffer
- * @param[in] size The number of bytes to be copied
- */
-void TEE_MemMove(void* dest, const void* src, uint32_t size) {
- memmove(dest, src, size);
-}
-
-/**
- * Compares bytes of one object to another
- *
- * The TEE_MemCompare function compares the first size bytes of the object
- * pointed to by buffer1 to the first size bytes of the object pointed to by
- * buffer2. Note that buffer1 and buffer2 can reside in any kinds of memory,
- * including shared memory.
- *
- * @param[in] buffer1 A pointer to the first buffer
- * @param[in] buffer2 A pointer to the second buffer
- * @param[in] size The number of bytes to be compared
- *
- * @return The sign of a non-zero return value is determined by the sign of the
- * difference between the values of the first pair of bytes (both interpreted as
- * type uint8_t) that differ in the objects being compared.
- *
- * + If the first byte that differs is higher in buffer1, then return an integer
- * greater than zero.
- *
- * + If the first size bytes of the two buffers are identical, then return zero.
- *
- * + If the first byte that differs is higher in buffer2, then return an integer
- * lower than zero.
- */
-int32_t TEE_MemCompare(const void *buffer1, const void *buffer2, uint32_t size) {
- uint32_t i = 0;
- uint8_t* buf1 = (uint8_t*)buffer1;
- uint8_t* buf2 = (uint8_t*)buffer2;
- for (; i < size; ++i) {
- if (buf1[i] > buf2[i]) {
- return 1;
- } else if (buf1[i] < buf2[i]) {
- return -1;
- }
- }
- return 0;
-}
-
-/**
- * Writes the byte x into the object
- *
- * The TEE_MemFill function writes the byte x (converted to a uint8_t) into the
- * first size bytes of the object pointed to by buffer. Note that buffer can
- * reside in any kinds of memory, including shared memory.
- *
- * @param[in] buffer A pointer to the destination buffer
- * @param[in] x The value to be set
- * @param[in] size The number of bytes to be set
- */
-void TEE_MemFill(void* buffer, uint32_t x, uint32_t size) {
- if (NULL == buffer) {
- return;
- }
- uint32_t i = 0;
- uint8_t* buf = (uint8_t*)buffer;
- for (; i < size; ++i) {
- buf[i] = (uint8_t)x;
- }
-}
-
-/**
- * Checks specified buffer for access rights
- *
- * The TEE_CheckMemoryAccessRights function causes the Implementation to examine
- * a buffer of memory specified in the parameters buffer and size and to
- * determine whether the current Trusted Application instance has the access
- * rights requested in the parameter accessFlags. If the characteristics of the
- * buffer are compatible with accessFlags, then the function returns
- * TEE_SUCCESS. Otherwise, it returns TEE_ERROR_ACCESS_DENIED. Note that the
- * buffer should not be accessed by the function, but the Implementation should
- * check the access rights based on the address of the buffer and internal
- * memory management information.
- * This function MUST NOT panic for any reason.
- *
- * @param[in] buffer Pointer to the buffer to check
- * @param[in] size Size of the buffer to check
- * @param[in] accessFlags The access flags to check
- *
- * @return TEE_SUCCESS: If the entire buffer allows the requested accesses or
- * TEE_ERROR_ACCESS_DENIED: If at least one byte in the buffer is not accessible
- * with the requested accesses
- */
-TEE_Result TEE_CheckMemoryAccessRights(uint32_t accessFlags, void* buffer,
- size_t size) {
- //TODO: Need to verify ow this function will be used
- return TEE_SUCCESS;
-}
-
-/**
- * Provides an alternative to writable global data
- *
- * The TEE_SetInstanceData and TEE_GetInstanceData functions provide an
- * alternative to writable global data (writable variables with global scope and
- * writable static variables with global or function scope). While an
- * Implementation supports C global variables, using these functions may be
- * sometimes more efficient, especially if only a single instance data variable
- * is required.
- *
- * @param[in] instanceData A pointer to the global Trusted Application instance
- * data. This pointer may be NULL.
- */
-void TEE_SetInstanceData(void* instanceData) {
- globalTAInstanceData = instanceData;
-}
-
-/**
- * Retrieves the instance data pointer
- *
- * The TEE_GetInstanceData function retrieves the instance data pointer set by
- * the Trusted Application using the @ref TEE_GetInstanceData function.
- *
- * @return The value returned is the previously set pointer to the Trusted
- * Application instance data, or NULre:\L if no instance data pointer has yet been
- * set.
- */
-void* TEE_GetInstanceData(void) {
- return globalTAInstanceData;
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssf_malloc.c
+ *
+ * Description: SSF malloc functions
+ *
+ * Version: 1.0
+ * Created: 23 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: krishna (Kr), k.devale@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include <tee_internal_api.h>
+#include <stdlib.h>
+#include <string.h>
+#include "ssf_lib.h"
+#include "../../TEEStub/TACommands/SharedMemoryMap.h"
+
+/*-----------------------------------------------------------------------------
+ * Globals
+ *-----------------------------------------------------------------------------*/
+/**
+ * For use by: TEE_GetInstanceData and TEE_SetInstanceData
+ */
+static void* globalTAInstanceData = 0;
+
+/*-----------------------------------------------------------------------------
+ * TEE API implementation
+ *-----------------------------------------------------------------------------*/
+/**
+ * Allocates space for an object
+ *
+ * The TEE_Malloc function allocates space for an object whose size in bytes is
+ * specified in the parameter size.
+ *
+ * @param[in] size The size of the buffer to be allocated.
+ * @param[in] hint A hint to the allocator. Currently defined values are as
+ * follows:
+ *
+ * + The default value, 0, guarantees that the returned block of memory is
+ * filled with zeros.
+ *
+ * + Values in the range [0x00000001, 0x7FFFFFFF] are reserved for future
+ * version of this specification.
+ *
+ * + Values in the range [0x80000000, 0xFFFFFFFF] can be used for
+ * implementation-defined hints.
+ *
+ * @return Upon successful completion, with size not equal to zero, the function
+ * returns a pointer to the allocated space. If the space cannot be allocated, a
+ * NULL pointer is returned.
+ */
+void* TEE_Malloc(size_t size, uint32_t hint) {
+ void* buf = newOnceSharedMemory(size);
+ if (buf == NULL) {
+ return NULL;
+ }
+ if (0 == hint) {
+ memset(buf, 0, size);
+ }
+ return buf;
+}
+
+/**
+ * Changes the size of the memory object
+ *
+ * The TEE_Realloc function changes the size of the memory object pointed to by
+ * buffer to the size specified by nNewSize.
+ *
+ * @param[in] buffer: The pointer to the object to be reallocated
+ * @param[in] newSize: The new size required for the object
+ *
+ * @return Upon successful completion, TEE_Realloc returns a pointer to the
+ * (possibly moved) allocated space. If there is not enough available memory,
+ * TEE_Realloc returns a NULL pointer.
+ */
+void* TEE_Realloc(const void* buffer, uint32_t newSize) {
+ if (NULL == buffer || 0 == newSize) {
+ return NULL;
+ }
+ void* newBuf = TEE_Malloc(newSize, 0);
+ if(newBuf != NULL) {
+ uint32_t copySize = 0;
+ uint32_t oriSize = getSharedMemorySize((void*)buffer);
+ if(oriSize != 0)
+ {
+ if(oriSize > newSize) copySize = newSize;
+ else copySize = oriSize;
+ TEE_MemMove(newBuf, buffer, copySize);
+ TEE_Free((void*)buffer);
+ return newBuf;
+ }
+ else TEE_Free(newBuf);
+ }
+ return NULL;
+}
+
+
+/**
+ * Causes the space pointed to by buffer to be deallocated
+ *
+ * The TEE_Free function causes the space pointed to by buffer to be
+ * deallocated; that is, made available for further allocation. If buffer is a
+ * NULL pointer, TEE_Free does nothing. Otherwise, it is a Programmer Error
+ * if the argument does not match a pointer previously returned by the
+ * @ref TEE_Malloc or @ref TEE_Realloc, or if the space has been deallocated by
+ * a call to TEE_Free or @ref TEE_Realloc.
+ *
+ * @param[in] buffer The pointer to the memory block to be freed
+ */
+void TEE_Free(const void *buffer) {
+ if (buffer) {
+ deleteOnceSharedMemory((void*)buffer);
+ }
+}
+
+/**
+ * Copies size bytes from one object to another
+ *
+ * The TEE_MemMove function copies size bytes from the object pointed to by src
+ * into the object pointed to by dest. Note that the buffers dest and src can
+ * reside in any kinds of memory, including shared memory.
+ *
+ * @param[in] dest A pointer to the destination buffer
+ * @param[in] src A pointer to the source buffer
+ * @param[in] size The number of bytes to be copied
+ */
+void TEE_MemMove(void* dest, const void* src, uint32_t size) {
+ memmove(dest, src, size);
+}
+
+/**
+ * Compares bytes of one object to another
+ *
+ * The TEE_MemCompare function compares the first size bytes of the object
+ * pointed to by buffer1 to the first size bytes of the object pointed to by
+ * buffer2. Note that buffer1 and buffer2 can reside in any kinds of memory,
+ * including shared memory.
+ *
+ * @param[in] buffer1 A pointer to the first buffer
+ * @param[in] buffer2 A pointer to the second buffer
+ * @param[in] size The number of bytes to be compared
+ *
+ * @return The sign of a non-zero return value is determined by the sign of the
+ * difference between the values of the first pair of bytes (both interpreted as
+ * type uint8_t) that differ in the objects being compared.
+ *
+ * + If the first byte that differs is higher in buffer1, then return an integer
+ * greater than zero.
+ *
+ * + If the first size bytes of the two buffers are identical, then return zero.
+ *
+ * + If the first byte that differs is higher in buffer2, then return an integer
+ * lower than zero.
+ */
+int32_t TEE_MemCompare(const void *buffer1, const void *buffer2, uint32_t size) {
+ uint32_t i = 0;
+ uint8_t* buf1 = (uint8_t*)buffer1;
+ uint8_t* buf2 = (uint8_t*)buffer2;
+ for (; i < size; ++i) {
+ if (buf1[i] > buf2[i]) {
+ return 1;
+ } else if (buf1[i] < buf2[i]) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+/**
+ * Writes the byte x into the object
+ *
+ * The TEE_MemFill function writes the byte x (converted to a uint8_t) into the
+ * first size bytes of the object pointed to by buffer. Note that buffer can
+ * reside in any kinds of memory, including shared memory.
+ *
+ * @param[in] buffer A pointer to the destination buffer
+ * @param[in] x The value to be set
+ * @param[in] size The number of bytes to be set
+ */
+void TEE_MemFill(void* buffer, uint32_t x, uint32_t size) {
+ if (NULL == buffer) {
+ return;
+ }
+ uint32_t i = 0;
+ uint8_t* buf = (uint8_t*)buffer;
+ for (; i < size; ++i) {
+ buf[i] = (uint8_t)x;
+ }
+}
+
+/**
+ * Checks specified buffer for access rights
+ *
+ * The TEE_CheckMemoryAccessRights function causes the Implementation to examine
+ * a buffer of memory specified in the parameters buffer and size and to
+ * determine whether the current Trusted Application instance has the access
+ * rights requested in the parameter accessFlags. If the characteristics of the
+ * buffer are compatible with accessFlags, then the function returns
+ * TEE_SUCCESS. Otherwise, it returns TEE_ERROR_ACCESS_DENIED. Note that the
+ * buffer should not be accessed by the function, but the Implementation should
+ * check the access rights based on the address of the buffer and internal
+ * memory management information.
+ * This function MUST NOT panic for any reason.
+ *
+ * @param[in] buffer Pointer to the buffer to check
+ * @param[in] size Size of the buffer to check
+ * @param[in] accessFlags The access flags to check
+ *
+ * @return TEE_SUCCESS: If the entire buffer allows the requested accesses or
+ * TEE_ERROR_ACCESS_DENIED: If at least one byte in the buffer is not accessible
+ * with the requested accesses
+ */
+TEE_Result TEE_CheckMemoryAccessRights(uint32_t accessFlags, void* buffer,
+ size_t size) {
+ //TODO: Need to verify ow this function will be used
+ return TEE_SUCCESS;
+}
+
+/**
+ * Provides an alternative to writable global data
+ *
+ * The TEE_SetInstanceData and TEE_GetInstanceData functions provide an
+ * alternative to writable global data (writable variables with global scope and
+ * writable static variables with global or function scope). While an
+ * Implementation supports C global variables, using these functions may be
+ * sometimes more efficient, especially if only a single instance data variable
+ * is required.
+ *
+ * @param[in] instanceData A pointer to the global Trusted Application instance
+ * data. This pointer may be NULL.
+ */
+void TEE_SetInstanceData(void* instanceData) {
+ globalTAInstanceData = instanceData;
+}
+
+/**
+ * Retrieves the instance data pointer
+ *
+ * The TEE_GetInstanceData function retrieves the instance data pointer set by
+ * the Trusted Application using the @ref TEE_GetInstanceData function.
+ *
+ * @return The value returned is the previously set pointer to the Trusted
+ * Application instance data, or NULre:\L if no instance data pointer has yet been
+ * set.
+ */
+void* TEE_GetInstanceData(void) {
+ return globalTAInstanceData;
+}
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssf_panic.c
- *
- * Description: SSF oanic functions
- *
- * Version: 1.0
- * Created: 23 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: krishna (Kr), k.devale@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include <tee_internal_api.h>
-#include "ssf_lib.h"
-#include "ssf_client.h"
-#include "tee_command.h"
-
-/* =========================================================================
- * PANIC
- * =========================================================================
- */
-/* Krishna Devale:
- * Options to implement panic and send back a signal to the execution logic of
- * TEEStub to clean up and exit
- * 1. Use pthread lock on a global variable "bool panic"
- * The TEEStub will wait on this lock for read/write access to global variable "panic"
- * When "panic" is detected as true in execution engine, TEEStub exits.
- * Here TEE_Panic allows the the called entry point to complete and exit
- * This behaviour may be not desirable. [Confirm this]
- *
- * 2. Use a callback function registered to SSFLib on its init.
- * This callback is defined in TEEStub. The TEE_Panic function calls the callback function.
- * This callback is expected to perform cleanup and do a clean exit.
- * This callback never returns to TEE_Panic. Thus, TEE_Panic is guaranteed to exit
- * without returning to its calling function
- */
-void TEE_Panic(TEE_Result panic_code) {
- exit(0);
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssf_panic.c
+ *
+ * Description: SSF oanic functions
+ *
+ * Version: 1.0
+ * Created: 23 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: krishna (Kr), k.devale@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include <tee_internal_api.h>
+#include "ssf_lib.h"
+#include "ssf_client.h"
+#include "tee_command.h"
+
+/* =========================================================================
+ * PANIC
+ * =========================================================================
+ */
+/* Krishna Devale:
+ * Options to implement panic and send back a signal to the execution logic of
+ * TEEStub to clean up and exit
+ * 1. Use pthread lock on a global variable "bool panic"
+ * The TEEStub will wait on this lock for read/write access to global variable "panic"
+ * When "panic" is detected as true in execution engine, TEEStub exits.
+ * Here TEE_Panic allows the the called entry point to complete and exit
+ * This behaviour may be not desirable. [Confirm this]
+ *
+ * 2. Use a callback function registered to SSFLib on its init.
+ * This callback is defined in TEEStub. The TEE_Panic function calls the callback function.
+ * This callback is expected to perform cleanup and do a clean exit.
+ * This callback never returns to TEE_Panic. Thus, TEE_Panic is guaranteed to exit
+ * without returning to its calling function
+ */
+void TEE_Panic(TEE_Result panic_code) {
+ exit(0);
+}
--- /dev/null
+/*
+ * ssf_permission.c
+ *
+ * This source file is proprietary property of Samsung Electronics Co., Ltd.
+ *
+ * Copyright (C) 2011 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ */
+
+#include <stdlib.h>
+#include <permission.h>
+#include <error.h>
+#include <log.h>
+
+int CheckPermission(const int flag) {
+ TEE_Result propertyResult;
+ uint32_t outValue;
+ propertyResult = TEE_GetPropertyAsU32((TEE_PropSetHandle)TEE_PROPSET_CURRENT_TA, "permission", &outValue);
+
+ if(propertyResult == TEE_SUCCESS) {
+ if(flag & outValue) {
+ return 0;
+ }
+ }
+
+ return TEE_ERROR_ACCESS_DENIED;
+}
+
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssf_storage.c
- *
- * Description: SSF storage functions
- *
- * Version: 1.0
- * Created: 23 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: krishna (Kr), k.devale@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include "ssf_storage.h"
-#include <sys/mman.h>
-#include <string.h>
-
-/*-----------------------------------------------------------------------------
- * MACROS
- *-----------------------------------------------------------------------------*/
-#define __FREE(buf) if(buf) {OsaFree(buf); buf = NULL;}
-#define FREE_PO(po) if(po) {clean_po_file(po);OsaFree(po); po = NULL;}
-
-#define PO_INTERNAL_MODULE_NAME "po_file"
-#define PO_STAT_INTERNAL_MODULE_NAME "po_stat"
-#define PI_FILE_NAME "pi_file"
-#define UUID_FILE "/usr/apps/tee/TA-UUID.list"
-
-TEE_UUID ssf_sharedthisTAUUID;
-static TEE_UUID this_uuid;
-static int uuid_got = 0;
-
-#define g_bTAdbug 1
-#define TZ_PRINT(fmt...) \
- do {if (g_bTAdbug) printf("[SSFLIB] ");printf(fmt);}while(0)
-#define TZ_ERROR(fmt...) \
- do {if (g_bTAdbug) printf("[SSFLIB] ");printf(fmt);}while(0)
-
-#if 0
-int get_ta_name(char* ta_name) {
- pid_t pid = getpid();
- char path[256] = {0};
- char ta_path[256] = {0};
- sprintf(path, "/proc/%d/exe", pid);
- int cnt = readlink(path, ta_path, 256);
- if (cnt < 0 || cnt > 256) {
- MSG("Error readlink.");
- return -1;
- }
- ta_path[cnt] = '\0';
- int idx = cnt - 1;
- for (; idx >= 0; idx--) {
- if (ta_path[idx] == '/') {
- strcpy(ta_name, ta_path + idx + 1);
- return 0;
- }
- }
- return -1;
-}
-#endif
-
-/*-----------------------------------------------------------------------------
- * Local functions
- *-----------------------------------------------------------------------------*/
-int get_uuid() {
-//assigns UIID obtained from TEEStub
- this_uuid = ssf_sharedthisTAUUID;
- uuid_got = 1;
- return 0;
-#if 0
- if (uuid_got)
- {
- return 0;
- }
- char ta_name[256] =
- { 0};
- if (0 != get_ta_name(ta_name))
- {
- MSG("Failed to get ta name.");
- return -1;
- }
- FILE* f = fopen(UUID_FILE, "r");
- if (!f)
- {
- MSG("Can't open file %s\n", UUID_FILE);
- return -1;
- }
- char name[256];
- char *line = NULL;
- size_t len = 0;
- ssize_t read_bytes;
- int matched = 0;
- TEE_UUID uuid;
- while (-1 != getline(&line, &len, f))
- {
- matched =
- sscanf(line,
- "TA={ %x , %hx , %hx , { %hhx , %hhx , %hhx , %hhx , %hhx , %hhx , %hhx , %hhx } } : %64s",
- &uuid.timeLow, &uuid.timeMid, &uuid.timeHiAndVersion,
- &uuid.clockSeqAndNode[0], &uuid.clockSeqAndNode[1],
- &uuid.clockSeqAndNode[2], &uuid.clockSeqAndNode[3],
- &uuid.clockSeqAndNode[4], &uuid.clockSeqAndNode[5],
- &uuid.clockSeqAndNode[6], &uuid.clockSeqAndNode[7],
- name);
- if (matched != 12 || matched == EOF)
- {
- MSG("bad format for uuid:%s\n", line);
- continue;
- }
- OsaFree(line);
- line = NULL;
- MSG("ta_name [%s] <=> name [%s]", ta_name, name);
- if (0 == memcmp(ta_name, name, strlen(ta_name)))
- {
- this_uuid = uuid;
- uuid_got = 1;
- fclose(f);
- return 0;
- }
- }
- fclose(f);
- return -1;
-#endif
-}
-
-void printhex(unsigned char* buf, unsigned int size) {
- MSG("---------------------------------------------------");
- unsigned int i;
- for (i = 0; i < size; ++i) {
- if (0 == (i % 16) && i) {
- printf("\n");
- }
- printf("%02x ", buf[i]);
- }
- MSG("\n---------------------------------------------------");
-}
-
-/*-----------------------------------------------------------------------------
- * TEE API implementation
- *-----------------------------------------------------------------------------*/
-////////////////////////////////////////////////////////////////////////////////////
-// internal attribute operations
-////////////////////////////////////////////////////////////////////////////////////
-TEE_Result copy_attribute(TEE_Attribute* dest, TEE_Attribute* src) {
- if (!dest || !src) {
- return TEE_ERROR_BAD_PARAMETERS;
- }
- dest->attributeID = src->attributeID;
- if (src->attributeID & TEE_ATTR_FLAG_VALUE) {
- dest->content.value.a = src->content.value.a;
- dest->content.value.b = src->content.value.b;
- } else {
- int buf_size = (src->content.ref.length + 7) / 8;
- void* buffer = OsaMalloc(buf_size);
- if (!buffer) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memcpy(buffer, src->content.ref.buffer, buf_size);
- dest->content.ref.buffer = buffer;
- dest->content.ref.length = src->content.ref.length;
- }
- return TEE_SUCCESS;
-}
-
-void free_attribute(TEE_Attribute* attr) {
- if (!attr) {
- return;
- }
- if (!(attr->attributeID & TEE_ATTR_FLAG_VALUE)) {
- OsaFree((void*)attr->content.ref.buffer);
- }
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-// Internal transient Object Operations
-/////////////////////////////////////////////////////////////////////////////////////////////
-TEE_Result allocate_transient_object(TransientObject* tr, uint32_t objectType,
- uint32_t maxObjectSize) {
- tr->attr.attr_number = 0;
-
-/* switch (objectType) {
- case TEE_TYPE_AES:
- if (maxObjectSize != 128 && maxObjectSize != 192
- && maxObjectSize != 256) {
- return TEE_ERROR_NOT_SUPPORTED;
- }
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_DES:
- //if (maxObjectSize != 64) {
- // return TEE_ERROR_NOT_SUPPORTED;
- //}
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_DES3:
- if (maxObjectSize != 128 && maxObjectSize != 192)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_HMAC_MD5:
- if (maxObjectSize < 64 || maxObjectSize > 512 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_HMAC_SHA1:
- if (maxObjectSize < 80 || maxObjectSize > 512 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_HMAC_SHA224:
- if (maxObjectSize < 112 || maxObjectSize > 512 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_HMAC_SHA256:
- if (maxObjectSize < 192 || maxObjectSize > 1024 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_HMAC_SHA384:
- if (maxObjectSize < 256 || maxObjectSize > 1024 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_HMAC_SHA512:
- if (maxObjectSize < 256 || maxObjectSize > 1024 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- case TEE_TYPE_RSA_PUBLIC_KEY:
- case TEE_TYPE_RSA_KEYPAIR:
- if (maxObjectSize < 256 || maxObjectSize > 3072)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = sizeof(rsa_context);
- break;
- case TEE_TYPE_DSA_PUBLIC_KEY:
- case TEE_TYPE_DSA_KEYPAIR:
- if (maxObjectSize < 512 || maxObjectSize > 1024 || maxObjectSize % 64)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = sizeof(dsa_context);
- break;
- case TEE_TYPE_DH_KEYPAIR:
- if (maxObjectSize < 256 || maxObjectSize > 2048)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = sizeof(dh_context);
- break;
- case TEE_TYPE_GENERIC_SECRET:
- if (maxObjectSize > 4096 || maxObjectSize % 8)
- return TEE_ERROR_NOT_SUPPORTED;
- //tr->attr.buf_len = (maxObjectSize + 7)>>3;
- break;
- default:
- return TEE_ERROR_NOT_SUPPORTED;
- }
-*/
- // Object info
- tr->info.objectType = objectType;
- tr->info.objectSize = 0;
- tr->info.maxObjectSize = maxObjectSize;
- //tr->info.dataSize = 0;
- //tr->info.dataPosition = 0;
- //tr->info.handleFlags = 0;
- tr->info.objectUsage = 0xffffffff;
- return TEE_SUCCESS;
-}
-
-size_t calc_attr_size(TransientObject* tr) {
- size_t size = 0;
- size += sizeof(int);
- size += tr->attr.attr_number * 4; //attrID
- TEE_Attribute* attrs = tr->attr.attr_array;
- int i;
- for (i = 0; i < tr->attr.attr_number; ++i) {
- if (attrs[i].attributeID & TEE_ATTR_FLAG_VALUE) {
- size += 2 * sizeof(uint32_t);
- } else {
- size += sizeof(size_t);
- size += (attrs[i].content.ref.length + 7) / 8;
- }
- }
- return size;
-}
-
-TEE_Result serialise_attr(TransientObject* tr, char* buf) {
- if (!buf) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memcpy(buf, (void*)&tr->attr.attr_number, sizeof(int));
- buf += sizeof(int);
-
- TEE_Attribute* attrs = tr->attr.attr_array;
- int i;
- for (i = 0; i < tr->attr.attr_number; ++i) {
- //AttrID
- memcpy(buf, &(attrs[i].attributeID), 4);
- buf += 4;
- if (attrs[i].attributeID & TEE_ATTR_FLAG_VALUE) {
- memcpy(buf, (void*)&(attrs[i].content.value.a), 2 * sizeof(uint32_t));
- buf += 2 * sizeof(uint32_t);
- } else {
- memcpy(buf, &(attrs[i].content.ref.length), 4);
- buf += 4;
- memcpy(buf, (void*)attrs[i].content.ref.buffer,
- (attrs[i].content.ref.length + 7) / 8);
- buf += (attrs[i].content.ref.length + 7) / 8;
- }
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result deserialise_attr(char* buf, TransientObject* tr) {
- if (!buf) {
- return TEE_SUCCESS;
- }
- TEE_Attribute* attrs = tr->attr.attr_array;
- memcpy(&tr->attr.attr_number, buf, sizeof(int));
- buf += sizeof(int);
-
- int i;
- for (i = 0; i < tr->attr.attr_number; ++i) {
- memcpy(&attrs[i].attributeID, buf, 4);
- buf += 4;
- if (attrs[i].attributeID & TEE_ATTR_FLAG_VALUE) {
- memcpy((void*)&(attrs[i].content.value.a), buf, 2 * sizeof(uint32_t));
- buf += 2 * sizeof(uint32_t);
- } else {
- memcpy((void*)&attrs[i].content.ref.length, buf, 4);
- buf += 4;
- void* buffer = OsaMalloc((attrs[i].content.ref.length + 7) / 8);
- if (!buffer) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memcpy(buffer, buf, (attrs[i].content.ref.length + 7) / 8);
- attrs[i].content.ref.buffer = buffer;
- buf += (attrs[i].content.ref.length + 7) / 8;
- }
- }
- return TEE_SUCCESS;
-}
-
-/////////////////////////////////////////////////////////////////////////////////////////////
-// Internal Persistent Object Operations
-/////////////////////////////////////////////////////////////////////////////////////////////
-
-TEE_Result allocate_persistent_object(persistent_object** po,
- uint32_t storageID, const void* objectID, size_t objectIDLen,
- uint32_t flags) {
- if (objectIDLen > TEE_OBJECT_ID_MAX_LEN) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (storageID != TEE_STORAGE_PRIVATE) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- persistent_object* tmp_po = (persistent_object*)OsaMalloc(
- sizeof(persistent_object));
- if (!tmp_po) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memset(tmp_po, 0, sizeof(persistent_object));
-
- tmp_po->storage_id = storageID;
- tmp_po->attr.info.handleFlags = flags;
- tmp_po->obj_id_len = objectIDLen;
- memcpy(tmp_po->object_id, objectID, objectIDLen);
- if (0 != get_uuid()) {
- MSG("Failed to get UUID of TA.");
- FREE_PO(tmp_po);
- return TEE_ERROR_GENERIC;
- }
- tmp_po->TA_UUID = this_uuid;
- *po = tmp_po;
- init_po(tmp_po);
- return TEE_SUCCESS;
-}
-
-TEE_Result create_po(persistent_object* po, TransientObject* attr,
- const void* init_data, size_t data_size) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- TEE_Result rc;
- if (NULL != attr) {
- if (!(attr->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- rc = allocate_transient_object(&po->attr, attr->info.objectType,
- attr->info.maxObjectSize);
- if (rc != TEE_SUCCESS) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- // copy attributes
-// TEE_CopyObjectAttributes((TEE_ObjectHandle) & po->attr,
-// (TEE_ObjectHandle) attr);
-
- TEE_CopyObjectAttributes((TEE_ObjectHandle)&po->attr.info,
- (TEE_ObjectHandle)attr);
-
- // get required buffer length
- po->po_file.attr_size = calc_attr_size(&po->attr);
- po->po_file.attr = (uint8_t*)OsaMalloc(po->po_file.attr_size);
- if (NULL == po->po_file.attr) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- // fill attr
- rc = serialise_attr(&po->attr, (char*)po->po_file.attr);
- if (rc) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- }
-
- // fill data object
- if (init_data && data_size) {
- po->po_file.obj_data_size = data_size;
- if (0 != po->po_file.obj_data_size) {
- po->po_file.object_data = (uint8_t*)OsaMalloc(po->po_file.obj_data_size);
- if (!po->po_file.object_data) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memcpy(po->po_file.object_data, init_data, po->po_file.obj_data_size);
- }
- }
-
- // init object info
- po->attr.info.dataPosition = 0;
- po->attr.info.dataSize = data_size;
- po->attr.info.handleFlags |= TEE_HANDLE_FLAG_PERSISTENT
- | TEE_HANDLE_FLAG_INITIALIZED;
- po->attr.info.objectUsage = 0xffffff;
- po->attr.info.objectSize =
- attr == TEE_HANDLE_NULL ? 0 : attr->info.objectSize;
-
- // write po file to ss
- po->po_file.po_info = po->attr.info;
- if (0 != write_po_file(po)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- memset(&g_po_info_file, 0, sizeof(po_info_file));
- // write to stat file.
- if (write_po_info(&g_po_info_file, po->object_id, po->obj_id_len,
- &po->attr.info)) {
- return TEE_ERROR_GENERIC;
- }
- // update po share info
- if (0 != update_share_info(&po->share_info, po->attr.info.handleFlags, 1)) {
- return TEE_ERROR_GENERIC;
- }
- // add to po list
- add_to_po_list(po);
- return TEE_SUCCESS;
-}
-
-TEE_Result open_po(persistent_object* po) {
- int handleFlages;
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- int ret = update_share_info(&po->share_info, po->attr.info.handleFlags, 1);
- if (0 != ret) {
- return (1 == ret) ? TEE_ERROR_ACCESS_CONFLICT : TEE_ERROR_GENERIC;
- }
- // read and parse
- ret = load_po_file(po);
- if (0 != ret) {
- ret = (1 == ret) ? TEE_ERROR_ITEM_NOT_FOUND : TEE_ERROR_GENERIC;
- goto out;
- }
- if (deserialise_attr((char*)po->po_file.attr, (TransientObject*)&po->attr)) {
- ret = TEE_ERROR_GENERIC;
- goto out;
- }
- handleFlages = po->attr.info.handleFlags | TEE_HANDLE_FLAG_PERSISTENT
- | TEE_HANDLE_FLAG_INITIALIZED;
- po->attr.info = po->po_file.po_info;
- po->attr.info.handleFlags = handleFlages;
- po->attr.info.dataPosition = 0;
- // add to po list
- add_to_po_list(po);
- ret = TEE_SUCCESS;
- out:
- if (ret) {
- update_share_info(&po->share_info, po->attr.info.handleFlags, 0);
- }
- return ret;
-}
-
-TEE_Result read_object_data(persistent_object* po, void* buffer, size_t size,
- uint32_t* count) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!buffer) {
- return TEE_ERROR_BAD_PARAMETERS;
- }
- if (0 == size || 0 == po->attr.info.dataSize) {
- *count = 0;
- return TEE_SUCCESS;
- }
- if (po->attr.info.dataPosition >= po->attr.info.dataSize) {
- return TEE_ERROR_OVERFLOW;
- }
- int cpsz =
- (po->attr.info.dataPosition + size >= po->attr.info.dataSize) ?
- (po->attr.info.dataSize - po->attr.info.dataPosition) : size;
-
- void* src = po->po_file.object_data + po->attr.info.dataPosition;
- memcpy(buffer, src, cpsz);
- //update object info
- po->attr.info.dataPosition += cpsz;
- *count = cpsz;
- return TEE_SUCCESS;
-}
-
-TEE_Result seek_object_data(persistent_object* po, int32_t offset,
- TEE_Whence whence) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- uint32_t begin_pos = 0;
- if (TEE_DATA_SEEK_CUR == whence) {
- begin_pos = po->attr.info.dataPosition;
- } else if (TEE_DATA_SEEK_END == whence) {
- begin_pos = po->attr.info.dataSize;
- }
- int32_t dataPos = begin_pos + offset;
- if ((uint32_t)dataPos >= TEE_DATA_MAX_POSITION) {
- return TEE_ERROR_OVERFLOW;
- }
- if (dataPos < 0) {
- dataPos = 0;
- }
- // Not support "hole" in file in this version.
- if ((uint32_t)dataPos > (po->attr.info.dataSize - 1)) {
- dataPos = po->attr.info.dataSize;
- }
- po->attr.info.dataPosition = dataPos;
- return TEE_SUCCESS;
-}
-
-TEE_Result write_object_data(persistent_object* po, const void* buffer,
- size_t size) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!buffer || !size) {
- return TEE_SUCCESS;
- }
- if (po->attr.info.dataPosition > po->attr.info.dataSize) {
- return TEE_ERROR_OVERFLOW;
- }
- uint32_t modified_size = po->attr.info.dataPosition + size;
- if (modified_size <= po->attr.info.dataSize) {
- memcpy(po->po_file.object_data + po->attr.info.dataPosition, buffer, size);
- } else {
- void* tmp_buf = OsaMalloc(modified_size);
- if (NULL == tmp_buf) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memcpy(tmp_buf, po->po_file.object_data, po->attr.info.dataPosition);
- memcpy((uint8_t*)tmp_buf + po->attr.info.dataPosition, buffer, size);
- OsaFree(po->po_file.object_data);
- po->po_file.object_data = (unsigned char*)tmp_buf;
- }
- //update object info
- po->attr.info.dataPosition += size;
- po->attr.info.dataSize =
- (modified_size > po->attr.info.dataSize) ? modified_size :
- po->attr.info.dataSize;
- // sync to ss.
- po->po_file.po_info.dataSize = po->attr.info.dataSize;
- if (-1 == write_po_file(po)) {
- MSG("Failed to write po file to secure storage.");
- return TEE_ERROR_GENERIC;
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result truncate_object_data(persistent_object* po, size_t size) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- // now not support the "hole" in file.
- size_t trunc_sz =
- po->attr.info.dataSize > size ? size : po->attr.info.dataSize;
- if (trunc_sz == po->attr.info.dataSize) {
- return TEE_SUCCESS;
- }
- po->attr.info.dataSize = trunc_sz;
- po->po_file.po_info.dataSize = trunc_sz;
- // write to ss
- if (-1 == write_po_file(po)) {
- return TEE_ERROR_GENERIC;
- }
- return TEE_SUCCESS;
-}
-
-void close_po(persistent_object* po) {
- if (NULL == po) {
- return;
- }
- update_share_info(&po->share_info, po->attr.info.handleFlags, 0);
-
- // remove from po list
- rem_from_po_list(po);
- // free online attributes
- TEE_Attribute* attrs = po->attr.attr.attr_array;
- int i;
- for (i = 0; i < po->attr.attr.attr_number; ++i) {
- free_attribute(&attrs[i]);
- }
- FREE_PO(po);
-}
-
-TEE_Result free_po(persistent_object* po) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (-1 == delete_po_file(po)) {
- return TEE_ERROR_GENERIC;
- }
- // free online attributes
- TEE_Attribute* attrs = po->attr.attr.attr_array;
- int i;
- for (i = 0; i < po->attr.attr.attr_number; ++i) {
- free_attribute(&attrs[i]);
- }
- // remove from po list
- rem_from_po_list(po);
- release_share_info(&po->share_info);
- FREE_PO(po);
- return TEE_SUCCESS;
-}
-
-TEE_Result rename_po(persistent_object* po, const void* newObjectID,
- size_t newObjectIDLen) {
- if (NULL == po) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (-1 == rename_po_file(po, newObjectID, newObjectIDLen)) {
- return TEE_ERROR_GENERIC;
- }
- memcpy(po->object_id, newObjectID, newObjectIDLen);
- po->obj_id_len = newObjectIDLen;
- return TEE_SUCCESS;
-}
-
-TEE_Result exist_po(persistent_object* po) {
- int ret = ss_validate(po->po_file.file_name, &po->po_file.cred,
- SS_OPT_DEFAULT);
- if (SS_RET_CANT_FIND_REQUESTED_DATA == ret) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- if (SS_RET_SUCCESS == ret) {
- return TEE_SUCCESS;
- }
- return TEE_ERROR_GENERIC;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// Persistent file operations
-////////////////////////////////////////////////////////////////////////////////////
-void init_po(persistent_object* po) {
- char uuid[64] = {0};
- convert_TA_UUID(uuid, po->TA_UUID);
- MSG("UUID of the TA is %s.", uuid);
- ss_set_credential(&po->po_file.cred, uuid, PO_INTERNAL_MODULE_NAME, 1, 0);
-
- //derive file name
- derive_po_file_name((void*)po->object_id, po->obj_id_len,
- po->po_file.file_name);
- po->po_file.attr = NULL;
- po->po_file.attr_size = 0;
- po->po_file.object_data = NULL;
- po->po_file.obj_data_size = 0;
- // init po_share_info
- po->share_info.fd = -1;
- po->share_info.usr_info = NULL;
- memcpy(po->share_info.name, po->po_file.file_name, PO_FILE_NAME_MAX_LEN);
- po->po_list.prev = NULL;
- po->po_list.next = NULL;
- po->po_list.po = po;
- regist_clean_up();
-}
-
-int derive_po_file_name(const void* obj_id, int obj_id_len, char* fn) {
- byte_to_hex((unsigned char*)fn, (unsigned char*)obj_id, obj_id_len);
- fn[2 * obj_id_len] = '\0';
- return 0;
-}
-
-int load_po_file(persistent_object* po) {
- uint8_t* retbuf = NULL;
- uint8_t* tmp_ptr = NULL;
- uint32_t read_size = 0;
- int ret = ss_read(&retbuf, &read_size, 0, po->po_file.file_name,
- &po->po_file.cred, SS_OPT_DEFAULT);
- if (SS_RET_CANT_FIND_REQUESTED_DATA == ret) {
- MSG("Po file not exist.");
- return 1;
- }
- if (SS_RET_SUCCESS != ret) {
- MSG("Failed to read data from secure storage, ret = %d.", ret);
- return -1;
- }
- tmp_ptr = retbuf;
-
- // load po info
- memcpy(&po->po_file.po_info, tmp_ptr, sizeof(TEE_ObjectInfo));
- tmp_ptr += sizeof(TEE_ObjectInfo);
- // load attr
- size_t attr_size = read_size - sizeof(TEE_ObjectInfo)
- - po->po_file.po_info.dataSize;
- po->po_file.attr_size = attr_size;
- if (0 < po->po_file.attr_size) {
- po->po_file.attr = (unsigned char*)OsaMalloc(attr_size);
- memcpy(po->po_file.attr, tmp_ptr, attr_size);
- }
- tmp_ptr += attr_size;
-
- // load object data
- po->po_file.obj_data_size = po->po_file.po_info.dataSize;
- if (0 < po->po_file.obj_data_size) {
- po->po_file.object_data = (unsigned char*)OsaMalloc(
- po->po_file.obj_data_size);
- memcpy(po->po_file.object_data, tmp_ptr, po->po_file.obj_data_size);
- }
- ss_free_buffer(retbuf);
- return 0;
-}
-
-int write_po_file(persistent_object* po) {
- uint8_t* buf = NULL;
- po->po_file.obj_data_size = po->attr.info.dataSize;
- uint32_t buf_size = po->po_file.attr_size + po->po_file.obj_data_size
- + sizeof(TEE_ObjectInfo);
- buf = (unsigned char*)OsaMalloc(buf_size);
- if (NULL == buf) {
- MSG("Failed to allocate memory.");
- OsaFree(buf);
- return -1;
- }
- uint8_t* tmp_buf = buf;
-
- // po_info
- memcpy(tmp_buf, &po->po_file.po_info, sizeof(TEE_ObjectInfo));
- tmp_buf += sizeof(TEE_ObjectInfo);
- // attr
- memcpy(tmp_buf, (void*)po->po_file.attr, po->po_file.attr_size);
- tmp_buf += po->po_file.attr_size;
- // object data
- memcpy(tmp_buf, (void*)po->po_file.object_data, po->po_file.obj_data_size);
- int ret = ss_write(buf, buf_size, 0, po->po_file.file_name, &po->po_file.cred,
- SS_OPT_DEFAULT);
- if (SS_RET_SUCCESS != ret) {
- MSG("Failed to write data to securestorage, ret = %d.", ret);
- OsaFree(buf);
- return -1;
- }
- OsaFree(buf);
- return 0;
-}
-
-int rename_po_file(persistent_object* po, const void* newObjectID,
- size_t newObjectIDLen) {
- // first delete old file
- if (-1 == delete_po_file(po)) {
- MSG("Failed to delete old po file.");
- return -1;
- }
- derive_po_file_name(newObjectID, newObjectIDLen, po->po_file.file_name);
- if (0 != write_po_file(po)) {
- MSG("Failed to write po file.");
- return -1;
- }
- write_po_info(&g_po_info_file, newObjectID, newObjectIDLen, &po->attr.info);
- return 0;
-}
-
-void clean_po_file(persistent_object* po) {
- if (!po) {
- return;
- }
- __FREE(po->po_file.attr);
- __FREE(po->po_file.object_data);
-}
-
-int delete_po_file(persistent_object* po) {
- int ret = ss_delete(po->po_file.file_name, &po->po_file.cred, SS_OPT_DEFAULT);
- if (SS_RET_SUCCESS != ret) {
- MSG("Failed to delete data from secure storage. ret = %d.", ret);
- return -1;
- }
- ret = delete_po_info(&g_po_info_file, po->object_id, po->obj_id_len);
- if (-1 == ret) {
- MSG("Failed to delete po info.");
- return -1;
- }
- return 0;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// misc operations
-////////////////////////////////////////////////////////////////////////////////////
-po_info_file g_po_info_file;
-
-int init_po_info_file(po_info_file* pi_file) {
- if (pi_file->b_inited) {
- return 0;
- }
- TEE_UUID tmp_uuid;
- if (0 != get_uuid()) {
- MSG("Failed to get UUID of TA.");
- return -1;
- }
- tmp_uuid = this_uuid;
- char uuid[64] = {0};
- convert_TA_UUID(uuid, tmp_uuid);
- ss_set_credential(&pi_file->cred, uuid, PO_INTERNAL_MODULE_NAME, 1, 0);
- uint32_t fn_sz = strlen(PI_FILE_NAME);
- memcpy(pi_file->filename, PI_FILE_NAME, fn_sz);
- pi_file->filename[fn_sz] = '\0';
- pi_file->b_inited = 1;
- return 0;
-}
-
-int load_po_info_file(po_info_file* pi_file) {
- if (init_po_info_file(pi_file)) {
- return -1;
- }
- uint8_t* ret_buf = NULL;
- uint32_t read_sz = 0;
- int ret = ss_read(&ret_buf, &read_sz, 0, pi_file->filename, &pi_file->cred,
- SS_OPT_DEFAULT);
- if (SS_RET_CANT_FIND_REQUESTED_DATA == ret) {
- pi_file->po_num = 0;
- return 0;
- }
- if (SS_RET_SUCCESS != ret) {
- MSG("Failed to read from secure storage, ret = %d.", ret);
- return -1;
- }
- if (0 == read_sz) {
- pi_file->po_num = 0;
- return 0;
- }
- uint32_t po_info_sz = sizeof(persistent_object_info);
- if (read_sz % po_info_sz) {
- MSG("po_info file data error.");
- ss_free_buffer(ret_buf);
- return -1;
- }
- pi_file->po_num = read_sz / po_info_sz;
- pi_file->po_info = (persistent_object_info*)ret_buf;
- return 0;
-}
-
-int get_po_info(po_info_file* pi_file, persistent_object_info** po_info,
- int* po_num) {
- if (-1 == load_po_info_file(pi_file)) {
- return -1;
- }
- if (0 == pi_file->po_num) {
- *po_num = 0;
- return 0;
- }
- persistent_object_info* tmp_info = NULL;
- tmp_info = (persistent_object_info*)OsaMalloc(
- pi_file->po_num * sizeof(persistent_object_info));
- if (NULL == tmp_info) {
- MSG("Failed to alloc memory.");
- __FREE(pi_file->po_info);
- return -1;
- }
- int32_t i = 0;
- persistent_object_info* tmp_po_info = pi_file->po_info;
- for (; i < pi_file->po_num; ++i) {
- tmp_info[i] = *tmp_po_info;
- tmp_po_info++;
- }
- *po_num = pi_file->po_num;
- *po_info = tmp_info;
- __FREE(pi_file->po_info);
- return 0;
-}
-
-int write_po_info(po_info_file* pi_file, const void* objectID,
- uint32_t obj_id_len, TEE_ObjectInfo* info) {
- if (-1 == load_po_info_file(pi_file)) {
- return -1;
- }
- persistent_object_info po_info;
- memcpy((void*)po_info.object_id, objectID, obj_id_len);
- po_info.obj_id_len = obj_id_len;
- po_info.info = *info;
- persistent_object_info* po_infos = NULL;
- uint32_t po_info_sz = sizeof(persistent_object_info);
- po_infos = (persistent_object_info*)OsaMalloc(
- (pi_file->po_num + 1) * po_info_sz);
- uint32_t po_num = pi_file->po_num;
-
- memcpy((void*)po_infos, (void*)pi_file->po_info, po_num * po_info_sz);
- memcpy((uint8_t*)po_infos + po_num * po_info_sz, (void*)&po_info, po_info_sz);
-
- pi_file->po_num += 1;
- __FREE(pi_file->po_info);
- int ret = ss_write((uint8_t*)po_infos, po_info_sz * pi_file->po_num, 0,
- pi_file->filename, &pi_file->cred, SS_OPT_DEFAULT);
- if (SS_RET_SUCCESS != ret) {
- MSG("Failed to write po stat to secure storage,ret = %d.", ret);
- __FREE(po_infos);
- return -1;
- }
- __FREE(po_infos);
- return 0;
-}
-
-int delete_po_info(po_info_file* pi_file, const void* objectID,
- uint32_t obj_id_len) {
- persistent_object_info* po_del = NULL;
-
- if (-1 == load_po_info_file(pi_file)) {
- return -1;
- }
- uint32_t po_info_sz = sizeof(persistent_object_info);
- po_del = find_po_info(pi_file, objectID, obj_id_len);
- if (NULL == po_del) {
- MSG("po info to del not found.");
- return 0;
- }
- uint8_t* po_del_pos = (uint8_t*)po_del;
- uint8_t* cp_begin = po_del_pos + po_info_sz;
- uint32_t cp_sz = po_info_sz * pi_file->po_num
- - (cp_begin - (uint8_t*)pi_file->po_info);
-
- memcpy(po_del_pos, cp_begin, cp_sz);
- pi_file->po_num--;
- int ret = ss_write((uint8_t*)pi_file->po_info, po_info_sz * pi_file->po_num,
- 0, pi_file->filename, &pi_file->cred, SS_OPT_DEFAULT);
- if (SS_RET_SUCCESS != ret) {
- MSG("Failed to write po stat to secure storage,ret = %d.", ret);
- __FREE(pi_file->po_info);
- return -1;
- }
- __FREE(pi_file->po_info);
- return 0;
-}
-
-persistent_object_info* find_po_info(po_info_file* pi_file,
- const void* objectID, uint32_t obj_id_len) {
- if (NULL == objectID || 0 == obj_id_len) {
- MSG("objectID is invalid.");
- return NULL;
- }
- int32_t i = 0;
- int b_find = 0;
- persistent_object_info* po_info_tmp = pi_file->po_info;
- for (; i < pi_file->po_num; ++i) {
- if (0 == memcmp(po_info_tmp->object_id, objectID, obj_id_len)) {
- b_find = 1;
- break;
- }
- po_info_tmp++;
- }
- return (b_find ? po_info_tmp : NULL);
-}
-
-// po share rule
-// TODO: locking mechanism to be improved using pthread locks ORr
-// As ssflib is shared lib, instead of malloc'ing the share_info,
-// just use a global variable, there by no need of locking
-void lock_po_share_info(po_share_info* share_info) {
- while (share_info->usr_info->lock) {
- }
- share_info->usr_info->lock = 1;
-}
-
-void unlock_po_share_info(po_share_info* share_info) {
- if (share_info->usr_info->lock) {
- share_info->usr_info->lock = 0;
- }
-}
-
-int init_share_info(po_share_info* share_info) {
- if (NULL != share_info->usr_info) {
- MSG("Share info has been inited.");
- return 0;
- }
- // is the shm exist
- share_info->usr_info = (po_user*)OsaMalloc(sizeof(po_user));
- memset(share_info->usr_info, 0, sizeof(po_user));
-#if 0
- int b_shm_exist = 1;
- if (0 > shm_open(share_info->name, O_EXCL | O_CREAT, 0666))
- {
- b_shm_exist = 1;
- }
- share_info->fd = shm_open(share_info->name, O_RDWR | O_CREAT, 0666);
- if (0 > share_info->fd)
- {
- MSG("Failed to open shm %s.", share_info->name);
- return -1;
- }
- // linux posix shm need this
- if (!b_shm_exist)
- {
- ftruncate(share_info->fd, sizeof(po_user));
- }
- share_info->usr_info = (po_user*) mmap(NULL, sizeof(po_user),
- PROT_READ | PROT_WRITE, MAP_SHARED, share_info->fd, 0);
- if (share_info->usr_info == (void *) 0xFFFFFFFF)
- {
- MSG("Failed to mmap shm.");
- return -1;
- }
- if (!b_shm_exist)
- {
- share_info->usr_info->lock = 0;
- memset(share_info->usr_info, 0, sizeof(po_user));
- }
-#endif
- return 0;
-}
-
-int check_share_rule(po_share_info* share_info, uint32_t handleFlags) {
- if ((NULL == share_info) || (-1 == init_share_info(share_info))) {
- return -1;
- }
- int ret = 0;
- // no user
- if ((0 == share_info->usr_info->x_user)
- && (0 == share_info->usr_info->rs_user)
- && (0 == share_info->usr_info->ws_user)
- && (0 == share_info->usr_info->rws_user)) {
- goto out;
- }
- if (handleFlags & TEE_DATA_FLAG_ACCESS_READ) {
- if (!((handleFlags & TEE_DATA_FLAG_SHARE_READ)
- && (0 == share_info->usr_info->x_user)
- && (0 == share_info->usr_info->ws_user))) {
- ret = -1;
- goto out;
- }
- }
- if (handleFlags & TEE_DATA_FLAG_ACCESS_WRITE) {
- if (!((handleFlags & TEE_DATA_FLAG_SHARE_WRITE)
- && (0 == share_info->usr_info->x_user)
- && (0 == share_info->usr_info->rs_user))) {
- ret = -1;
- goto out;
- }
- }
- if (handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META) {
- if (!((0 == share_info->usr_info->x_user)
- && (0 == share_info->usr_info->rs_user)
- && (0 == share_info->usr_info->ws_user)
- && (0 == share_info->usr_info->rws_user))) {
- ret = -1;
- }
- }
- out: return ret;
-}
-
-int update_share_info(po_share_info* share_info, uint32_t handleFlags,
- int b_open) {
- if (NULL == share_info->usr_info) {
- if (-1 == init_share_info(share_info)) {
- return -1;
- }
- }
- // lock
- // TODO: Commented for debugging, to be uncommented
- lock_po_share_info(share_info);
- int ret = 0;
- if (b_open) {
- if (check_share_rule(share_info, handleFlags)) {
- MSG("Access conflict!");
- ret = 1;
- goto out;
- }
- }
- handleFlags &= ~TEE_DATA_FLAG_ACCESS_READ;
- handleFlags &= ~TEE_DATA_FLAG_ACCESS_WRITE;
- handleFlags &= ~TEE_HANDLE_FLAG_PERSISTENT;
- handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED;
-
- if ((handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META)
- || (handleFlags & TEE_DATA_FLAG_EXCLUSIVE) || (0 == handleFlags)) {
- b_open ? share_info->usr_info->x_user++ : share_info->usr_info->x_user--;
- goto out;
- }
- if ((handleFlags & TEE_DATA_FLAG_SHARE_READ)
- && (handleFlags & TEE_DATA_FLAG_SHARE_WRITE)) {
- b_open ? share_info->usr_info->rws_user++ :
- share_info->usr_info->rws_user--;
- goto out;
- }
- if (handleFlags & TEE_DATA_FLAG_SHARE_READ) {
- b_open ? share_info->usr_info->rs_user++ : share_info->usr_info->rs_user--;
- goto out;
- }
- if (handleFlags & TEE_DATA_FLAG_SHARE_WRITE) {
- b_open ? share_info->usr_info->ws_user++ : share_info->usr_info->ws_user--;
- goto out;
- }
- out:
-
- if ((0 == share_info->usr_info->x_user)
- && (0 == share_info->usr_info->rs_user)
- && (0 == share_info->usr_info->ws_user)
- && (0 == share_info->usr_info->rws_user)) {
- release_share_info(share_info);
- }
- unlock_po_share_info(share_info);
- return ret;
-}
-
-int release_share_info(po_share_info* share_info) {
-#if 0
- if ((NULL == share_info) || (0 > share_info->fd))
- {
- MSG("Share info has been inited.");
- return 0;
- }
- shm_unlink(share_info->name);
-#endif
- OsaFree(share_info->usr_info);
- return 0;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// misc operations
-////////////////////////////////////////////////////////////////////////////////////
-void byte_to_hex(uint8_t* dest, const uint8_t* src, unsigned long src_len) {
- char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
- 'c', 'd', 'e', 'f'};
-
- unsigned long j;
- for (j = 0; j < src_len; j++) {
- dest[j * 2] = hexval[((src[j] >> 4) & 0xF)];
- dest[(j * 2) + 1] = hexval[(src[j]) & 0x0F];
- }
-}
-
-void convert_TA_UUID(char* uuid, TEE_UUID TA_UUID) {
- // In its canonical form, a UUID consists of 32 hexadecimal digits, displayed in 5 groups separated by hyphens,
- // in the form 8-4-4-4-12 for a total of 36 characters(32 digits and 4 '-'). For example:
- // 550e8400-e29b-41d4-a716-446655440000
- // Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number as well
- // as two reserved bits. All other bits are set using a random or pseudorandom data source.
- // Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx with hexadecimal digits x and hexadecimal
- // digits 8, 9, A, or B for y. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.
-
- char* tmp = uuid;
-
- snprintf(tmp, 9, "%08x", TA_UUID.timeLow);
- tmp[8] = '-';
- tmp += 9;
- snprintf(tmp, 5, "%04x", TA_UUID.timeMid);
- tmp[4] = '-';
- tmp += 5;
- snprintf(tmp, 5, "%04x", TA_UUID.timeHiAndVersion);
- tmp[4] = '-';
- tmp += 5;
- uint32_t i = 0;
- for (; i < 2; ++i) {
- snprintf(tmp, 3,"%02x", TA_UUID.clockSeqAndNode[i]);
- tmp += 2;
- }
- tmp[0] = '-';
-
- tmp += 1;
- for (; i < 8; ++i) {
- snprintf(tmp, 3, "%02x", TA_UUID.clockSeqAndNode[i]);
- tmp += 2;
- }
- MSG("this_uuid : %s ", uuid);
-}
-
-int gen_random(uint8_t* dest, uint8_t data_len) {
- UCI_HANDLE uh = UCI_ERROR;
- uh = uci_context_alloc(ID_UCI_X931, UCI_SW_CRYPTOCORE);
- if (uh == UCI_ERROR || uh == UCI_MEM_ALLOR_ERROR) {
- return -1;
- }
- unsigned char seed[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
- 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
- int ret = uci_prng_seed(uh, seed);
- if (ret != UCI_SUCCESS) {
- goto out;
- }
- ret = uci_prng_get(uh, data_len * 8, dest);
- if (ret != UCI_SUCCESS) {
- goto out;
- }
- out: uci_context_free(uh);
- return ret;
-}
-
-// persistent object list operations
-po_list_node g_po_list = {NULL, NULL, NULL};
-
-void debug_list() {
- po_list_node* node = g_po_list.next;
- while (node != NULL) {
- MSG("PO [%s] ==>", node->po->po_file.file_name);
- node = node->next;
- }
-}
-
-void add_to_po_list(persistent_object* po) {
- if (NULL == po) {
- return;
- }
- po->po_list.po = po;
- // first po
- if (NULL == g_po_list.next) {
- g_po_list.next = &po->po_list;
- po->po_list.prev = &g_po_list;
- po->po_list.next = NULL;
- } else {
- g_po_list.next->prev = &po->po_list;
- po->po_list.next = g_po_list.next;
- po->po_list.prev = &g_po_list;
- g_po_list.next = &po->po_list;
- }
- MSG("=====PO %s added=====", po->po_file.file_name);
- //debug_list();
-}
-
-void rem_from_po_list(persistent_object* po) {
- if (NULL == po) {
- return;
- }
- MSG("=====To remove PO %s=====", po->po_file.file_name);
- //debug_list();
- if (po->po_list.prev) {
- po->po_list.prev->next = po->po_list.next;
- }
- if (po->po_list.next) {
- po->po_list.next->prev = po->po_list.prev;
- }
- MSG("======PO removed=====");
- //debug_list();
-}
-
-void cleanup(void) {
- po_list_node* node = g_po_list.next;
- while (NULL != node) {
- TEE_CloseObject((TEE_ObjectHandle)node->po);
- node = node->next;
- }
-}
-
-void regist_clean_up() {
- static int b_reg = 0;
- if (b_reg) {
- return;
- }
- if (0 == atexit(cleanup)) {
- b_reg = 1;
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// object general operations
-////////////////////////////////////////////////////////////////////////////////////
-void TEE_GetObjectInfo(TEE_ObjectHandle object, TEE_ObjectInfo* objectInfo) {
- if (objectInfo) {
- objectInfo->objectType = object->tr.info.objectType;
- objectInfo->objectSize = object->tr.info.objectSize;
- objectInfo->maxObjectSize = object->tr.info.maxObjectSize;
- objectInfo->objectUsage = object->tr.info.objectUsage;
- objectInfo->dataSize = object->tr.info.dataSize;
- objectInfo->dataPosition = object->tr.info.dataPosition;
- objectInfo->handleFlags = object->tr.info.handleFlags;
- }
-}
-
-// usage ??
-void TEE_RestrictObjectUsage(TEE_ObjectHandle object, uint32_t objectUsage) {
- object->tr.info.objectUsage &= objectUsage;
-}
-
-TEE_Result TEE_GetObjectBufferAttribute(TEE_ObjectHandle object,
- uint32_t attributeID, void* buffer, size_t* size) {
- uint32_t len;
- int i, n = -1;
- TransientObject * obj = &object->tr;
-
- if (!(obj->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- // search for attributeID in attr_array
- for (i = 0; i < obj->attr.attr_number; i++) {
- if (obj->attr.attr_array[i].attributeID == attributeID) {
- n = i;
- break;
- }
- }
- if (n == -1) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- // bit[29] == 1 -> not a buffer attribute
- if (attributeID & TEE_ATTR_FLAG_VALUE) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- // protected attribute
- if (!(attributeID & TEE_ATTR_FLAG_PUBLIC)
- && !(obj->info.objectUsage & TEE_USAGE_EXTRACTABLE)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- //len = ((obj->attr.attr_array[n].content.ref.length & 0x7FFFFFFF) + 7) >> 3 ;
- len = (obj->attr.attr_array[n].content.ref.length + 7) >> 3;
-
- // out buffer is too small
- if (len > *size) {
- return TEE_ERROR_SHORT_BUFFER;
- }
- memcpy(buffer, obj->attr.attr_array[n].content.ref.buffer, len);
- *size = len;
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_GetObjectValueAttribute(TEE_ObjectHandle object,
- uint32_t attributeID, uint32_t* a, uint32_t* b) {
- int i, n = -1;
- TransientObject * obj = &object->tr;
-
- if (!(obj->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- // search for attributeID in attr_array
- for (i = 0; i < obj->attr.attr_number; i++) {
- if (obj->attr.attr_array[i].attributeID == attributeID) {
- n = i;
- break;
- }
- }
- if (n == -1) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- // bit[29] == 0 -> not a value attribute
- if (!(attributeID & TEE_ATTR_FLAG_VALUE)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- // protected attribute
- if (!(attributeID & TEE_ATTR_FLAG_PUBLIC)
- && !(obj->info.objectUsage & TEE_USAGE_EXTRACTABLE)) {
- return TEE_ERROR_ACCESS_DENIED;
- }
- if (a) {
- *a = obj->attr.attr_array[i].content.value.a;
- }
- if (b) {
- *b = obj->attr.attr_array[i].content.value.b;
- }
- return TEE_SUCCESS;
-}
-
-void TEE_CloseObject(TEE_ObjectHandle object) {
- if (object == TEE_HANDLE_NULL) {
- return;
- }
- if (object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) // persistent object
- {
- persistent_object *po = (persistent_object*)object;
- close_po(po);
- } else {
- TEE_FreeTransientObject(object);
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// Transient Object operations
-////////////////////////////////////////////////////////////////////////////////////
-TEE_Result TEE_AllocateTransientObject(uint32_t objectType,
- uint32_t maxObjectSize, TEE_ObjectHandle* object) {
- TEE_Result rc;
-
-
- TransientObject * tr = (TransientObject*)OsaMalloc(sizeof(TransientObject));
- if (!tr) {
- OsaFree(tr);
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- memset(tr, 0, sizeof(TransientObject));
- rc = allocate_transient_object(tr, objectType, maxObjectSize);
- if (rc != TEE_SUCCESS) {
- OsaFree(tr);
- return rc;
- }
- *object = (TEE_ObjectHandle)&tr->info;
- OsaFree(tr);
- return TEE_SUCCESS;
-}
-
-void TEE_FreeTransientObject(TEE_ObjectHandle object) {
- TransientObject * tr = NULL;
-
- if (object == TEE_HANDLE_NULL) {
- return;
- }
- tr = &object->tr;
- TEE_Attribute* attrs = tr->attr.attr_array;
- int i;
- for (i = 0; i < tr->attr.attr_number; ++i) {
- free_attribute(&attrs[i]);
- }
- memset(&tr->attr, 0, sizeof(tr->attr));
- OsaFree(tr);
-}
-
-void TEE_ResetTransientObject(TEE_ObjectHandle object) {
- TransientObject* tr;
-
- if (object == TEE_HANDLE_NULL) {
- return;
- }
- tr = &object->tr;
- TEE_Attribute* attrs = tr->attr.attr_array;
- int i;
- for (i = 0; i < tr->attr.attr_number; ++i) {
- free_attribute(&attrs[i]);
- }
- memset(tr->attr.attr_array, 0, sizeof(tr->attr.attr_array));
- tr->attr.attr_number = 0;
-
- tr->info.objectSize = 0;
- tr->info.dataSize = 0;
- tr->info.dataPosition = 0;
- tr->info.handleFlags = 0;
- tr->info.objectUsage = 0xffffffff;
-}
-
-TEE_Result TEE_PopulateTransientObject(TEE_ObjectHandle object,
- const TEE_Attribute* attrs, uint32_t attrCount) {
- unsigned int i;
-
- TransientObject* tr = &object->tr;
- if (tr->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- TEE_Attribute* curr_attr = &tr->attr.attr_array[tr->attr.attr_number];
- for (i = 0; i < attrCount; i++) {
-
- if (attrs[i].content.ref.length > tr->info.maxObjectSize) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- copy_attribute(&curr_attr[i], (TEE_Attribute*)&attrs[i]);
- tr->attr.attr_number++;
- tr->info.objectSize =
- tr->info.objectSize > attrs[i].content.ref.length ?
- tr->info.objectSize : attrs[i].content.ref.length;
- }
-
- switch (tr->info.objectType) {
- case TEE_TYPE_AES:
- case TEE_TYPE_DES:
- case TEE_TYPE_DES3:
- case TEE_TYPE_HMAC_MD5:
- case TEE_TYPE_HMAC_SHA1:
- case TEE_TYPE_HMAC_SHA224:
- case TEE_TYPE_HMAC_SHA256:
- case TEE_TYPE_HMAC_SHA384:
- case TEE_TYPE_HMAC_SHA512:
- case TEE_TYPE_GENERIC_SECRET:
- if (tr->attr.attr_number != 1) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- break;
- case TEE_TYPE_RSA_PUBLIC_KEY:
- case TEE_TYPE_RSA_KEYPAIR: {
- // Krishna: Incorrect to check this condition
- /*if ((tr->info.objectType == TEE_TYPE_RSA_KEYPAIR)
- && (tr->attr.attr_number != 3) && (tr->attr.attr_number != 8)) {
- TZ_ERROR("tr->attr.attr_number = %d\n", tr->attr.attr_number);
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }*/
- if ((tr->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY)
- && (tr->attr.attr_number != 2)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- }
- break;
- case TEE_TYPE_DSA_PUBLIC_KEY:
- case TEE_TYPE_DSA_KEYPAIR: {
- if ((tr->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY)
- && (tr->attr.attr_number != 4)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- } else if ((tr->info.objectType == TEE_TYPE_DSA_KEYPAIR)
- && (tr->attr.attr_number != 5)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- }
- break;
- case TEE_TYPE_DH_KEYPAIR: {
- if ((tr->attr.attr_number != 3) && (tr->attr.attr_number != 4)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- }
- break;
- default:
- return TEE_ERROR_BAD_PARAMETERS;
- }
- tr->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
- return TEE_SUCCESS;
-}
-
-void TEE_InitRefAttribute(TEE_Attribute* attr, uint32_t attributeID,
- const void* buffer, size_t length) {
- attr->attributeID = attributeID;
- attr->content.ref.buffer = buffer;
- attr->content.ref.length = length;
-}
-
-void TEE_InitValueAttribute(TEE_Attribute* attr, uint32_t attributeID,
- uint32_t a, uint32_t b) {
- attr->attributeID = attributeID;
- attr->content.value.a = a;
- attr->content.value.b = b;
-}
-
-void TEE_CopyObjectAttributes(TEE_ObjectHandle destObject,
- TEE_ObjectHandle srcObject) {
- int attrCount, i;
- //int offset = 0;
- TEE_Attribute * attrs;
-
- TransientObject* src = &srcObject->tr;
- TransientObject* dest = &destObject->tr;
-
- if (dest->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- dest->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
- if (!(src->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- // check compatibility of source & destination
- if (!((src->info.objectType == dest->info.objectType)
- || ((dest->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY)
- && (src->info.objectType == TEE_TYPE_RSA_KEYPAIR))
- || ((dest->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY)
- && (src->info.objectType == TEE_TYPE_DSA_KEYPAIR)))) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (src->info.objectSize > dest->info.maxObjectSize) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- dest->info.objectUsage &= src->info.objectUsage;
- // copy attributes
- attrs = src->attr.attr_array;
- attrCount = src->attr.attr_number;
- //offset = 0;
- for (i = 0; i < attrCount; i++) {
- copy_attribute(&dest->attr.attr_array[i], &attrs[i]);
- dest->attr.attr_number++;
- }
-}
-
-TEE_Result TEE_GenerateKey(TEE_ObjectHandle object, uint32_t keySize,
- const TEE_Attribute* params, uint32_t paramCount) {
- char key[256];
- TEE_Attribute attrs[MAX_ATTRIBUTE_NUMBER];
- unsigned int i, check = 0;
- TransientObject* tr = &object->tr;
-
- if (tr->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (keySize > tr->info.maxObjectSize) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- tr->info.objectSize = keySize;
- switch (tr->info.objectType) {
- case TEE_TYPE_AES:
- case TEE_TYPE_DES:
- case TEE_TYPE_DES3:
- case TEE_TYPE_HMAC_MD5:
- case TEE_TYPE_HMAC_SHA1:
- case TEE_TYPE_HMAC_SHA224:
- case TEE_TYPE_HMAC_SHA256:
- case TEE_TYPE_HMAC_SHA384:
- case TEE_TYPE_HMAC_SHA512:
- case TEE_TYPE_GENERIC_SECRET:
- // generate 1 random key
- gen_random((unsigned char*)key, (keySize + 7) / 8);
- TEE_InitRefAttribute(&attrs[0], TEE_ATTR_SECRET_VALUE, key, keySize);
- TEE_PopulateTransientObject(object, attrs, 1);
- break;
- case TEE_TYPE_RSA_KEYPAIR: {
- uci_key_s uci_key;
- int key_size = (keySize + 7) / 8;
- uci_key.ucik_rsa_n = (unsigned char*)OsaMalloc(key_size);
- uci_key.ucik_rsa_n_len = key_size;
- uci_key.ucik_rsa_e = (unsigned char*)OsaMalloc(key_size);
- uci_key.ucik_rsa_e_len = key_size;
- uci_key.ucik_rsa_d = (unsigned char*)OsaMalloc(key_size);
- uci_key.ucik_rsa_d_len = key_size;
- uci_param_s up;
- up.ucip_rsa_flag = RSA_GENKEYWITHNON;
- up.ucip_rsa_padding = ID_UCI_RSAES_PKCS15;
- //alg
- int alg = ID_UCI_RSA;
- if (512 == keySize) {
- alg = ID_UCI_RSA512;
- } else if (1024 == keySize) {
- alg = ID_UCI_RSA1024;
- } else if (2048 == keySize) {
- alg = ID_UCI_RSA2048;
- } else if (3072 == keySize) {
- alg = ID_UCI_RSA3072;
- }
- UCI_HANDLE uh = uci_context_alloc(alg, UCI_SW);
- uci_ae_gen_keypair(uh, &uci_key, &up);
- uci_context_free(uh);
-
- TEE_InitRefAttribute(&attrs[0], TEE_ATTR_RSA_MODULUS, uci_key.ucik_rsa_n,
- keySize);
- TEE_InitRefAttribute(&attrs[1], TEE_ATTR_RSA_PUBLIC_EXPONENT,
- uci_key.ucik_rsa_e, keySize);
- TEE_InitRefAttribute(&attrs[2], TEE_ATTR_RSA_PRIVATE_EXPONENT,
- uci_key.ucik_rsa_d, keySize);
- TEE_PopulateTransientObject(object, attrs, 3);
-
- OsaFree(uci_key.ucik_rsa_n);
- OsaFree(uci_key.ucik_rsa_e);
- OsaFree(uci_key.ucik_rsa_d);
- }
- break;
-
- case TEE_TYPE_DSA_KEYPAIR: {
- uci_key_s uci_key;
- int key_size = (keySize + 7) / 8;
- uci_key.ucik_dsa_pubk_len = key_size;
- uci_key.ucik_dsa_pubkey = (unsigned char*)OsaMalloc(key_size);
- uci_key.ucik_dsa_privk_len = key_size;
- uci_key.ucik_dsa_privkey = (unsigned char*)OsaMalloc(key_size);
- uci_param_s up;
- up.ucip_dsa_tsize = 0;
-
- // check the mandatory attributes
- for (i = 0; i < paramCount; i++) {
- if (params[i].attributeID == TEE_ATTR_DSA_PRIME) {
- up.ucip_dsa_p = (unsigned char*)params[i].content.ref.buffer;
- up.ucip_dsa_p_len = (params[i].content.ref.length + 7) / 8;
- check |= 0x01;
- } else if (params[i].attributeID == TEE_ATTR_DSA_BASE) {
- up.ucip_dsa_g = (unsigned char*)params[i].content.ref.buffer;
- up.ucip_dsa_g_len = (params[i].content.ref.length + 7) / 8;
- check |= 0x02;
- } else if (params[i].attributeID == TEE_ATTR_DSA_SUBPRIME) {
- up.ucip_dsa_q = (unsigned char*)params[i].content.ref.buffer;
- up.ucip_dsa_q_len = (params[i].content.ref.length + 7) / 8;
- check |= 0x04;
- }
- }
- if (check != 0x07) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- // generate public & private keys. algorithm is the same as for DH
- UCI_HANDLE handle = uci_context_alloc(ID_UCI_DSA, UCI_SW);
- uci_ae_gen_keypair(handle, &uci_key, &up);
- uci_context_free(handle);
- for (i = 0; i < paramCount; i++) {
- TEE_InitRefAttribute(&attrs[i], params[i].attributeID,
- params[i].content.ref.buffer, params[i].content.ref.length);
- }
- TEE_InitRefAttribute(&attrs[3], TEE_ATTR_DSA_PUBLIC_VALUE,
- uci_key.ucik_dsa_pubkey, uci_key.ucik_dsa_pubk_len * 8);
- TEE_InitRefAttribute(&attrs[4], TEE_ATTR_DSA_PRIVATE_VALUE,
- uci_key.ucik_dsa_privkey, uci_key.ucik_dsa_privk_len * 8);
- TEE_PopulateTransientObject(object, attrs, 5);
- OsaFree(uci_key.ucik_dsa_pubkey);
- OsaFree(uci_key.ucik_dsa_privkey);
- }
- break;
-
- case TEE_TYPE_DH_KEYPAIR: {
- int key_size = (keySize + 7) / 8;
- uint8_t* privKey = (unsigned char*)OsaMalloc(key_size);
- uint8_t* pubKey = (unsigned char*)OsaMalloc(key_size);
- uci_param_s uciparam;
-
- for (i = 0; i < paramCount; i++) {
- if (params[i].attributeID == TEE_ATTR_DH_PRIME) {
- check |= 0x01;
- uciparam.ucip_dh_prime = (unsigned char*)params[i].content.ref.buffer;
- uciparam.ucip_dh_len = (params[i].content.ref.length + 7) / 8;
- } else if (params[i].attributeID == TEE_ATTR_DH_BASE) {
- check |= 0x02;
- uciparam.ucip_dh_generator = (unsigned char*)params[i].content.ref
- .buffer;
- }
- }
- if (check != 0x03) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- UCI_HANDLE handle = uci_context_alloc(ID_UCI_DH, UCI_SW);
- uci_dh_gen_phasekey(handle, privKey, pubKey, &uciparam);
- uci_context_free(handle);
- for (i = 0; i < paramCount; i++) {
- TEE_InitRefAttribute(&attrs[i], params[i].attributeID,
- params[i].content.ref.buffer, params[i].content.ref.length);
- }
- TEE_InitRefAttribute(&attrs[2], TEE_ATTR_DH_PRIVATE_VALUE, privKey,
- keySize);
- TEE_InitRefAttribute(&attrs[3], TEE_ATTR_DH_PUBLIC_VALUE, pubKey,
- keySize);
- TEE_PopulateTransientObject(object, attrs, 4);
-
- OsaFree(privKey);
- OsaFree(pubKey);
- }
- break;
- }
- return TEE_SUCCESS;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// Persistent object operations
-////////////////////////////////////////////////////////////////////////////////////
-
-TEE_Result TEE_CreatePersistentObject(uint32_t storageID, const void* objectID,
- size_t objectIDLen, uint32_t flags, TEE_ObjectHandle attributes,
- const void* initialData, size_t initialDataLen, TEE_ObjectHandle* object) {
- persistent_object* po = NULL;
- TEE_Result rc = allocate_persistent_object(&po, storageID, objectID,
- objectIDLen, flags);
- TransientObject* tr_obj = NULL;
- if (TEE_HANDLE_NULL != attributes) {
- tr_obj = &attributes->tr;
- }
- rc = exist_po(po);
- // already exist
- if (TEE_SUCCESS == rc) {
- if (flags & TEE_DATA_FLAG_EXCLUSIVE) {
- MSG("Persistent object already exist.");
- FREE_PO(po);
- return TEE_ERROR_ACCESS_CONFLICT;
- }
- if (!object) {
- FREE_PO(po);
- return TEE_SUCCESS;
- }
- rc = open_po(po);
- } else {
- rc = create_po(po, tr_obj, initialData, initialDataLen);
- }
- if (rc) {
- FREE_PO(po);
- return rc;
- }
- if (object) {
- *object = (TEE_ObjectHandle)&po->attr.info;
- } else {
- close_po(po);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_OpenPersistentObject(uint32_t storageID, const void* objectID,
- size_t objectIDLen, uint32_t flags, TEE_ObjectHandle* object) {
- persistent_object* po = NULL;
- TEE_Result rc = allocate_persistent_object(&po, storageID, objectID,
- objectIDLen, flags);
- if (rc) {
- return rc;
- }
- rc = open_po(po);
- if (rc) {
- FREE_PO(po);
- return rc;
- }
- *object = (TEE_ObjectHandle)&po->attr.info;
- return TEE_SUCCESS;
-}
-
-void TEE_CloseAndDeletePersistentObject(TEE_ObjectHandle object) {
- persistent_object* op;
- if (object == TEE_HANDLE_NULL) {
- return;
- }
- if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- op = (persistent_object*)object;
- if (!(op->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- free_po(op);
-}
-
-TEE_Result TEE_RenamePersistentObject(TEE_ObjectHandle object,
- const void* newObjectID, size_t newObjectIDLen) {
- if (object == TEE_HANDLE_NULL) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
- // transient object
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- persistent_object* po;
- po = (persistent_object*)object;
- if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_EXCLUSIVE)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (newObjectIDLen > TEE_OBJECT_ID_MAX_LEN) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- return rename_po(po, newObjectID, newObjectIDLen);
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// Persistent enumerator operations
-////////////////////////////////////////////////////////////////////////////////////
-TEE_Result TEE_AllocatePersistentObjectEnumerator(
- TEE_ObjectEnumHandle* objectEnumerator) {
- struct __TEE_ObjectEnumHandle* eh;
- eh = (__TEE_ObjectEnumHandle *)OsaMalloc(
- sizeof(struct __TEE_ObjectEnumHandle));
- if (!eh) {
- return TEE_ERROR_OUT_OF_MEMORY;
- }
- eh->po_info = NULL;
- eh->po_num = 0;
- eh->curr_position = 0;
- eh->state = ENUM_STATE_INIT;
-
- *objectEnumerator = eh;
- return TEE_SUCCESS;
-}
-
-void TEE_FreePersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator) {
- if (TEE_HANDLE_NULL == objectEnumerator) {
- return;
- }
- __FREE(objectEnumerator->po_info);
- __FREE(objectEnumerator);
-}
-
-void TEE_ResetPersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator) {
- if (TEE_HANDLE_NULL == objectEnumerator) {
- return;
- }
- objectEnumerator->curr_position = 0;
- objectEnumerator->po_num = 0;
- objectEnumerator->state = ENUM_STATE_INIT;
- __FREE(objectEnumerator->po_info);
- objectEnumerator->po_info = NULL;
-}
-
-TEE_Result TEE_StartPersistentObjectEnumerator(
- TEE_ObjectEnumHandle objectEnumerator, uint32_t storageID) {
- if (TEE_HANDLE_NULL == objectEnumerator) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (storageID != TEE_STORAGE_PRIVATE) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- TEE_UUID uuid;
- if (0 != get_uuid()) {
- MSG("Failed to get UUID of TA.");
- return -1;
- }
- uuid = this_uuid;
-
- if (objectEnumerator->state == ENUM_STATE_STARTED) {
- TEE_ResetPersistentObjectEnumerator(objectEnumerator);
- }
- int ret = get_po_info(&g_po_info_file, &objectEnumerator->po_info,
- &objectEnumerator->po_num);
- if (ret || !objectEnumerator->po_num) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- objectEnumerator->state = ENUM_STATE_STARTED;
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_GetNextPersistentObject(TEE_ObjectEnumHandle objectEnumerator,
- TEE_ObjectInfo* objectInfo, void* objectID, size_t* objectIDLen) {
- if (TEE_HANDLE_NULL == objectEnumerator) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if ((objectEnumerator->state != ENUM_STATE_STARTED)
- || (objectEnumerator->state == ENUM_STATE_END)) {
- return TEE_ERROR_ITEM_NOT_FOUND;
- }
- persistent_object_info* po_info = objectEnumerator->po_info;
- int curr_pos = objectEnumerator->curr_position;
- *objectInfo = po_info[curr_pos].info;
- *objectIDLen = po_info[curr_pos].obj_id_len;
- memcpy(objectID, po_info[curr_pos].object_id, po_info[curr_pos].obj_id_len);
-
- objectEnumerator->curr_position++;
- if (objectEnumerator->curr_position >= objectEnumerator->po_num) {
- objectEnumerator->state = ENUM_STATE_END;
- }
- return TEE_SUCCESS;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-// Data stream access operations
-////////////////////////////////////////////////////////////////////////////////////
-
-TEE_Result TEE_ReadObjectData(TEE_ObjectHandle object, void* buffer,
- size_t size, uint32_t* count) {
- int num;
- if (object == TEE_HANDLE_NULL) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- persistent_object* po = (persistent_object*)object;
- if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_READ)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (size == 0) {
- num = 0;
- } else {
- TEE_Result rc = read_object_data(po, buffer, size, (uint32_t*)&num);
- if (rc) {
- return rc;
- }
- }
- *count = num;
-
- MSG("Data read is:");
- printhex((unsigned char*)buffer, num);
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_WriteObjectData(TEE_ObjectHandle object, const void* buffer,
- size_t size) {
- if (object == TEE_HANDLE_NULL) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- persistent_object* po = (persistent_object*)object;
- if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (size != 0) {
- return write_object_data(po, buffer, size);
- }
- return TEE_SUCCESS;
-}
-
-TEE_Result TEE_TruncateObjectData(TEE_ObjectHandle object, uint32_t size) {
- if (object == TEE_HANDLE_NULL) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- persistent_object* po = (persistent_object*)object;
- if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- return truncate_object_data(po, size);
-}
-
-TEE_Result TEE_SeekObjectData(TEE_ObjectHandle object, int32_t offset,
- TEE_Whence whence) {
- if (object == TEE_HANDLE_NULL) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
- TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
- TEE_Panic(0);
- }
- persistent_object* po = (persistent_object*)object;
- return seek_object_data(po, offset, whence);
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssf_storage.c
+ *
+ * Description: SSF storage functions
+ *
+ * Version: 1.0
+ * Created: 23 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: krishna (Kr), k.devale@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include "ssf_storage.h"
+#include <sys/mman.h>
+#include <string.h>
+#include <permission.h>
+#include <log.h>
+
+/*-----------------------------------------------------------------------------
+ * MACROS
+ *-----------------------------------------------------------------------------*/
+#define __FREE(buf) if(buf) {OsaFree(buf); buf = NULL;}
+#define FREE_PO(po) if(po) {clean_po_file(po);OsaFree(po); po = NULL;}
+
+#define PO_INTERNAL_MODULE_NAME "po_file"
+#define PO_STAT_INTERNAL_MODULE_NAME "po_stat"
+#define PI_FILE_NAME "pi_file"
+#define UUID_FILE "/usr/apps/tee/TA-UUID.list"
+
+TEE_UUID ssf_sharedthisTAUUID;
+static TEE_UUID this_uuid;
+static int uuid_got = 0;
+
+#define g_bTAdbug 1
+#define TZ_PRINT(fmt...) \
+ do {if (g_bTAdbug) printf("[SSFLIB] ");printf(fmt);}while(0)
+#define TZ_ERROR(fmt...) \
+ do {if (g_bTAdbug) printf("[SSFLIB] ");printf(fmt);}while(0)
+
+#if 0
+int get_ta_name(char* ta_name) {
+ pid_t pid = getpid();
+ char path[256] = {0};
+ char ta_path[256] = {0};
+ sprintf(path, "/proc/%d/exe", pid);
+ int cnt = readlink(path, ta_path, 256);
+ if (cnt < 0 || cnt > 256) {
+ MSG("Error readlink.");
+ return -1;
+ }
+ ta_path[cnt] = '\0';
+ int idx = cnt - 1;
+ for (; idx >= 0; idx--) {
+ if (ta_path[idx] == '/') {
+ strcpy(ta_name, ta_path + idx + 1);
+ return 0;
+ }
+ }
+ return -1;
+}
+#endif
+
+/*-----------------------------------------------------------------------------
+ * Local functions
+ *-----------------------------------------------------------------------------*/
+int get_uuid() {
+//assigns UIID obtained from TEEStub
+ this_uuid = ssf_sharedthisTAUUID;
+ uuid_got = 1;
+ return 0;
+#if 0
+ if (uuid_got)
+ {
+ return 0;
+ }
+ char ta_name[256] =
+ { 0};
+ if (0 != get_ta_name(ta_name))
+ {
+ MSG("Failed to get ta name.");
+ return -1;
+ }
+ FILE* f = fopen(UUID_FILE, "r");
+ if (!f)
+ {
+ MSG("Can't open file %s\n", UUID_FILE);
+ return -1;
+ }
+ char name[256];
+ char *line = NULL;
+ size_t len = 0;
+ ssize_t read_bytes;
+ int matched = 0;
+ TEE_UUID uuid;
+ while (-1 != getline(&line, &len, f))
+ {
+ matched =
+ sscanf(line,
+ "TA={ %x , %hx , %hx , { %hhx , %hhx , %hhx , %hhx , %hhx , %hhx , %hhx , %hhx } } : %64s",
+ &uuid.timeLow, &uuid.timeMid, &uuid.timeHiAndVersion,
+ &uuid.clockSeqAndNode[0], &uuid.clockSeqAndNode[1],
+ &uuid.clockSeqAndNode[2], &uuid.clockSeqAndNode[3],
+ &uuid.clockSeqAndNode[4], &uuid.clockSeqAndNode[5],
+ &uuid.clockSeqAndNode[6], &uuid.clockSeqAndNode[7],
+ name);
+ if (matched != 12 || matched == EOF)
+ {
+ MSG("bad format for uuid:%s\n", line);
+ continue;
+ }
+ OsaFree(line);
+ line = NULL;
+ MSG("ta_name [%s] <=> name [%s]", ta_name, name);
+ if (0 == memcmp(ta_name, name, strlen(ta_name)))
+ {
+ this_uuid = uuid;
+ uuid_got = 1;
+ fclose(f);
+ return 0;
+ }
+ }
+ fclose(f);
+ return -1;
+#endif
+}
+
+void printhex(unsigned char* buf, unsigned int size) {
+ MSG("---------------------------------------------------");
+ unsigned int i;
+ for (i = 0; i < size; ++i) {
+ if (0 == (i % 16) && i) {
+ printf("\n");
+ }
+ printf("%02x ", buf[i]);
+ }
+ MSG("\n---------------------------------------------------");
+}
+
+/*-----------------------------------------------------------------------------
+ * TEE API implementation
+ *-----------------------------------------------------------------------------*/
+////////////////////////////////////////////////////////////////////////////////////
+// internal attribute operations
+////////////////////////////////////////////////////////////////////////////////////
+TEE_Result copy_attribute(TEE_Attribute* dest, TEE_Attribute* src) {
+ if (!dest || !src) {
+ return TEE_ERROR_BAD_PARAMETERS;
+ }
+ dest->attributeID = src->attributeID;
+ if (src->attributeID & TEE_ATTR_FLAG_VALUE) {
+ dest->content.value.a = src->content.value.a;
+ dest->content.value.b = src->content.value.b;
+ } else {
+ int buf_size = (src->content.ref.length + 7) / 8;
+ void* buffer = OsaMalloc(buf_size);
+ if (!buffer) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memcpy(buffer, src->content.ref.buffer, buf_size);
+ dest->content.ref.buffer = buffer;
+ dest->content.ref.length = src->content.ref.length;
+ }
+ return TEE_SUCCESS;
+}
+
+void free_attribute(TEE_Attribute* attr) {
+ if (!attr) {
+ return;
+ }
+ if (!(attr->attributeID & TEE_ATTR_FLAG_VALUE)) {
+ OsaFree((void*)attr->content.ref.buffer);
+ }
+}
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+// Internal transient Object Operations
+/////////////////////////////////////////////////////////////////////////////////////////////
+TEE_Result allocate_transient_object(TransientObject* tr, uint32_t objectType,
+ uint32_t maxObjectSize) {
+ tr->attr.attr_number = 0;
+
+/* switch (objectType) {
+ case TEE_TYPE_AES:
+ if (maxObjectSize != 128 && maxObjectSize != 192
+ && maxObjectSize != 256) {
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_DES:
+ //if (maxObjectSize != 64) {
+ // return TEE_ERROR_NOT_SUPPORTED;
+ //}
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_DES3:
+ if (maxObjectSize != 128 && maxObjectSize != 192)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_HMAC_MD5:
+ if (maxObjectSize < 64 || maxObjectSize > 512 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_HMAC_SHA1:
+ if (maxObjectSize < 80 || maxObjectSize > 512 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_HMAC_SHA224:
+ if (maxObjectSize < 112 || maxObjectSize > 512 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_HMAC_SHA256:
+ if (maxObjectSize < 192 || maxObjectSize > 1024 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_HMAC_SHA384:
+ if (maxObjectSize < 256 || maxObjectSize > 1024 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_HMAC_SHA512:
+ if (maxObjectSize < 256 || maxObjectSize > 1024 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ case TEE_TYPE_RSA_PUBLIC_KEY:
+ case TEE_TYPE_RSA_KEYPAIR:
+ if (maxObjectSize < 256 || maxObjectSize > 3072)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = sizeof(rsa_context);
+ break;
+ case TEE_TYPE_DSA_PUBLIC_KEY:
+ case TEE_TYPE_DSA_KEYPAIR:
+ if (maxObjectSize < 512 || maxObjectSize > 1024 || maxObjectSize % 64)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = sizeof(dsa_context);
+ break;
+ case TEE_TYPE_DH_KEYPAIR:
+ if (maxObjectSize < 256 || maxObjectSize > 2048)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = sizeof(dh_context);
+ break;
+ case TEE_TYPE_GENERIC_SECRET:
+ if (maxObjectSize > 4096 || maxObjectSize % 8)
+ return TEE_ERROR_NOT_SUPPORTED;
+ //tr->attr.buf_len = (maxObjectSize + 7)>>3;
+ break;
+ default:
+ return TEE_ERROR_NOT_SUPPORTED;
+ }
+*/
+ // Object info
+ tr->info.objectType = objectType;
+ tr->info.objectSize = 0;
+ tr->info.maxObjectSize = maxObjectSize;
+ //tr->info.dataSize = 0;
+ //tr->info.dataPosition = 0;
+ //tr->info.handleFlags = 0;
+ tr->info.objectUsage = 0xffffffff;
+ return TEE_SUCCESS;
+}
+
+size_t calc_attr_size(TransientObject* tr) {
+ size_t size = 0;
+ size += sizeof(int);
+ size += tr->attr.attr_number * 4; //attrID
+ TEE_Attribute* attrs = tr->attr.attr_array;
+ int i;
+ for (i = 0; i < tr->attr.attr_number; ++i) {
+ if (attrs[i].attributeID & TEE_ATTR_FLAG_VALUE) {
+ size += 2 * sizeof(uint32_t);
+ } else {
+ size += sizeof(size_t);
+ size += (attrs[i].content.ref.length + 7) / 8;
+ }
+ }
+ return size;
+}
+
+TEE_Result serialise_attr(TransientObject* tr, char* buf) {
+ if (!buf) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memcpy(buf, (void*)&tr->attr.attr_number, sizeof(int));
+ buf += sizeof(int);
+
+ TEE_Attribute* attrs = tr->attr.attr_array;
+ int i;
+ for (i = 0; i < tr->attr.attr_number; ++i) {
+ //AttrID
+ memcpy(buf, &(attrs[i].attributeID), 4);
+ buf += 4;
+ if (attrs[i].attributeID & TEE_ATTR_FLAG_VALUE) {
+ memcpy(buf, (void*)&(attrs[i].content.value.a), 2 * sizeof(uint32_t));
+ buf += 2 * sizeof(uint32_t);
+ } else {
+ memcpy(buf, &(attrs[i].content.ref.length), 4);
+ buf += 4;
+ memcpy(buf, (void*)attrs[i].content.ref.buffer,
+ (attrs[i].content.ref.length + 7) / 8);
+ buf += (attrs[i].content.ref.length + 7) / 8;
+ }
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result deserialise_attr(char* buf, TransientObject* tr) {
+ if (!buf) {
+ return TEE_SUCCESS;
+ }
+ TEE_Attribute* attrs = tr->attr.attr_array;
+ memcpy(&tr->attr.attr_number, buf, sizeof(int));
+ buf += sizeof(int);
+
+ int i;
+ for (i = 0; i < tr->attr.attr_number; ++i) {
+ memcpy(&attrs[i].attributeID, buf, 4);
+ buf += 4;
+ if (attrs[i].attributeID & TEE_ATTR_FLAG_VALUE) {
+ memcpy((void*)&(attrs[i].content.value.a), buf, 2 * sizeof(uint32_t));
+ buf += 2 * sizeof(uint32_t);
+ } else {
+ memcpy((void*)&attrs[i].content.ref.length, buf, 4);
+ buf += 4;
+ void* buffer = OsaMalloc((attrs[i].content.ref.length + 7) / 8);
+ if (!buffer) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memcpy(buffer, buf, (attrs[i].content.ref.length + 7) / 8);
+ attrs[i].content.ref.buffer = buffer;
+ buf += (attrs[i].content.ref.length + 7) / 8;
+ }
+ }
+ return TEE_SUCCESS;
+}
+
+/////////////////////////////////////////////////////////////////////////////////////////////
+// Internal Persistent Object Operations
+/////////////////////////////////////////////////////////////////////////////////////////////
+
+TEE_Result allocate_persistent_object(persistent_object** po,
+ uint32_t storageID, const void* objectID, size_t objectIDLen,
+ uint32_t flags) {
+ if (objectIDLen > TEE_OBJECT_ID_MAX_LEN) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (storageID != TEE_STORAGE_PRIVATE) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ persistent_object* tmp_po = (persistent_object*)OsaMalloc(
+ sizeof(persistent_object));
+ if (!tmp_po) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memset(tmp_po, 0, sizeof(persistent_object));
+
+ tmp_po->storage_id = storageID;
+ tmp_po->attr.info.handleFlags = flags;
+ tmp_po->obj_id_len = objectIDLen;
+ memcpy(tmp_po->object_id, objectID, objectIDLen);
+ if (0 != get_uuid()) {
+ MSG("Failed to get UUID of TA.");
+ FREE_PO(tmp_po);
+ return TEE_ERROR_GENERIC;
+ }
+ tmp_po->TA_UUID = this_uuid;
+ *po = tmp_po;
+ init_po(tmp_po);
+ return TEE_SUCCESS;
+}
+
+TEE_Result create_po(persistent_object* po, TransientObject* attr,
+ const void* init_data, size_t data_size) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ TEE_Result rc;
+ if (NULL != attr) {
+ if (!(attr->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ rc = allocate_transient_object(&po->attr, attr->info.objectType,
+ attr->info.maxObjectSize);
+ if (rc != TEE_SUCCESS) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ // copy attributes
+// TEE_CopyObjectAttributes((TEE_ObjectHandle) & po->attr,
+// (TEE_ObjectHandle) attr);
+
+ TEE_CopyObjectAttributes((TEE_ObjectHandle)&po->attr.info,
+ (TEE_ObjectHandle)attr);
+
+ // get required buffer length
+ po->po_file.attr_size = calc_attr_size(&po->attr);
+ po->po_file.attr = (uint8_t*)OsaMalloc(po->po_file.attr_size);
+ if (NULL == po->po_file.attr) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ // fill attr
+ rc = serialise_attr(&po->attr, (char*)po->po_file.attr);
+ if (rc) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ }
+
+ // fill data object
+ if (init_data && data_size) {
+ po->po_file.obj_data_size = data_size;
+ if (0 != po->po_file.obj_data_size) {
+ po->po_file.object_data = (uint8_t*)OsaMalloc(po->po_file.obj_data_size);
+ if (!po->po_file.object_data) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memcpy(po->po_file.object_data, init_data, po->po_file.obj_data_size);
+ }
+ }
+
+ // init object info
+ po->attr.info.dataPosition = 0;
+ po->attr.info.dataSize = data_size;
+ po->attr.info.handleFlags |= TEE_HANDLE_FLAG_PERSISTENT
+ | TEE_HANDLE_FLAG_INITIALIZED;
+ po->attr.info.objectUsage = 0xffffff;
+ po->attr.info.objectSize =
+ attr == TEE_HANDLE_NULL ? 0 : attr->info.objectSize;
+
+ // write po file to ss
+ po->po_file.po_info = po->attr.info;
+ if (0 != write_po_file(po)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ memset(&g_po_info_file, 0, sizeof(po_info_file));
+ // write to stat file.
+ if (write_po_info(&g_po_info_file, po->object_id, po->obj_id_len,
+ &po->attr.info)) {
+ return TEE_ERROR_GENERIC;
+ }
+ // update po share info
+ if (0 != update_share_info(&po->share_info, po->attr.info.handleFlags,0, 1, po)) {
+ return TEE_ERROR_GENERIC;
+ }
+ // add to po list
+ add_to_po_list(po);
+ return TEE_SUCCESS;
+}
+
+TEE_Result open_po(persistent_object* po) {
+ int handleFlages;
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+
+ // read and parse
+ int ret = load_po_file(po);
+ if (0 != ret) {
+ return (1 == ret) ? TEE_ERROR_ITEM_NOT_FOUND : TEE_ERROR_GENERIC;
+ }
+ ret = update_share_info(&po->share_info, po->attr.info.handleFlags, (po->po_file.po_info.handleFlags), 1, po);
+ if (0 != ret) {
+ return (1 == ret) ? TEE_ERROR_ACCESS_CONFLICT : TEE_ERROR_GENERIC;
+ }
+
+ if (deserialise_attr((char*)po->po_file.attr, (TransientObject*)&po->attr)) {
+ ret = TEE_ERROR_GENERIC;
+ goto out;
+ }
+ handleFlages = po->attr.info.handleFlags | TEE_HANDLE_FLAG_PERSISTENT
+ | TEE_HANDLE_FLAG_INITIALIZED;
+ po->attr.info = po->po_file.po_info;
+ po->attr.info.handleFlags = handleFlages;
+ po->attr.info.dataPosition = 0;
+ // add to po list
+ add_to_po_list(po);
+ ret = TEE_SUCCESS;
+ out:
+ if (ret) {
+ update_share_info(&po->share_info, po->attr.info.handleFlags, 0, 0, po);
+ }
+ return ret;
+}
+
+TEE_Result read_object_data(persistent_object* po, void* buffer, size_t size,
+ uint32_t* count) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!buffer) {
+ return TEE_ERROR_BAD_PARAMETERS;
+ }
+ if (0 == size || 0 == po->attr.info.dataSize) {
+ *count = 0;
+ return TEE_SUCCESS;
+ }
+ if (po->attr.info.dataPosition >= po->attr.info.dataSize) {
+ return TEE_ERROR_OVERFLOW;
+ }
+ int cpsz =
+ (po->attr.info.dataPosition + size >= po->attr.info.dataSize) ?
+ (po->attr.info.dataSize - po->attr.info.dataPosition) : size;
+
+ void* src = po->po_file.object_data + po->attr.info.dataPosition;
+ memcpy(buffer, src, cpsz);
+ //update object info
+ po->attr.info.dataPosition += cpsz;
+ *count = cpsz;
+ return TEE_SUCCESS;
+}
+
+TEE_Result seek_object_data(persistent_object* po, int32_t offset,
+ TEE_Whence whence) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ uint32_t begin_pos = 0;
+ if (TEE_DATA_SEEK_CUR == whence) {
+ begin_pos = po->attr.info.dataPosition;
+ } else if (TEE_DATA_SEEK_END == whence) {
+ begin_pos = po->attr.info.dataSize;
+ }
+ int32_t dataPos = begin_pos + offset;
+ if ((uint32_t)dataPos >= TEE_DATA_MAX_POSITION) {
+ return TEE_ERROR_OVERFLOW;
+ }
+ if (dataPos < 0) {
+ dataPos = 0;
+ }
+ // Not support "hole" in file in this version.
+ if ((uint32_t)dataPos > (po->attr.info.dataSize - 1)) {
+ dataPos = po->attr.info.dataSize;
+ }
+ po->attr.info.dataPosition = dataPos;
+ return TEE_SUCCESS;
+}
+
+TEE_Result write_object_data(persistent_object* po, const void* buffer,
+ size_t size) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!buffer || !size) {
+ return TEE_SUCCESS;
+ }
+ if (po->attr.info.dataPosition > po->attr.info.dataSize) {
+ return TEE_ERROR_OVERFLOW;
+ }
+ uint32_t modified_size = po->attr.info.dataPosition + size;
+ if (modified_size <= po->attr.info.dataSize) {
+ memcpy(po->po_file.object_data + po->attr.info.dataPosition, buffer, size);
+ } else {
+ void* tmp_buf = OsaMalloc(modified_size);
+ if (NULL == tmp_buf) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memcpy(tmp_buf, po->po_file.object_data, po->attr.info.dataPosition);
+ memcpy((uint8_t*)tmp_buf + po->attr.info.dataPosition, buffer, size);
+ OsaFree(po->po_file.object_data);
+ po->po_file.object_data = (unsigned char*)tmp_buf;
+ }
+ //update object info
+ po->attr.info.dataPosition += size;
+ po->attr.info.dataSize =
+ (modified_size > po->attr.info.dataSize) ? modified_size :
+ po->attr.info.dataSize;
+ // sync to ss.
+ po->po_file.po_info.dataSize = po->attr.info.dataSize;
+ if (-1 == write_po_file(po)) {
+ MSG("Failed to write po file to secure storage.");
+ return TEE_ERROR_GENERIC;
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result truncate_object_data(persistent_object* po, size_t size) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ // now not support the "hole" in file.
+ size_t trunc_sz =
+ po->attr.info.dataSize > size ? size : po->attr.info.dataSize;
+ if (trunc_sz == po->attr.info.dataSize) {
+ return TEE_SUCCESS;
+ }
+ po->attr.info.dataSize = trunc_sz;
+ po->po_file.po_info.dataSize = trunc_sz;
+ // write to ss
+ if (-1 == write_po_file(po)) {
+ return TEE_ERROR_GENERIC;
+ }
+ return TEE_SUCCESS;
+}
+
+void close_po(persistent_object* po) {
+ if (NULL == po) {
+ return;
+ }
+ update_share_info(&po->share_info, po->attr.info.handleFlags, 0, 0, po);
+
+ // remove from po list
+ rem_from_po_list(po);
+
+ // free online attributes
+ TEE_Attribute* attrs = po->attr.attr.attr_array;
+ int i;
+ for (i = 0; i < po->attr.attr.attr_number; ++i) {
+ free_attribute(&attrs[i]);
+ }
+ FREE_PO(po);
+}
+
+TEE_Result free_po(persistent_object* po) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (-1 == delete_po_file(po)) {
+ return TEE_ERROR_GENERIC;
+ }
+ // free online attributes
+ TEE_Attribute* attrs = po->attr.attr.attr_array;
+ int i;
+ for (i = 0; i < po->attr.attr.attr_number; ++i) {
+ free_attribute(&attrs[i]);
+ }
+ // remove from po list
+ rem_from_po_list(po);
+ release_share_info(&po->share_info);
+ FREE_PO(po);
+ return TEE_SUCCESS;
+}
+
+TEE_Result rename_po(persistent_object* po, const void* newObjectID,
+ size_t newObjectIDLen) {
+ if (NULL == po) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (-1 == rename_po_file(po, newObjectID, newObjectIDLen)) {
+ return TEE_ERROR_GENERIC;
+ }
+ memcpy(po->object_id, newObjectID, newObjectIDLen);
+ po->obj_id_len = newObjectIDLen;
+ return TEE_SUCCESS;
+}
+
+TEE_Result exist_po(persistent_object* po) {
+ int ret = ss_validate(po->po_file.file_name, &po->po_file.cred,
+ SS_OPT_DEFAULT);
+ if (SS_RET_CANT_FIND_REQUESTED_DATA == ret) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ if (SS_RET_SUCCESS == ret) {
+ return TEE_SUCCESS;
+ }
+ return TEE_ERROR_GENERIC;
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// Persistent file operations
+////////////////////////////////////////////////////////////////////////////////////
+void init_po(persistent_object* po) {
+ char uuid[64] = {0};
+ convert_TA_UUID(uuid, po->TA_UUID);
+ MSG("UUID of the TA is %s.", uuid);
+ ss_set_credential(&po->po_file.cred, uuid, PO_INTERNAL_MODULE_NAME, 1, 0);
+
+ //derive file name
+ derive_po_file_name((void*)po->object_id, po->obj_id_len,
+ po->po_file.file_name);
+ po->po_file.attr = NULL;
+ po->po_file.attr_size = 0;
+ po->po_file.object_data = NULL;
+ po->po_file.obj_data_size = 0;
+ // init po_share_info
+ po->share_info.fd = -1;
+ po->share_info.usr_info = NULL;
+ memcpy(po->share_info.name, po->po_file.file_name, PO_FILE_NAME_MAX_LEN);
+ po->po_list.prev = NULL;
+ po->po_list.next = NULL;
+ po->po_list.po = po;
+ regist_clean_up();
+}
+
+int derive_po_file_name(const void* obj_id, int obj_id_len, char* fn) {
+ byte_to_hex((unsigned char*)fn, (unsigned char*)obj_id, obj_id_len);
+ fn[2 * obj_id_len] = '\0';
+ return 0;
+}
+
+int load_po_file(persistent_object* po) {
+ uint8_t* retbuf = NULL;
+ uint8_t* tmp_ptr = NULL;
+ uint32_t read_size = 0;
+ int ret = ss_read(&retbuf, &read_size, 0, po->po_file.file_name,
+ &(po->po_file.cred), SS_OPT_DEFAULT);
+ if (SS_RET_CANT_FIND_REQUESTED_DATA == ret) {
+ MSG("Po file not exist.");
+ return 1;
+ }
+ if (SS_RET_SUCCESS != ret) {
+ MSG("Failed to read data from secure storage, ret = %d.", ret);
+ return -1;
+ }
+ tmp_ptr = retbuf;
+
+ // load po info
+ memcpy(&po->po_file.po_info, tmp_ptr, sizeof(TEE_ObjectInfo));
+ tmp_ptr += sizeof(TEE_ObjectInfo);
+ // load attr
+ size_t attr_size = read_size - sizeof(TEE_ObjectInfo)
+ - po->po_file.po_info.dataSize;
+ po->po_file.attr_size = attr_size;
+ if (0 < po->po_file.attr_size) {
+ po->po_file.attr = (unsigned char*)OsaMalloc(attr_size);
+ memcpy(po->po_file.attr, tmp_ptr, attr_size);
+ }
+ tmp_ptr += attr_size;
+
+ // load object data
+ po->po_file.obj_data_size = po->po_file.po_info.dataSize;
+ if (0 < po->po_file.obj_data_size) {
+ po->po_file.object_data = (unsigned char*)OsaMalloc(
+ po->po_file.obj_data_size);
+ memcpy(po->po_file.object_data, tmp_ptr, po->po_file.obj_data_size);
+ }
+ ss_free_buffer(retbuf);
+ return 0;
+}
+
+int write_po_file(persistent_object* po) {
+ uint8_t* buf = NULL;
+ po->po_file.obj_data_size = po->attr.info.dataSize;
+ uint32_t buf_size = po->po_file.attr_size + po->po_file.obj_data_size
+ + sizeof(TEE_ObjectInfo);
+ buf = (unsigned char*)OsaMalloc(buf_size);
+ if (NULL == buf) {
+ MSG("Failed to allocate memory.");
+ OsaFree(buf);
+ return -1;
+ }
+ uint8_t* tmp_buf = buf;
+
+ // po_info
+ memcpy(tmp_buf, &po->po_file.po_info, sizeof(TEE_ObjectInfo));
+ tmp_buf += sizeof(TEE_ObjectInfo);
+ // attr
+ memcpy(tmp_buf, (void*)po->po_file.attr, po->po_file.attr_size);
+ tmp_buf += po->po_file.attr_size;
+ // object data
+ memcpy(tmp_buf, (void*)po->po_file.object_data, po->po_file.obj_data_size);
+ int ret = ss_write(buf, buf_size, 0, po->po_file.file_name, &po->po_file.cred,
+ SS_OPT_DEFAULT);
+ if (SS_RET_SUCCESS != ret) {
+ MSG("Failed to write data to securestorage, ret = %d.", ret);
+ OsaFree(buf);
+ return -1;
+ }
+ OsaFree(buf);
+ return 0;
+}
+
+int rename_po_file(persistent_object* po, const void* newObjectID,
+ size_t newObjectIDLen) {
+ // first delete old file
+ if (-1 == delete_po_file(po)) {
+ MSG("Failed to delete old po file.");
+ return -1;
+ }
+ derive_po_file_name(newObjectID, newObjectIDLen, po->po_file.file_name);
+ if (0 != write_po_file(po)) {
+ MSG("Failed to write po file.");
+ return -1;
+ }
+ write_po_info(&g_po_info_file, newObjectID, newObjectIDLen, &po->attr.info);
+ return 0;
+}
+
+void clean_po_file(persistent_object* po) {
+ if (!po) {
+ return;
+ }
+ __FREE(po->po_file.attr);
+ __FREE(po->po_file.object_data);
+}
+
+int delete_po_file(persistent_object* po) {
+ int ret = ss_delete(po->po_file.file_name, &po->po_file.cred, SS_OPT_DEFAULT);
+ if (SS_RET_SUCCESS != ret) {
+ MSG("Failed to delete data from secure storage. ret = %d.", ret);
+ return -1;
+ }
+ ret = delete_po_info(&g_po_info_file, po->object_id, po->obj_id_len);
+ if (-1 == ret) {
+ MSG("Failed to delete po info.");
+ return -1;
+ }
+ return 0;
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// misc operations
+////////////////////////////////////////////////////////////////////////////////////
+po_info_file g_po_info_file;
+
+int init_po_info_file(po_info_file* pi_file) {
+ if (pi_file->b_inited) {
+ return 0;
+ }
+ TEE_UUID tmp_uuid;
+ if (0 != get_uuid()) {
+ MSG("Failed to get UUID of TA.");
+ return -1;
+ }
+ tmp_uuid = this_uuid;
+ char uuid[64] = {0};
+ convert_TA_UUID(uuid, tmp_uuid);
+ ss_set_credential(&pi_file->cred, uuid, PO_INTERNAL_MODULE_NAME, 1, 0);
+ uint32_t fn_sz = strlen(PI_FILE_NAME);
+ memcpy(pi_file->filename, PI_FILE_NAME, fn_sz);
+ pi_file->filename[fn_sz] = '\0';
+ pi_file->b_inited = 1;
+ return 0;
+}
+
+int load_po_info_file(po_info_file* pi_file) {
+ if (init_po_info_file(pi_file)) {
+ return -1;
+ }
+ uint8_t* ret_buf = NULL;
+ uint32_t read_sz = 0;
+ int ret = ss_read(&ret_buf, &read_sz, 0, pi_file->filename, &pi_file->cred,
+ SS_OPT_DEFAULT);
+ if (SS_RET_CANT_FIND_REQUESTED_DATA == ret) {
+ pi_file->po_num = 0;
+ return 0;
+ }
+ if (SS_RET_SUCCESS != ret) {
+ MSG("Failed to read from secure storage, ret = %d.", ret);
+ return -1;
+ }
+ if (0 == read_sz) {
+ pi_file->po_num = 0;
+ return 0;
+ }
+ uint32_t po_info_sz = sizeof(persistent_object_info);
+ if (read_sz % po_info_sz) {
+ MSG("po_info file data error.");
+ ss_free_buffer(ret_buf);
+ return -1;
+ }
+ pi_file->po_num = read_sz / po_info_sz;
+ pi_file->po_info = (persistent_object_info*)ret_buf;
+ return 0;
+}
+
+int get_po_info(po_info_file* pi_file, persistent_object_info** po_info,
+ int* po_num) {
+ if (-1 == load_po_info_file(pi_file)) {
+ return -1;
+ }
+ if (0 == pi_file->po_num) {
+ *po_num = 0;
+ return 0;
+ }
+ persistent_object_info* tmp_info = NULL;
+ tmp_info = (persistent_object_info*)OsaMalloc(
+ pi_file->po_num * sizeof(persistent_object_info));
+ if (NULL == tmp_info) {
+ MSG("Failed to alloc memory.");
+ __FREE(pi_file->po_info);
+ return -1;
+ }
+ int32_t i = 0;
+ persistent_object_info* tmp_po_info = pi_file->po_info;
+ for (; i < pi_file->po_num; ++i) {
+ tmp_info[i] = *tmp_po_info;
+ tmp_po_info++;
+ }
+ *po_num = pi_file->po_num;
+ *po_info = tmp_info;
+ __FREE(pi_file->po_info);
+ return 0;
+}
+
+int write_po_info(po_info_file* pi_file, const void* objectID,
+ uint32_t obj_id_len, TEE_ObjectInfo* info) {
+ if (-1 == load_po_info_file(pi_file)) {
+ return -1;
+ }
+ persistent_object_info po_info;
+ memcpy((void*)po_info.object_id, objectID, obj_id_len);
+ po_info.obj_id_len = obj_id_len;
+ po_info.info = *info;
+ persistent_object_info* po_infos = NULL;
+ uint32_t po_info_sz = sizeof(persistent_object_info);
+ po_infos = (persistent_object_info*)OsaMalloc(
+ (pi_file->po_num + 1) * po_info_sz);
+ uint32_t po_num = pi_file->po_num;
+
+ memcpy((void*)po_infos, (void*)pi_file->po_info, po_num * po_info_sz);
+ memcpy((uint8_t*)po_infos + po_num * po_info_sz, (void*)&po_info, po_info_sz);
+
+ pi_file->po_num += 1;
+ __FREE(pi_file->po_info);
+ int ret = ss_write((uint8_t*)po_infos, po_info_sz * pi_file->po_num, 0,
+ pi_file->filename, &pi_file->cred, SS_OPT_DEFAULT);
+ if (SS_RET_SUCCESS != ret) {
+ MSG("Failed to write po stat to secure storage,ret = %d.", ret);
+ __FREE(po_infos);
+ return -1;
+ }
+ __FREE(po_infos);
+ return 0;
+}
+
+int delete_po_info(po_info_file* pi_file, const void* objectID,
+ uint32_t obj_id_len) {
+ persistent_object_info* po_del = NULL;
+
+ if (-1 == load_po_info_file(pi_file)) {
+ return -1;
+ }
+ uint32_t po_info_sz = sizeof(persistent_object_info);
+ po_del = find_po_info(pi_file, objectID, obj_id_len);
+ if (NULL == po_del) {
+ MSG("po info to del not found.");
+ return 0;
+ }
+ uint8_t* po_del_pos = (uint8_t*)po_del;
+ uint8_t* cp_begin = po_del_pos + po_info_sz;
+ uint32_t cp_sz = po_info_sz * pi_file->po_num
+ - (cp_begin - (uint8_t*)pi_file->po_info);
+
+ memcpy(po_del_pos, cp_begin, cp_sz);
+ pi_file->po_num--;
+ int ret = ss_write((uint8_t*)pi_file->po_info, po_info_sz * pi_file->po_num,
+ 0, pi_file->filename, &pi_file->cred, SS_OPT_DEFAULT);
+ if (SS_RET_SUCCESS != ret) {
+ MSG("Failed to write po stat to secure storage,ret = %d.", ret);
+ __FREE(pi_file->po_info);
+ return -1;
+ }
+ __FREE(pi_file->po_info);
+ return 0;
+}
+
+persistent_object_info* find_po_info(po_info_file* pi_file,
+ const void* objectID, uint32_t obj_id_len) {
+ if (NULL == objectID || 0 == obj_id_len) {
+ MSG("objectID is invalid.");
+ return NULL;
+ }
+ int32_t i = 0;
+ int b_find = 0;
+ persistent_object_info* po_info_tmp = pi_file->po_info;
+ for (; i < pi_file->po_num; ++i) {
+ if (0 == memcmp(po_info_tmp->object_id, objectID, obj_id_len)) {
+ b_find = 1;
+ break;
+ }
+ po_info_tmp++;
+ }
+ return (b_find ? po_info_tmp : NULL);
+}
+
+// po share rule
+// TODO: locking mechanism to be improved using pthread locks ORr
+// As ssflib is shared lib, instead of malloc'ing the share_info,
+// just use a global variable, there by no need of locking
+void lock_po_share_info(po_share_info* share_info) {
+ while (share_info->usr_info->lock) {
+ }
+ share_info->usr_info->lock = 1;
+}
+
+void unlock_po_share_info(po_share_info* share_info) {
+ if (share_info->usr_info->lock) {
+ share_info->usr_info->lock = 0;
+ }
+}
+
+int init_share_info(po_share_info* share_info) {
+ if (NULL != share_info->usr_info) {
+ MSG("Share info has been inited.");
+ return 0;
+ }
+ // is the shm exist
+ share_info->usr_info = (po_user*)OsaMalloc(sizeof(po_user));
+ memset(share_info->usr_info, 0, sizeof(po_user));
+#if 0
+ int b_shm_exist = 1;
+ if (0 > shm_open(share_info->name, O_EXCL | O_CREAT, 0666))
+ {
+ b_shm_exist = 1;
+ }
+ share_info->fd = shm_open(share_info->name, O_RDWR | O_CREAT, 0666);
+ if (0 > share_info->fd)
+ {
+ MSG("Failed to open shm %s.", share_info->name);
+ return -1;
+ }
+ // linux posix shm need this
+ if (!b_shm_exist)
+ {
+ ftruncate(share_info->fd, sizeof(po_user));
+ }
+ share_info->usr_info = (po_user*) mmap(NULL, sizeof(po_user),
+ PROT_READ | PROT_WRITE, MAP_SHARED, share_info->fd, 0);
+ if (share_info->usr_info == (void *) 0xFFFFFFFF)
+ {
+ MSG("Failed to mmap shm.");
+ return -1;
+ }
+ if (!b_shm_exist)
+ {
+ share_info->usr_info->lock = 0;
+ memset(share_info->usr_info, 0, sizeof(po_user));
+ }
+#endif
+ return 0;
+}
+
+int check_share_rule(po_share_info* share_info, uint32_t handleFlags, uint32_t origFlags) {
+ if ((NULL == share_info) || (-1 == init_share_info(share_info))) {
+ return -1;
+ }
+ int ret = 0;
+ if(origFlags & TEE_DATA_FLAG_ACCESS_READ && origFlags & TEE_DATA_FLAG_ACCESS_WRITE &&
+ origFlags & TEE_DATA_FLAG_SHARE_READ && origFlags & TEE_DATA_FLAG_SHARE_WRITE) {
+ if(handleFlags != 0 && share_info->usr_info->x_user > 0) {
+ ret = -1;
+ goto out;
+ }
+ }
+ if((origFlags & TEE_DATA_FLAG_ACCESS_READ && !(origFlags & TEE_DATA_FLAG_ACCESS_WRITE) &&
+ handleFlags & TEE_DATA_FLAG_ACCESS_WRITE) ||
+ (origFlags & TEE_DATA_FLAG_ACCESS_WRITE && !(origFlags & TEE_DATA_FLAG_ACCESS_READ) &&
+ handleFlags & TEE_DATA_FLAG_ACCESS_READ)) {
+ ret = -1;
+ goto out;
+ }
+ if ((0 < share_info->usr_info->rs_user &&
+ handleFlags & TEE_DATA_FLAG_ACCESS_READ && !(handleFlags & TEE_DATA_FLAG_SHARE_READ)) ||
+ (0 < share_info->usr_info->ws_user &&
+ handleFlags & TEE_DATA_FLAG_ACCESS_WRITE && !(handleFlags & TEE_DATA_FLAG_SHARE_WRITE))) {
+ ret = -1;
+ goto out;
+ }
+ if ((1 == share_info->usr_info->rs_user && handleFlags & TEE_DATA_FLAG_SHARE_WRITE) ||
+ (1 == share_info->usr_info->ws_user && handleFlags & TEE_DATA_FLAG_SHARE_READ)) {
+ ret = -1;
+ goto out;
+ }
+
+ // no user
+ if ((0 == share_info->usr_info->x_user)
+ && (0 == share_info->usr_info->rs_user)
+ && (0 == share_info->usr_info->ws_user)
+ && (0 == share_info->usr_info->rws_user)) {
+ goto out;
+ }
+ if (handleFlags & TEE_DATA_FLAG_ACCESS_READ) {
+ if (!((handleFlags & TEE_DATA_FLAG_SHARE_READ)
+ && (0 == share_info->usr_info->x_user)
+ && (0 == share_info->usr_info->ws_user))) {
+ ret = -1;
+ goto out;
+ }
+ }
+ if (handleFlags & TEE_DATA_FLAG_ACCESS_WRITE) {
+ if (!((handleFlags & TEE_DATA_FLAG_SHARE_WRITE)
+ && (0 == share_info->usr_info->x_user)
+ && (0 == share_info->usr_info->rs_user))) {
+ ret = -1;
+ goto out;
+ }
+ }
+ if (handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META) {
+ if (!((0 == share_info->usr_info->x_user)
+ && (0 == share_info->usr_info->rs_user)
+ && (0 == share_info->usr_info->ws_user)
+ && (0 == share_info->usr_info->rws_user))) {
+ ret = -1;
+ goto out;
+ }
+ }
+ out: return ret;
+}
+
+int update_share_info(po_share_info* share_info, uint32_t handleFlags,
+ uint32_t origFlags, int b_open, persistent_object* po) {
+ if (NULL == share_info->usr_info) {
+ share_info->usr_info = get_po_user_from_po_list(po->storage_id, po->object_id, po->obj_id_len);
+ if(NULL == share_info->usr_info) {
+ if (-1 == init_share_info(share_info)) {
+ return -1;
+ }
+ }
+ }
+
+ // lock
+ // TODO: Commented for debugging, to be uncommented
+ lock_po_share_info(share_info);
+ int ret = 0;
+ if (b_open) {
+ if (check_share_rule(share_info, handleFlags, origFlags)) {
+ MSG("Access conflict!");
+ ret = 1;
+ goto out;
+ }
+ }
+
+ handleFlags &= ~TEE_HANDLE_FLAG_PERSISTENT;
+ handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED;
+
+ if ((handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META)
+ || (handleFlags & TEE_DATA_FLAG_EXCLUSIVE) || (0 == handleFlags)) {
+ b_open ? share_info->usr_info->x_user++ : share_info->usr_info->x_user--;
+ goto out;
+ }
+ if ((handleFlags & TEE_DATA_FLAG_SHARE_READ)
+ && (handleFlags & TEE_DATA_FLAG_SHARE_WRITE)) {
+ b_open ? share_info->usr_info->rws_user++ :
+ share_info->usr_info->rws_user--;
+ goto out;
+ }
+ if (handleFlags & TEE_DATA_FLAG_SHARE_READ) {
+ b_open ? share_info->usr_info->rs_user++ : share_info->usr_info->rs_user--;
+ goto out;
+ }
+ if (handleFlags & TEE_DATA_FLAG_SHARE_WRITE) {
+ b_open ? share_info->usr_info->ws_user++ : share_info->usr_info->ws_user--;
+ goto out;
+ }
+ if (handleFlags & TEE_DATA_FLAG_ACCESS_READ) {
+ b_open ? share_info->usr_info->rs_user++ : share_info->usr_info->rs_user--;
+ goto out;
+ }
+ if (handleFlags & TEE_DATA_FLAG_ACCESS_WRITE) {
+ b_open ? share_info->usr_info->ws_user++ : share_info->usr_info->ws_user--;
+ goto out;
+ }
+
+ out:
+
+ unlock_po_share_info(share_info);
+ return ret;
+}
+
+int release_share_info(po_share_info* share_info) {
+#if 0
+ if ((NULL == share_info) || (0 > share_info->fd))
+ {
+ MSG("Share info has been inited.");
+ return 0;
+ }
+ shm_unlink(share_info->name);
+#endif
+ if(share_info->usr_info != NULL) {
+ if ((0 == share_info->usr_info->x_user)
+ && (0 == share_info->usr_info->rs_user)
+ && (0 == share_info->usr_info->ws_user)
+ && (0 == share_info->usr_info->rws_user)) {
+ OsaFree(share_info->usr_info);
+ share_info->usr_info = NULL;
+ }
+ }
+ return 0;
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// misc operations
+////////////////////////////////////////////////////////////////////////////////////
+void byte_to_hex(uint8_t* dest, const uint8_t* src, unsigned long src_len) {
+ char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
+ 'c', 'd', 'e', 'f'};
+
+ unsigned long j;
+ for (j = 0; j < src_len; j++) {
+ dest[j * 2] = hexval[((src[j] >> 4) & 0xF)];
+ dest[(j * 2) + 1] = hexval[(src[j]) & 0x0F];
+ }
+}
+
+void convert_TA_UUID(char* uuid, TEE_UUID TA_UUID) {
+ // In its canonical form, a UUID consists of 32 hexadecimal digits, displayed in 5 groups separated by hyphens,
+ // in the form 8-4-4-4-12 for a total of 36 characters(32 digits and 4 '-'). For example:
+ // 550e8400-e29b-41d4-a716-446655440000
+ // Version 4 UUIDs use a scheme relying only on random numbers. This algorithm sets the version number as well
+ // as two reserved bits. All other bits are set using a random or pseudorandom data source.
+ // Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx with hexadecimal digits x and hexadecimal
+ // digits 8, 9, A, or B for y. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.
+
+ char* tmp = uuid;
+
+ snprintf(tmp, 9, "%08x", TA_UUID.timeLow);
+ tmp[8] = '-';
+ tmp += 9;
+ snprintf(tmp, 5, "%04x", TA_UUID.timeMid);
+ tmp[4] = '-';
+ tmp += 5;
+ snprintf(tmp, 5, "%04x", TA_UUID.timeHiAndVersion);
+ tmp[4] = '-';
+ tmp += 5;
+ uint32_t i = 0;
+ for (; i < 2; ++i) {
+ snprintf(tmp, 3,"%02x", TA_UUID.clockSeqAndNode[i]);
+ tmp += 2;
+ }
+ tmp[0] = '-';
+
+ tmp += 1;
+ for (; i < 8; ++i) {
+ snprintf(tmp, 3, "%02x", TA_UUID.clockSeqAndNode[i]);
+ tmp += 2;
+ }
+ MSG("this_uuid : %s ", uuid);
+}
+
+int gen_random(uint8_t* dest, uint8_t data_len) {
+ UCI_HANDLE uh = UCI_ERROR;
+ uh = uci_context_alloc(ID_UCI_X931, UCI_SW_CRYPTOCORE);
+ if (uh == UCI_ERROR || uh == UCI_MEM_ALLOR_ERROR) {
+ return -1;
+ }
+ unsigned char seed[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
+ int ret = uci_prng_seed(uh, seed);
+ if (ret != UCI_SUCCESS) {
+ goto out;
+ }
+ ret = uci_prng_get(uh, data_len * 8, dest);
+ if (ret != UCI_SUCCESS) {
+ goto out;
+ }
+ out: uci_context_free(uh);
+ return ret;
+}
+
+// persistent object list operations
+po_list_node g_po_list = {NULL, NULL, NULL};
+
+void debug_list() {
+ po_list_node* node = g_po_list.next;
+ while (node != NULL) {
+ MSG("PO [%s] ==>", node->po->po_file.file_name);
+ node = node->next;
+ }
+}
+
+void add_to_po_list(persistent_object* po) {
+ if (NULL == po) {
+ return;
+ }
+ po->po_list.po = po;
+ // first po
+ if (NULL == g_po_list.next) {
+ g_po_list.next = &po->po_list;
+ po->po_list.prev = &g_po_list;
+ po->po_list.next = NULL;
+ } else {
+ g_po_list.next->prev = &po->po_list;
+ po->po_list.next = g_po_list.next;
+ po->po_list.prev = &g_po_list;
+ g_po_list.next = &po->po_list;
+ }
+ MSG("=====PO %s added=====", po->po_file.file_name);
+ //debug_list();
+}
+
+void rem_from_po_list(persistent_object* po) {
+ if (NULL == po) {
+ return;
+ }
+ MSG("=====To remove PO %s=====", po->po_file.file_name);
+ //debug_list();
+ if (po->po_list.prev) {
+ po->po_list.prev->next = po->po_list.next;
+ }
+ if (po->po_list.next) {
+ po->po_list.next->prev = po->po_list.prev;
+ }
+ MSG("======PO removed=====");
+ //debug_list();
+}
+
+po_user* get_po_user_from_po_list(uint32_t storageID, const void* objectID,
+ size_t objectIDLen)
+{
+ MSG("=====To find PO %d %s=====", storageID, (char *)objectID);
+ po_list_node* node = g_po_list.next;
+ while (node != NULL) {
+ MSG("======PO list : %d %s =====", node->po->storage_id, node->po->object_id);
+ if(node->po->storage_id == storageID &&
+ strncmp(node->po->object_id, (char*)objectID, objectIDLen) == 0 &&
+ node->po->share_info.usr_info != NULL)
+ {
+ MSG("======PO find =====");
+ return node->po->share_info.usr_info;
+ }
+ node = node->next;
+ }
+ MSG("======PO find end=====");
+ return NULL;
+}
+
+void cleanup(void) {
+ po_list_node* node = g_po_list.next;
+ while (NULL != node) {
+ TEE_CloseObject((TEE_ObjectHandle)node->po);
+ node = node->next;
+ }
+}
+
+void regist_clean_up() {
+ static int b_reg = 0;
+ if (b_reg) {
+ return;
+ }
+ if (0 == atexit(cleanup)) {
+ b_reg = 1;
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// object general operations
+////////////////////////////////////////////////////////////////////////////////////
+void TEE_GetObjectInfo(TEE_ObjectHandle object, TEE_ObjectInfo* objectInfo) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ if (objectInfo) {
+ objectInfo->objectType = object->tr.info.objectType;
+ objectInfo->objectSize = object->tr.info.objectSize;
+ objectInfo->maxObjectSize = object->tr.info.maxObjectSize;
+ objectInfo->objectUsage = object->tr.info.objectUsage;
+ objectInfo->dataSize = object->tr.info.dataSize;
+ objectInfo->dataPosition = object->tr.info.dataPosition;
+ objectInfo->handleFlags = object->tr.info.handleFlags;
+ }
+}
+
+// usage ??
+void TEE_RestrictObjectUsage(TEE_ObjectHandle object, uint32_t objectUsage) {
+ object->tr.info.objectUsage &= objectUsage;
+}
+
+TEE_Result TEE_GetObjectBufferAttribute(TEE_ObjectHandle object,
+ uint32_t attributeID, void* buffer, size_t* size) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ uint32_t len;
+ int i, n = -1;
+ TransientObject * obj = &object->tr;
+
+ if (!(obj->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ // search for attributeID in attr_array
+ for (i = 0; i < obj->attr.attr_number; i++) {
+ if (obj->attr.attr_array[i].attributeID == attributeID) {
+ n = i;
+ break;
+ }
+ }
+ if (n == -1) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ // bit[29] == 1 -> not a buffer attribute
+ if (attributeID & TEE_ATTR_FLAG_VALUE) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ // protected attribute
+ if (!(attributeID & TEE_ATTR_FLAG_PUBLIC)
+ && !(obj->info.objectUsage & TEE_USAGE_EXTRACTABLE)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ //len = ((obj->attr.attr_array[n].content.ref.length & 0x7FFFFFFF) + 7) >> 3 ;
+ len = (obj->attr.attr_array[n].content.ref.length + 7) >> 3;
+
+ // out buffer is too small
+ if (len > *size) {
+ return TEE_ERROR_SHORT_BUFFER;
+ }
+ memcpy(buffer, obj->attr.attr_array[n].content.ref.buffer, len);
+ *size = len;
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_GetObjectValueAttribute(TEE_ObjectHandle object,
+ uint32_t attributeID, uint32_t* a, uint32_t* b) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ int i, n = -1;
+ TransientObject * obj = &object->tr;
+
+ if (!(obj->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ // search for attributeID in attr_array
+ for (i = 0; i < obj->attr.attr_number; i++) {
+ if (obj->attr.attr_array[i].attributeID == attributeID) {
+ n = i;
+ break;
+ }
+ }
+ if (n == -1) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ // bit[29] == 0 -> not a value attribute
+ if (!(attributeID & TEE_ATTR_FLAG_VALUE)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ // protected attribute
+ if (!(attributeID & TEE_ATTR_FLAG_PUBLIC)
+ && !(obj->info.objectUsage & TEE_USAGE_EXTRACTABLE)) {
+ return TEE_ERROR_ACCESS_DENIED;
+ }
+ if (a) {
+ *a = obj->attr.attr_array[i].content.value.a;
+ }
+ if (b) {
+ *b = obj->attr.attr_array[i].content.value.b;
+ }
+ return TEE_SUCCESS;
+}
+
+void TEE_CloseObject(TEE_ObjectHandle object) {
+ if (object == TEE_HANDLE_NULL) {
+ return;
+ }
+ if (object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) // persistent object
+ {
+ persistent_object *po = (persistent_object*)object;
+ close_po(po);
+ } else {
+ TEE_FreeTransientObject(object);
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// Transient Object operations
+////////////////////////////////////////////////////////////////////////////////////
+TEE_Result TEE_AllocateTransientObject(uint32_t objectType,
+ uint32_t maxObjectSize, TEE_ObjectHandle* object) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ TEE_Result rc;
+
+
+ TransientObject * tr = (TransientObject*)OsaMalloc(sizeof(TransientObject));
+ if (!tr) {
+ OsaFree(tr);
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ memset(tr, 0, sizeof(TransientObject));
+ rc = allocate_transient_object(tr, objectType, maxObjectSize);
+ if (rc != TEE_SUCCESS) {
+ OsaFree(tr);
+ return rc;
+ }
+ *object = (TEE_ObjectHandle)&tr->info;
+ return TEE_SUCCESS;
+}
+
+void TEE_FreeTransientObject(TEE_ObjectHandle object) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ TransientObject * tr = NULL;
+ if (object == TEE_HANDLE_NULL) {
+ return;
+ }
+ tr = &object->tr;
+ TEE_Attribute* attrs = tr->attr.attr_array;
+ int i;
+ for (i = 0; i < tr->attr.attr_number; ++i) {
+ free_attribute(&attrs[i]);
+ }
+ memset(&tr->attr, 0, sizeof(tr->attr));
+ OsaFree(tr);
+}
+
+void TEE_ResetTransientObject(TEE_ObjectHandle object) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ TransientObject* tr;
+ if (object == TEE_HANDLE_NULL) {
+ return;
+ }
+ tr = &object->tr;
+ TEE_Attribute* attrs = tr->attr.attr_array;
+ int i;
+ for (i = 0; i < tr->attr.attr_number; ++i) {
+ free_attribute(&attrs[i]);
+ }
+ memset(tr->attr.attr_array, 0, sizeof(tr->attr.attr_array));
+ tr->attr.attr_number = 0;
+
+ tr->info.objectSize = 0;
+ tr->info.dataSize = 0;
+ tr->info.dataPosition = 0;
+ tr->info.handleFlags = 0;
+ tr->info.objectUsage = 0xffffffff;
+}
+
+TEE_Result TEE_PopulateTransientObject(TEE_ObjectHandle object,
+ const TEE_Attribute* attrs, uint32_t attrCount) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ unsigned int i;
+
+ TransientObject* tr = &object->tr;
+ if (tr->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ TEE_Attribute* curr_attr = &tr->attr.attr_array[tr->attr.attr_number];
+ for (i = 0; i < attrCount; i++) {
+
+ if (attrs[i].content.ref.length > tr->info.maxObjectSize) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ copy_attribute(&curr_attr[i], (TEE_Attribute*)&attrs[i]);
+ tr->attr.attr_number++;
+ tr->info.objectSize =
+ tr->info.objectSize > attrs[i].content.ref.length ?
+ tr->info.objectSize : attrs[i].content.ref.length;
+ }
+
+ switch (tr->info.objectType) {
+ case TEE_TYPE_AES:
+ case TEE_TYPE_DES:
+ case TEE_TYPE_DES3:
+ case TEE_TYPE_HMAC_MD5:
+ case TEE_TYPE_HMAC_SHA1:
+ case TEE_TYPE_HMAC_SHA224:
+ case TEE_TYPE_HMAC_SHA256:
+ case TEE_TYPE_HMAC_SHA384:
+ case TEE_TYPE_HMAC_SHA512:
+ case TEE_TYPE_GENERIC_SECRET:
+ if (tr->attr.attr_number != 1) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ break;
+ case TEE_TYPE_RSA_PUBLIC_KEY:
+ case TEE_TYPE_RSA_KEYPAIR: {
+ // Krishna: Incorrect to check this condition
+ /*if ((tr->info.objectType == TEE_TYPE_RSA_KEYPAIR)
+ && (tr->attr.attr_number != 3) && (tr->attr.attr_number != 8)) {
+ TZ_ERROR("tr->attr.attr_number = %d\n", tr->attr.attr_number);
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }*/
+ if ((tr->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY)
+ && (tr->attr.attr_number != 2)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ }
+ break;
+ case TEE_TYPE_DSA_PUBLIC_KEY:
+ case TEE_TYPE_DSA_KEYPAIR: {
+ if ((tr->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY)
+ && (tr->attr.attr_number != 4)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ } else if ((tr->info.objectType == TEE_TYPE_DSA_KEYPAIR)
+ && (tr->attr.attr_number != 5)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ }
+ break;
+ case TEE_TYPE_DH_KEYPAIR: {
+ if ((tr->attr.attr_number != 3) && (tr->attr.attr_number != 4)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ }
+ break;
+ default:
+ return TEE_ERROR_BAD_PARAMETERS;
+ }
+ tr->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
+ return TEE_SUCCESS;
+}
+
+void TEE_InitRefAttribute(TEE_Attribute* attr, uint32_t attributeID,
+ const void* buffer, size_t length) {
+ attr->attributeID = attributeID;
+ attr->content.ref.buffer = buffer;
+ attr->content.ref.length = length;
+}
+
+void TEE_InitValueAttribute(TEE_Attribute* attr, uint32_t attributeID,
+ uint32_t a, uint32_t b) {
+ attr->attributeID = attributeID;
+ attr->content.value.a = a;
+ attr->content.value.b = b;
+}
+
+void TEE_CopyObjectAttributes(TEE_ObjectHandle destObject,
+ TEE_ObjectHandle srcObject) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ int attrCount, i;
+ //int offset = 0;
+ TEE_Attribute * attrs;
+
+ TransientObject* src = &srcObject->tr;
+ TransientObject* dest = &destObject->tr;
+
+ if (dest->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ dest->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
+ if (!(src->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ // check compatibility of source & destination
+ if (!((src->info.objectType == dest->info.objectType)
+ || ((dest->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY)
+ && (src->info.objectType == TEE_TYPE_RSA_KEYPAIR))
+ || ((dest->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY)
+ && (src->info.objectType == TEE_TYPE_DSA_KEYPAIR)))) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (src->info.objectSize > dest->info.maxObjectSize) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ dest->info.objectUsage &= src->info.objectUsage;
+ // copy attributes
+ attrs = src->attr.attr_array;
+ attrCount = src->attr.attr_number;
+ //offset = 0;
+ for (i = 0; i < attrCount; i++) {
+ copy_attribute(&dest->attr.attr_array[i], &attrs[i]);
+ dest->attr.attr_number++;
+ }
+}
+
+TEE_Result TEE_GenerateKey(TEE_ObjectHandle object, uint32_t keySize,
+ const TEE_Attribute* params, uint32_t paramCount) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ char key[256];
+ TEE_Attribute attrs[MAX_ATTRIBUTE_NUMBER];
+ unsigned int i, check = 0;
+ TransientObject* tr = &object->tr;
+
+ if (tr->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (keySize > tr->info.maxObjectSize) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ tr->info.objectSize = keySize;
+ switch (tr->info.objectType) {
+ case TEE_TYPE_AES:
+ case TEE_TYPE_DES:
+ case TEE_TYPE_DES3:
+ case TEE_TYPE_HMAC_MD5:
+ case TEE_TYPE_HMAC_SHA1:
+ case TEE_TYPE_HMAC_SHA224:
+ case TEE_TYPE_HMAC_SHA256:
+ case TEE_TYPE_HMAC_SHA384:
+ case TEE_TYPE_HMAC_SHA512:
+ case TEE_TYPE_GENERIC_SECRET:
+ // generate 1 random key
+ gen_random((unsigned char*)key, (keySize + 7) / 8);
+ TEE_InitRefAttribute(&attrs[0], TEE_ATTR_SECRET_VALUE, key, keySize);
+ TEE_PopulateTransientObject(object, attrs, 1);
+ break;
+ case TEE_TYPE_RSA_KEYPAIR: {
+ uci_key_s uci_key;
+ int key_size = (keySize + 7) / 8;
+ uci_key.ucik_rsa_n = (unsigned char*)OsaMalloc(key_size);
+ uci_key.ucik_rsa_n_len = key_size;
+ uci_key.ucik_rsa_e = (unsigned char*)OsaMalloc(key_size);
+ uci_key.ucik_rsa_e_len = key_size;
+ uci_key.ucik_rsa_d = (unsigned char*)OsaMalloc(key_size);
+ uci_key.ucik_rsa_d_len = key_size;
+ uci_param_s up;
+ up.ucip_rsa_flag = RSA_GENKEYWITHNON;
+ up.ucip_rsa_padding = ID_UCI_RSAES_PKCS15;
+ //alg
+ int alg = ID_UCI_RSA;
+ if (512 == keySize) {
+ alg = ID_UCI_RSA512;
+ } else if (1024 == keySize) {
+ alg = ID_UCI_RSA1024;
+ } else if (2048 == keySize) {
+ alg = ID_UCI_RSA2048;
+ } else if (3072 == keySize) {
+ alg = ID_UCI_RSA3072;
+ }
+ UCI_HANDLE uh = uci_context_alloc(alg, UCI_SW);
+ uci_ae_gen_keypair(uh, &uci_key, &up);
+ uci_context_free(uh);
+
+ TEE_InitRefAttribute(&attrs[0], TEE_ATTR_RSA_MODULUS, uci_key.ucik_rsa_n,
+ keySize);
+ TEE_InitRefAttribute(&attrs[1], TEE_ATTR_RSA_PUBLIC_EXPONENT,
+ uci_key.ucik_rsa_e, keySize);
+ TEE_InitRefAttribute(&attrs[2], TEE_ATTR_RSA_PRIVATE_EXPONENT,
+ uci_key.ucik_rsa_d, keySize);
+ TEE_PopulateTransientObject(object, attrs, 3);
+
+ OsaFree(uci_key.ucik_rsa_n);
+ OsaFree(uci_key.ucik_rsa_e);
+ OsaFree(uci_key.ucik_rsa_d);
+ }
+ break;
+
+ case TEE_TYPE_DSA_KEYPAIR: {
+ uci_key_s uci_key;
+ int key_size = (keySize + 7) / 8;
+ uci_key.ucik_dsa_pubk_len = key_size;
+ uci_key.ucik_dsa_pubkey = (unsigned char*)OsaMalloc(key_size);
+ uci_key.ucik_dsa_privk_len = key_size;
+ uci_key.ucik_dsa_privkey = (unsigned char*)OsaMalloc(key_size);
+ uci_param_s up;
+ up.ucip_dsa_tsize = 0;
+
+ // check the mandatory attributes
+ for (i = 0; i < paramCount; i++) {
+ if (params[i].attributeID == TEE_ATTR_DSA_PRIME) {
+ up.ucip_dsa_p = (unsigned char*)params[i].content.ref.buffer;
+ up.ucip_dsa_p_len = (params[i].content.ref.length + 7) / 8;
+ check |= 0x01;
+ } else if (params[i].attributeID == TEE_ATTR_DSA_BASE) {
+ up.ucip_dsa_g = (unsigned char*)params[i].content.ref.buffer;
+ up.ucip_dsa_g_len = (params[i].content.ref.length + 7) / 8;
+ check |= 0x02;
+ } else if (params[i].attributeID == TEE_ATTR_DSA_SUBPRIME) {
+ up.ucip_dsa_q = (unsigned char*)params[i].content.ref.buffer;
+ up.ucip_dsa_q_len = (params[i].content.ref.length + 7) / 8;
+ check |= 0x04;
+ }
+ }
+ if (check != 0x07) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ // generate public & private keys. algorithm is the same as for DH
+ UCI_HANDLE handle = uci_context_alloc(ID_UCI_DSA, UCI_SW);
+ uci_ae_gen_keypair(handle, &uci_key, &up);
+ uci_context_free(handle);
+ for (i = 0; i < paramCount; i++) {
+ TEE_InitRefAttribute(&attrs[i], params[i].attributeID,
+ params[i].content.ref.buffer, params[i].content.ref.length);
+ }
+ TEE_InitRefAttribute(&attrs[3], TEE_ATTR_DSA_PUBLIC_VALUE,
+ uci_key.ucik_dsa_pubkey, uci_key.ucik_dsa_pubk_len * 8);
+ TEE_InitRefAttribute(&attrs[4], TEE_ATTR_DSA_PRIVATE_VALUE,
+ uci_key.ucik_dsa_privkey, uci_key.ucik_dsa_privk_len * 8);
+ TEE_PopulateTransientObject(object, attrs, 5);
+ OsaFree(uci_key.ucik_dsa_pubkey);
+ OsaFree(uci_key.ucik_dsa_privkey);
+ }
+ break;
+
+ case TEE_TYPE_DH_KEYPAIR: {
+ int key_size = (keySize + 7) / 8;
+ uint8_t* privKey = (unsigned char*)OsaMalloc(key_size);
+ uint8_t* pubKey = (unsigned char*)OsaMalloc(key_size);
+ uci_param_s uciparam;
+
+ for (i = 0; i < paramCount; i++) {
+ if (params[i].attributeID == TEE_ATTR_DH_PRIME) {
+ check |= 0x01;
+ uciparam.ucip_dh_prime = (unsigned char*)params[i].content.ref.buffer;
+ uciparam.ucip_dh_len = (params[i].content.ref.length + 7) / 8;
+ } else if (params[i].attributeID == TEE_ATTR_DH_BASE) {
+ check |= 0x02;
+ uciparam.ucip_dh_generator = (unsigned char*)params[i].content.ref
+ .buffer;
+ }
+ }
+ if (check != 0x03) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ UCI_HANDLE handle = uci_context_alloc(ID_UCI_DH, UCI_SW);
+ uci_dh_gen_phasekey(handle, privKey, pubKey, &uciparam);
+ uci_context_free(handle);
+ for (i = 0; i < paramCount; i++) {
+ TEE_InitRefAttribute(&attrs[i], params[i].attributeID,
+ params[i].content.ref.buffer, params[i].content.ref.length);
+ }
+ TEE_InitRefAttribute(&attrs[2], TEE_ATTR_DH_PRIVATE_VALUE, privKey,
+ keySize);
+ TEE_InitRefAttribute(&attrs[3], TEE_ATTR_DH_PUBLIC_VALUE, pubKey,
+ keySize);
+ TEE_PopulateTransientObject(object, attrs, 4);
+
+ OsaFree(privKey);
+ OsaFree(pubKey);
+ }
+ break;
+ }
+ return TEE_SUCCESS;
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// Persistent object operations
+////////////////////////////////////////////////////////////////////////////////////
+
+TEE_Result TEE_CreatePersistentObject(uint32_t storageID, const void* objectID,
+ size_t objectIDLen, uint32_t flags, TEE_ObjectHandle attributes,
+ const void* initialData, size_t initialDataLen, TEE_ObjectHandle* object) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ persistent_object* po = NULL;
+ TEE_Result rc = allocate_persistent_object(&po, storageID, objectID,
+ objectIDLen, flags);
+ TransientObject* tr_obj = NULL;
+ if (TEE_HANDLE_NULL != attributes) {
+ tr_obj = &attributes->tr;
+ }
+ rc = exist_po(po);
+ // already exist
+ if (TEE_SUCCESS == rc) {
+ if (flags & TEE_DATA_FLAG_EXCLUSIVE) {
+ MSG("Persistent object already exist.");
+ FREE_PO(po);
+ return TEE_ERROR_ACCESS_CONFLICT;
+ }
+ if (!object) {
+ FREE_PO(po);
+ return TEE_SUCCESS;
+ }
+ rc = open_po(po);
+ } else {
+ rc = create_po(po, tr_obj, initialData, initialDataLen);
+ }
+ if (rc) {
+ FREE_PO(po);
+ return rc;
+ }
+ if (object) {
+ *object = (TEE_ObjectHandle)&po->attr.info;
+ } else {
+ close_po(po);
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_OpenPersistentObject(uint32_t storageID, const void* objectID,
+ size_t objectIDLen, uint32_t flags, TEE_ObjectHandle* object) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ persistent_object* po = NULL;
+ TEE_Result rc = allocate_persistent_object(&po, storageID, objectID,
+ objectIDLen, flags);
+ if (rc) {
+ return rc;
+ }
+ rc = open_po(po);
+ if (rc) {
+ FREE_PO(po);
+ return rc;
+ }
+ *object = (TEE_ObjectHandle)&po->attr.info;
+ return TEE_SUCCESS;
+}
+
+void TEE_CloseAndDeletePersistentObject(TEE_ObjectHandle object) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ persistent_object* op;
+ if (object == TEE_HANDLE_NULL) {
+ return;
+ }
+ if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ op = (persistent_object*)object;
+ if (!(op->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ free_po(op);
+}
+
+TEE_Result TEE_RenamePersistentObject(TEE_ObjectHandle object,
+ const void* newObjectID, size_t newObjectIDLen) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ if (object == TEE_HANDLE_NULL) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
+ // transient object
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ persistent_object* po;
+ po = (persistent_object*)object;
+ if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_EXCLUSIVE) &&
+ !(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE_META)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (newObjectIDLen > TEE_OBJECT_ID_MAX_LEN) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ return rename_po(po, newObjectID, newObjectIDLen);
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// Persistent enumerator operations
+////////////////////////////////////////////////////////////////////////////////////
+TEE_Result TEE_AllocatePersistentObjectEnumerator(
+ TEE_ObjectEnumHandle* objectEnumerator) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ struct __TEE_ObjectEnumHandle* eh;
+ eh = (struct __TEE_ObjectEnumHandle *)OsaMalloc(
+ sizeof(struct __TEE_ObjectEnumHandle));
+ if (!eh) {
+ return TEE_ERROR_OUT_OF_MEMORY;
+ }
+ eh->po_info = NULL;
+ eh->po_num = 0;
+ eh->curr_position = 0;
+ eh->state = ENUM_STATE_INIT;
+
+ *objectEnumerator = eh;
+ return TEE_SUCCESS;
+}
+
+void TEE_FreePersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ if (TEE_HANDLE_NULL == objectEnumerator) {
+ return;
+ }
+ __FREE(objectEnumerator->po_info);
+ __FREE(objectEnumerator);
+}
+
+void TEE_ResetPersistentObjectEnumerator(TEE_ObjectEnumHandle objectEnumerator) {
+ PERMISSION_CHECK_RETURN_VOID(PERM_STORAGE);
+ if (TEE_HANDLE_NULL == objectEnumerator) {
+ return;
+ }
+ objectEnumerator->curr_position = 0;
+ objectEnumerator->po_num = 0;
+ objectEnumerator->state = ENUM_STATE_INIT;
+ __FREE(objectEnumerator->po_info);
+ objectEnumerator->po_info = NULL;
+}
+
+TEE_Result TEE_StartPersistentObjectEnumerator(
+ TEE_ObjectEnumHandle objectEnumerator, uint32_t storageID) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ if (TEE_HANDLE_NULL == objectEnumerator) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (storageID != TEE_STORAGE_PRIVATE) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ TEE_UUID uuid;
+ if (0 != get_uuid()) {
+ MSG("Failed to get UUID of TA.");
+ return -1;
+ }
+ uuid = this_uuid;
+
+ if (objectEnumerator->state == ENUM_STATE_STARTED) {
+ TEE_ResetPersistentObjectEnumerator(objectEnumerator);
+ }
+ int ret = get_po_info(&g_po_info_file, &objectEnumerator->po_info,
+ &objectEnumerator->po_num);
+ if (ret || !objectEnumerator->po_num) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ objectEnumerator->state = ENUM_STATE_STARTED;
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_GetNextPersistentObject(TEE_ObjectEnumHandle objectEnumerator,
+ TEE_ObjectInfo* objectInfo, void* objectID, size_t* objectIDLen) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ if (TEE_HANDLE_NULL == objectEnumerator) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if ((objectEnumerator->state != ENUM_STATE_STARTED)
+ || (objectEnumerator->state == ENUM_STATE_END)) {
+ return TEE_ERROR_ITEM_NOT_FOUND;
+ }
+ persistent_object_info* po_info = objectEnumerator->po_info;
+ int curr_pos = objectEnumerator->curr_position;
+ *objectInfo = po_info[curr_pos].info;
+ *objectIDLen = po_info[curr_pos].obj_id_len;
+ memcpy(objectID, po_info[curr_pos].object_id, po_info[curr_pos].obj_id_len);
+
+ objectEnumerator->curr_position++;
+ if (objectEnumerator->curr_position >= objectEnumerator->po_num) {
+ objectEnumerator->state = ENUM_STATE_END;
+ }
+ return TEE_SUCCESS;
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+// Data stream access operations
+////////////////////////////////////////////////////////////////////////////////////
+
+TEE_Result TEE_ReadObjectData(TEE_ObjectHandle object, void* buffer,
+ size_t size, uint32_t* count) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ int num;
+ if (object == TEE_HANDLE_NULL) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ persistent_object* po = (persistent_object*)object;
+ if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_READ)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (size == 0) {
+ num = 0;
+ } else {
+ TEE_Result rc = read_object_data(po, buffer, size, (uint32_t*)&num);
+ if (rc) {
+ return rc;
+ }
+ }
+ *count = num;
+#if 0 /* Prevent slow-processing */
+ MSG("Data read is:");
+ printhex((unsigned char*)buffer, num);
+#endif
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_WriteObjectData(TEE_ObjectHandle object, const void* buffer,
+ size_t size) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ if (object == TEE_HANDLE_NULL) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ persistent_object* po = (persistent_object*)object;
+ if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (size != 0) {
+ return write_object_data(po, buffer, size);
+ }
+ return TEE_SUCCESS;
+}
+
+TEE_Result TEE_TruncateObjectData(TEE_ObjectHandle object, uint32_t size) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ if (object == TEE_HANDLE_NULL) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ persistent_object* po = (persistent_object*)object;
+ if (!(po->attr.info.handleFlags & TEE_DATA_FLAG_ACCESS_WRITE)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ return truncate_object_data(po, size);
+}
+
+TEE_Result TEE_SeekObjectData(TEE_ObjectHandle object, int32_t offset,
+ TEE_Whence whence) {
+ PERMISSION_CHECK(PERM_STORAGE);
+ if (object == TEE_HANDLE_NULL) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ if (!(object->tr.info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT)) {
+ TZ_ERROR("operation error line = %d,%s\n", __LINE__, __func__);
+ TEE_Panic(0);
+ }
+ persistent_object* po = (persistent_object*)object;
+ return seek_object_data(po, offset, whence);
+}
+++ /dev/null
-/*
- * =====================================================================================
- *
- * Filename: ssf_taentrypoint.c
- *
- * Description: SSF TA Internal functions
- *
- * Version: 1.0
- * Created: 20 April 2015 12:41:39 IST
- * Revision: Original
- * Compiler: gcc
- *
- * Author: krishna (Kr), k.devale@samsung.com
- * Organization: Samsung Electronics
- *
- * =====================================================================================
- */
-
-/*-----------------------------------------------------------------------------
- * Include files
- *-----------------------------------------------------------------------------*/
-#include "ssf_lib.h"
-#include "ssf_client.h"
-#include <unistd.h>
-#ifdef __DEBUG__
-#include <stdio.h>
-#endif
-
-/*-----------------------------------------------------------------------------
- * TEE Internal API implementation
- *-----------------------------------------------------------------------------*/
-
-TEE_Result TEE_OpenTASession(const TEE_UUID* destination,
- uint32_t cancellationRequestTimeout, uint32_t paramTypes,
- TEE_Param params[4], TEE_TASessionHandle* session, uint32_t* returnOrigin) {
-
- IntTAOpenSessionData data;
- data.destination = *destination;
- data.cancelTimeOut = cancellationRequestTimeout;
- data.operation.paramTypes = paramTypes;
-
- memcpy(data.operation.params, params, sizeof(TEE_Param[4]));
-
- pthread_mutex_lock(&socketLock);
- sendCommand(socketSimulatorDaemonFD, OPEN_TA_SESSION, &data,
- sizeof(IntTAOpenSessionData));
- pthread_mutex_unlock(&socketLock);
-#if 0
- printf("Inside: %s \n", __FUNCTION__);
- data.params[0].value.a = 1;
- data.params[0].value.b = 1;
- data.params[1].value.a = 2;
- data.params[1].value.b = 2;
- data.params[2].value.a = 3;
- data.params[2].value.b = 3;
- data.params[3].value.a = 4;
- data.params[3].value.b = 4;
- data.returnOrigin = TEE_ORIGIN_TRUSTED_APP;
- data.returnValue = TEE_SUCCESS;
-#endif
-
- // Return from the function call
- // [inout] TEE_Param params[4],
- // [out] TEE_TASessionHandle* session,
- // [out] uint32_t* returnOrigin);
- uint32_t* sessionData = (uint32_t*)OsaMalloc(sizeof(uint32_t));
- memcpy(params, data.operation.params, sizeof(TEE_Param[4]));
- *sessionData = data.session;
- *session = (TEE_TASessionHandle)sessionData;
- *returnOrigin = data.returnOrigin;
- return data.returnValue;
-}
-
-void TEE_CloseTASession(TEE_TASessionHandle session) {
-
- IntTACloseSessionData data;
- data.session = *(uint32_t*)session;
- pthread_mutex_lock(&socketLock);
- sendCommand(socketSimulatorDaemonFD, CLOSE_TA_SESSION, &data,
- sizeof(IntTACloseSessionData));
- pthread_mutex_unlock(&socketLock);
- OsaFree(session);
-}
-
-TEE_Result TEE_InvokeTACommand(TEE_TASessionHandle session,
- uint32_t cancellationRequestTimeout, uint32_t commandID,
- uint32_t paramTypes, TEE_Param params[4], uint32_t* returnOrigin) {
- IntTAInvokeCommandData data;
- data.session = *(uint32_t*)session;
- data.cancelTimeOut = cancellationRequestTimeout;
- data.commandID = commandID;
- data.operation.paramTypes = paramTypes;
- memcpy(data.operation.params, params, sizeof(TEE_Param[4]));
- pthread_mutex_lock(&socketLock);
- sendCommand(socketSimulatorDaemonFD, INVOKE_TA_COMMAND, &data,
- sizeof(IntTAInvokeCommandData));
- pthread_mutex_unlock(&socketLock);
-#if 0
- printf("Inside: %s \n", __FUNCTION__);
- data.params[0].value.a = 1;
- data.params[0].value.b = 1;
- data.params[1].value.a = 2;
- data.params[1].value.b = 2;
- data.params[2].value.a = 3;
- data.params[2].value.b = 3;
- data.params[3].value.a = 4;
- data.params[3].value.b = 4;
-
- data.returnOrigin = TEE_ORIGIN_TRUSTED_APP;
- data.returnValue = TEE_SUCCESS;
-#endif
- // Return from the function call
- // [inout] TEE_Param params[4],
- // [out] uint32_t* returnOrigin);
- memcpy(params, data.operation.params, sizeof(TEE_Param[4]));
- *returnOrigin = data.returnOrigin;
- return data.returnValue;
-}
--- /dev/null
+/*
+ * =====================================================================================
+ *
+ * Filename: ssf_taentrypoint.c
+ *
+ * Description: SSF TA Internal functions
+ *
+ * Version: 1.0
+ * Created: 20 April 2015 12:41:39 IST
+ * Revision: Original
+ * Compiler: gcc
+ *
+ * Author: krishna (Kr), k.devale@samsung.com
+ * Organization: Samsung Electronics
+ *
+ * =====================================================================================
+ */
+
+/*-----------------------------------------------------------------------------
+ * Include files
+ *-----------------------------------------------------------------------------*/
+#include "ssf_lib.h"
+#include "ssf_client.h"
+#include <unistd.h>
+#ifdef __DEBUG__
+#include <stdio.h>
+#endif
+#include "../../TEEStub/TACommands/SharedMemoryMap.h"
+
+/*-----------------------------------------------------------------------------
+ * TEE Internal API implementation
+ *-----------------------------------------------------------------------------*/
+extern TEE_UUID ssf_sharedthisTAUUID;
+
+#define __TEE_Preprocess_Operation \
+ uint32_t i, type; \
+ for (i = 0; i < 4; i++) { \
+ type = ((data.operation.paramTypes) >> (8 * i)) & 0x7f; \
+ if ((type == TEEC_VALUE_INPUT) || (type == TEEC_VALUE_OUTPUT) \
+ || (type == TEEC_VALUE_INOUT)) { \
+ data.operation.params[i].value.a = params[i].value.a; \
+ data.operation.params[i].value.b = params[i].value.b; \
+ } else if (type == TEEC_NONE) { \
+ } else { \
+ int getOffset = 0; \
+ if(params[i].memref.memid == 0) { \
+ params[i].memref.memid = getSharedMemoryShmID(params[i].memref.buffer); \
+ } else { \
+ char* getAdd = getSharedMemoryAddress(params[i].memref.memid); \
+ if(getAdd != 0) \
+ getOffset = (char*)params[i].memref.buffer - getAdd; \
+ } \
+ data.operation.params[i].mem.offset = getOffset; \
+ data.operation.params[i].mem.size = params[i].memref.size; \
+ data.operation.params[i].mem.shmKey = params[i].memref.memid; \
+ } \
+ }
+
+#define __TEE_Postprocess_Operation \
+ uint32_t i, type; \
+ for (i = 0; i < 4; i++) { \
+ type = ((data.operation.paramTypes) >> (8 * i)) & 0x7f; \
+ if ((type == TEEC_VALUE_INPUT) || (type == TEEC_VALUE_OUTPUT) \
+ || (type == TEEC_VALUE_INOUT)) { \
+ params[i].value.a = data.operation.params[i].value.a; \
+ params[i].value.b = data.operation.params[i].value.b; \
+ } else if (type == TEEC_NONE) { \
+ } else { \
+ params[i].memref.size = data.operation.params[i].mem.size; \
+ params[i].memref.memid = data.operation.params[i].mem.shmKey; \
+ } \
+ }
+
+TEE_Result TEE_OpenTASession(const TEE_UUID* destination,
+ uint32_t cancellationRequestTimeout, uint32_t paramTypes,
+ TEE_Param params[4], TEE_TASessionHandle* session, uint32_t* returnOrigin) {
+
+ IntTAOpenSessionData data;
+ if (returnOrigin) {
+ *returnOrigin = TEE_ORIGIN_API;
+ }
+ if (!session || !destination) {
+ return TEE_ERROR_BAD_PARAMETERS;
+ }
+ memset(&data, 0, sizeof(IntTAOpenSessionData));
+ data.source = ssf_sharedthisTAUUID;
+ data.destination = *destination;
+ data.cancelTimeOut = cancellationRequestTimeout;
+ data.operation.paramTypes = paramTypes;
+ if(params != 0)
+ {
+ __TEE_Preprocess_Operation;
+ }
+
+ pthread_mutex_lock(&socketLock);
+ sendCommand(socketSimulatorDaemonFD, OPEN_TA_SESSION, &data,
+ sizeof(IntTAOpenSessionData));
+ pthread_mutex_unlock(&socketLock);
+#if 0
+ printf("Inside: %s \n", __FUNCTION__);
+ data.params[0].value.a = 1;
+ data.params[0].value.b = 1;
+ data.params[1].value.a = 2;
+ data.params[1].value.b = 2;
+ data.params[2].value.a = 3;
+ data.params[2].value.b = 3;
+ data.params[3].value.a = 4;
+ data.params[3].value.b = 4;
+ data.returnOrigin = TEE_ORIGIN_TRUSTED_APP;
+ data.returnValue = TEE_SUCCESS;
+#endif
+
+ // Return from the function call
+ // [inout] TEE_Param params[4],
+ // [out] TEE_TASessionHandle* session,
+ // [out] uint32_t* returnOrigin);
+ uint32_t* sessionData = (uint32_t*)OsaMalloc(sizeof(uint32_t));
+ if(params != NULL)
+ {
+ __TEE_Postprocess_Operation;
+ }
+ *sessionData = data.session;
+ *session = (TEE_TASessionHandle)sessionData;
+ if (returnOrigin)
+ *returnOrigin = TEE_ORIGIN_TRUSTED_APP;
+ return data.returnValue;
+}
+
+void TEE_CloseTASession(TEE_TASessionHandle session) {
+
+ IntTACloseSessionData data;
+ data.session = *(uint32_t*)session;
+ pthread_mutex_lock(&socketLock);
+ sendCommand(socketSimulatorDaemonFD, CLOSE_TA_SESSION, &data,
+ sizeof(IntTACloseSessionData));
+ pthread_mutex_unlock(&socketLock);
+ OsaFree(session);
+}
+
+TEE_Result TEE_InvokeTACommand(TEE_TASessionHandle session,
+ uint32_t cancellationRequestTimeout, uint32_t commandID,
+ uint32_t paramTypes, TEE_Param params[4], uint32_t* returnOrigin) {
+
+ IntTAInvokeCommandData data;
+ if (returnOrigin) {
+ *returnOrigin = TEE_ORIGIN_API;
+ }
+ if (session == NULL){
+ return TEE_ERROR_TARGET_DEAD;
+ }
+ memset(&data, 0, sizeof(IntTAInvokeCommandData));
+ data.session = *(uint32_t*)session;
+ data.cancelTimeOut = cancellationRequestTimeout;
+ data.commandID = commandID;
+ data.operation.paramTypes = paramTypes;
+ if(params != NULL)
+ {
+ __TEE_Preprocess_Operation;
+ }
+
+ pthread_mutex_lock(&socketLock);
+ sendCommand(socketSimulatorDaemonFD, INVOKE_TA_COMMAND, &data,
+ sizeof(IntTAInvokeCommandData));
+ pthread_mutex_unlock(&socketLock);
+#if 0
+ printf("Inside: %s \n", __FUNCTION__);
+ data.params[0].value.a = 1;
+ data.params[0].value.b = 1;
+ data.params[1].value.a = 2;
+ data.params[1].value.b = 2;
+ data.params[2].value.a = 3;
+ data.params[2].value.b = 3;
+ data.params[3].value.a = 4;
+ data.params[3].value.b = 4;
+
+ data.returnOrigin = TEE_ORIGIN_TRUSTED_APP;
+ data.returnValue = TEE_SUCCESS;
+#endif
+ // Return from the function call
+ // [inout] TEE_Param params[4],
+ // [out] uint32_t* returnOrigin);
+ if(params != NULL)
+ {
+ __TEE_Postprocess_Operation;
+ }
+ if(returnOrigin != NULL)
+ *returnOrigin = TEE_ORIGIN_TRUSTED_APP;
+ return data.returnValue;
+}