1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #define _POSIX_C_SOURCE 200112L
23 #include "srmutility.h"
24 #include "srmresourcestrings.h"
26 #include "oic_malloc.h"
27 #include "oic_string.h"
29 #include "psinterface.h"
30 #include "doxmresource.h"
31 #include "credresource.h"
32 #include "pstatresource.h"
34 #include "casecurityinterface.h"
35 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
36 #include "pkix_interface.h"
39 #define TAG "OIC_SRM_UTILITY"
41 void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter)
43 OIC_LOG(INFO, TAG, "Initializing coap iterator");
44 if ((NULL == query) || (NULL == parseIter))
49 parseIter->attrPos = NULL;
50 parseIter->attrLen = 0;
51 parseIter->valPos = NULL;
52 parseIter->valLen = 0;
53 coap_parse_iterator_init((unsigned char *)query, strlen((char *)query),
54 (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR,
55 (unsigned char *) "", 0, &parseIter->pi);
58 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
60 OIC_LOG(INFO, TAG, "Getting Next Query");
61 if (NULL == parseIter)
66 unsigned char * qrySeg = NULL;
69 // Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR.
70 qrySeg = coap_parse_next(&parseIter->pi);
74 delimPos = strchr((char *)qrySeg, OIC_SEC_REST_QUERY_DELIMETER);
77 parseIter->attrPos = parseIter->pi.pos;
78 parseIter->attrLen = (unsigned char *)delimPos - parseIter->pi.pos;
79 parseIter->valPos = (unsigned char *)delimPos + 1;
80 parseIter->valLen = &qrySeg[parseIter->pi.segment_length] - parseIter->valPos;
87 // TODO This functionality is replicated in all SVR's and therefore we need
88 // to encapsulate it in a common method. However, this may not be the right
89 // file for this method.
90 OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
91 size_t *numUuids, OicUuid_t** uuids)
94 cJSON* jsonObj = cJSON_GetObjectItem((cJSON *)jsonRoot, arrayItem);
95 VERIFY_NON_NULL(TAG, jsonObj, ERROR);
96 VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
98 *numUuids = (size_t)cJSON_GetArraySize(jsonObj);
99 VERIFY_SUCCESS(TAG, *numUuids > 0, ERROR);
100 *uuids = (OicUuid_t*)OICCalloc(*numUuids, sizeof(OicUuid_t));
101 VERIFY_NON_NULL(TAG, *uuids, ERROR);
105 unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {0};
107 B64Result b64Ret = B64_OK;
109 cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
110 VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
111 VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
114 b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
115 sizeof(base64Buff), &outLen);
117 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof((*uuids)[idxx].id)),
119 memcpy((*uuids)[idxx].id, base64Buff, outLen);
120 } while ( ++idxx < *numUuids);
125 return OC_STACK_ERROR;
130 * Function to getting string of ownership transfer method
132 * @prarm oxmType ownership transfer method
134 * @return string value of ownership transfer method
136 const char* GetOxmString(OicSecOxm_t oxmType)
141 return OXM_JUST_WORKS;
142 case OIC_RANDOM_DEVICE_PIN:
143 return OXM_RANDOM_DEVICE_PIN;
144 case OIC_MANUFACTURER_CERTIFICATE:
145 return OXM_MANUFACTURER_CERTIFICATE;
146 case OIC_RAW_PUB_KEY:
147 return OXM_RAW_PUBLIC_KEY;
148 #ifdef MULTIPLE_OWNER
149 case OIC_PRECONFIG_PIN:
150 return OXM_PRECONF_PIN;
151 #endif //MULTIPLE_OWNER
152 case OIC_MV_JUST_WORKS:
153 return OXM_MV_JUST_WORKS;
154 case OIC_CON_MFG_CERT:
155 return OXM_CON_MFG_CERT;
161 OCStackResult ConvertUuidToStr(const OicUuid_t* uuid, char** strUuid)
163 if(NULL == uuid || NULL == strUuid || NULL != *strUuid)
165 OIC_LOG(ERROR, TAG, "ConvertUuidToStr : Invalid param");
166 return OC_STACK_INVALID_PARAM;
171 const size_t urnBufSize = (UUID_LENGTH * 2) + 4 + 1;
172 char* convertedUrn = (char*)OICCalloc(urnBufSize, sizeof(char));
173 VERIFY_NON_NULL(TAG, convertedUrn, ERROR);
175 for(uuidIdx=0, urnIdx=0; uuidIdx < UUID_LENGTH && urnIdx < urnBufSize; uuidIdx++, urnIdx+=2)
177 // canonical format for UUID has '8-4-4-4-12'
178 if(uuidIdx==4 || uuidIdx==6 || uuidIdx==8 || uuidIdx==10)
180 snprintf(convertedUrn + urnIdx, 2, "%c", '-');
183 snprintf(convertedUrn + urnIdx, 3, "%02x", (uint8_t)(uuid->id[uuidIdx]));
185 convertedUrn[urnBufSize - 1] = '\0';
187 *strUuid = convertedUrn;
191 return OC_STACK_NO_MEMORY;
194 OCStackResult ConvertStrToUuid(const char* strUuid, OicUuid_t* uuid)
196 if(NULL == strUuid || NULL == uuid)
198 OIC_LOG(ERROR, TAG, "ConvertStrToUuid : Invalid param");
199 return OC_STACK_INVALID_PARAM;
204 size_t strUuidLen = 0;
205 char convertedUuid[UUID_LENGTH * 2] = {0};
207 strUuidLen = strlen(strUuid);
210 OIC_LOG(INFO, TAG, "The empty string detected, The UUID will be converted to "\
211 "\"00000000-0000-0000-0000-000000000000\"");
213 else if(UUID_LENGTH * 2 + 4 == strUuidLen)
215 for(uuidIdx=0, urnIdx=0; uuidIdx < UUID_LENGTH ; uuidIdx++, urnIdx+=2)
217 if(*(strUuid + urnIdx) == '-')
221 sscanf(strUuid + urnIdx, "%2hhx", &convertedUuid[uuidIdx]);
226 OIC_LOG(ERROR, TAG, "Invalid string uuid format, Please set the uuid as correct format");
227 OIC_LOG(ERROR, TAG, "e.g) \"72616E64-5069-6E44-6576-557569643030\" (4-2-2-2-6)");
228 OIC_LOG(ERROR, TAG, "e.g) \"\"");
230 return OC_STACK_INVALID_PARAM;
233 memcpy(uuid->id, convertedUuid, UUID_LENGTH);
238 const OicUuid_t THE_NIL_UUID = {.id={0000000000000000}};
241 * Compares two OicUuid_t structs.
243 * @return true if the two OicUuid_t structs are equal, else false.
245 bool UuidCmp(const OicUuid_t *firstId, const OicUuid_t *secondId)
248 VERIFY_NON_NULL(TAG, firstId, ERROR);
249 VERIFY_NON_NULL(TAG, secondId, ERROR);
251 if (0 == memcmp(firstId, secondId, sizeof(OicUuid_t)))
257 OIC_LOG_V(DEBUG, TAG, "%s: returning %s.", __func__, ret?"true":"false");
262 * Compares OicUuid_t to Nil UUID {.id={0000000000000000}}
264 * @return true if the OicUuid_t is the Nil UUID.
266 bool IsNilUuid(const OicUuid_t *uuid)
269 char *strUuid = NULL;
270 ConvertUuidToStr(uuid, &strUuid);
273 OIC_LOG_V(DEBUG, TAG, "%s: uuid: %s.", __func__, strUuid);
277 return UuidCmp(uuid, &THE_NIL_UUID);
280 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
281 OCStackResult SetDeviceIdSeed(const uint8_t* seed, size_t seedSize)
283 return SetDoxmDeviceIDSeed(seed, seedSize);
286 static OicSecOtmEventHandler_t gOtmEventHandler = NULL;
287 static char ptAddr[256] = {0};
288 static uint16_t ptPort = 0;
290 void SetOtmEventHandler(OicSecOtmEventHandler_t otmEventHandler)
292 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
294 memset(ptAddr, 0x00, sizeof(ptAddr));
296 gOtmEventHandler = otmEventHandler;
297 OIC_LOG_V(DEBUG, TAG, "Out%s", __func__);
301 * Function to handle the handshake result in OTM.
302 * This function will be invoked after DTLS handshake
303 * @param endPoint [IN] The remote endpoint.
304 * @param errorInfo [IN] Error information from the endpoint.
307 static void DTLSHandshakeServerCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
309 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
310 if(NULL != endpoint && NULL != info)
312 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
313 endpoint->addr, endpoint->port, info->result);
315 //We can't know about PT's secure port, so compare only adress to identify the PT.
316 if (strncmp(endpoint->addr, ptAddr, strlen(ptAddr)) == 0)
318 OIC_LOG_V(INFO, TAG, "Normal port is [%s:%d]", ptAddr, ptPort);
320 //If DTLS handshake error occurred, revert secure resource and notify error event to application.
321 if (CA_STATUS_OK != info->result)
323 OIC_LOG(ERROR, TAG, "Failed to establish a secure session with owner device.");
324 ResetSecureResourceInPS();
325 OIC_LOG(INFO, TAG, "Secure Resources reverted.");
326 InvokeOtmEventHandler(endpoint->addr, endpoint->port, NULL, OIC_OTM_ERROR);
331 OIC_LOG_V(WARNING, TAG, "[%s:%d] is not a owner device", endpoint->addr, endpoint->port);
336 OIC_LOG(WARNING, TAG, "Invalid param.");
338 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
342 void InvokeOtmEventHandler(const char* addr, uint16_t port,
343 const OicUuid_t* uuid, OicSecOtmEvent_t event)
345 char* strUuid = NULL;
346 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
348 //addr can be NULL for init state
349 //port can be '0' for BLE and init state
350 //uuid can be NULL for init state & coap
355 case OIC_OTM_STARTED:
358 OICStrcpy(ptAddr, sizeof(ptAddr), addr);
363 memset(ptAddr, 0x00, sizeof(ptAddr));
366 //Register TLS event handler to catch the tls event while handshake
367 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DTLSHandshakeServerCB))
369 OIC_LOG(WARNING, TAG, "Failed to register (D)TLS handshake callback.");
374 memset(ptAddr, 0x00, sizeof(ptAddr));
376 //Register TLS event handler to catch the tls event while handshake
377 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
379 OIC_LOG(WARNING, TAG, "Failed to register (D)TLS handshake callback.");
381 //Restore Pkix handler to initial state
382 CAregisterPkixInfoHandler(GetPkixInfo);
383 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
384 CAregisterPskCredentialsHandler(GetDtlsPskCredentials);
387 OIC_LOG_V(ERROR, TAG, "Unknow OTM event : %d", event);
393 if(OC_STACK_OK != ConvertUuidToStr(uuid, &strUuid))
395 OIC_LOG(ERROR, TAG, "Failed to convert UUID to String.");
400 OIC_LOG(DEBUG, TAG, "=================================");
401 OIC_LOG(DEBUG, TAG, "[OTM Event]");
402 OIC_LOG_V(DEBUG, TAG, "PT UUID : %s", (strUuid ? strUuid : "NULL"));
403 OIC_LOG_V(DEBUG, TAG, "PT Addr=%s:%d", (addr ? addr : "NULL"), port);
404 OIC_LOG_V(DEBUG, TAG, "Event Code=%d", event);
405 OIC_LOG(DEBUG, TAG, "=================================");
407 if (NULL == gOtmEventHandler)
409 OIC_LOG(WARNING, TAG, "OTM event handler is not registered.");
413 OIC_LOG(DEBUG, TAG, "Invoking callback to notify OTM state..");
414 gOtmEventHandler(addr, port, strUuid, (int)event);
421 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);