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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "oic_malloc.h"
25 #include "resourcemanager.h"
26 #include "doxmresource.h"
27 #include "psinterface.h"
29 #include "srmresourcestrings.h"
30 #include "securevirtualresourcetypes.h"
33 #include "cainterface.h"
34 #include "credresource.h"
35 #include "ocserverrequest.h"
36 #include "srmutility.h"
44 #define TAG PCF("SRM-DOXM")
46 static OicSecDoxm_t *gDoxm = NULL;
47 static OCResourceHandle gDoxmHandle = NULL;
49 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
50 static OicSecDoxm_t gDefaultDoxm =
52 NULL, /* OicUrn_t *oxmType */
53 0, /* size_t oxmTypeLen */
54 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
55 1, /* size_t oxmLen */
56 OIC_JUST_WORKS, /* uint16_t oxmSel */
57 false, /* bool owned */
58 {}, /* OicUuid_t deviceID */
59 {}, /* OicUuid_t owner */
62 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
67 for(int i = 0; i < doxm->oxmTypeLen; i++)
69 OICFree(doxm->oxmType[i]);
71 OICFree(doxm->oxmType);
81 char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
89 cJSON *jsonDoxm = NULL;
90 char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
92 B64Result b64Ret = B64_OK;
94 cJSON *jsonRoot = cJSON_CreateObject();
95 VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
97 jsonDoxm = cJSON_CreateObject();
98 VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
99 cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
101 //OxmType -- Not Mandatory
102 if(doxm->oxmTypeLen > 0)
104 cJSON *jsonOxmTyArray = cJSON_CreateArray();
105 VERIFY_NON_NULL(TAG, jsonOxmTyArray, ERROR);
106 cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_TYPE_NAME, jsonOxmTyArray );
107 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
109 cJSON_AddItemToArray (jsonOxmTyArray, cJSON_CreateString(doxm->oxmType[i]));
113 //Oxm -- Not Mandatory
116 cJSON *jsonOxmArray = cJSON_CreateArray();
117 VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
118 cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
119 for (size_t i = 0; i < doxm->oxmLen; i++)
121 cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
125 //OxmSel -- Mandatory
126 cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);
129 cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);
131 //TODO: Need more clarification on deviceIDFormat field type.
133 //DeviceIdFormat -- Mandatory
134 cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_DEVICE_ID_FORMAT_NAME, doxm->deviceIDFormat);
137 //DeviceId -- Mandatory
139 b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
140 sizeof(base64Buff), &outLen);
141 VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
142 cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);
146 b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
147 sizeof(base64Buff), &outLen);
148 VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
149 cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);
151 jsonStr = cJSON_PrintUnformatted(jsonRoot);
156 cJSON_Delete(jsonRoot);
161 OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
169 OCStackResult ret = OC_STACK_ERROR;
170 OicSecDoxm_t *doxm = NULL;
171 cJSON *jsonDoxm = NULL;
172 cJSON *jsonObj = NULL;
174 size_t jsonObjLen = 0;
175 unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
177 B64Result b64Ret = B64_OK;
179 cJSON *jsonRoot = cJSON_Parse(jsonStr);
180 VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
182 jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
183 VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
185 doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
186 VERIFY_NON_NULL(TAG, doxm, ERROR);
188 //OxmType -- not Mandatory
189 jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
190 if ((jsonObj) && (cJSON_Array == jsonObj->type))
192 doxm->oxmTypeLen = cJSON_GetArraySize(jsonObj);
193 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
195 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
196 VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
198 for(int i = 0; i < doxm->oxmTypeLen ; i++)
200 cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
201 VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
203 jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
204 doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
205 VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
206 strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
210 //Oxm -- not Mandatory
211 jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME);
212 if (jsonObj && cJSON_Array == jsonObj->type)
214 doxm->oxmLen = cJSON_GetArraySize(jsonObj);
215 VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
217 doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
218 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
220 for(int i = 0; i < doxm->oxmLen ; i++)
222 cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
223 VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
224 doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
228 //OxmSel -- Mandatory
229 jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
232 VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR)
233 doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
235 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
237 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
238 doxm->oxmSel = gDoxm->oxmSel;
242 jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
245 VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR)
246 doxm->owned = jsonObj->valueint;
248 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
250 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
251 doxm->owned = gDoxm->owned;
254 //DeviceId -- Mandatory
255 jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
258 VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
259 if(cJSON_String == jsonObj->type)
261 //Check for empty string, in case DeviceId field has not been set yet
262 if (jsonObj->valuestring[0])
265 b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
266 sizeof(base64Buff), &outLen);
267 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)),
269 memcpy(doxm->deviceID.id, base64Buff, outLen);
273 else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id
275 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
276 VERIFY_SUCCESS(TAG, strcmp((char *)gDoxm->deviceID.id, "") != 0, ERROR);
277 strncpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
280 // Owner -- will be empty when device state is unowned.
281 if (true == doxm->owned)
283 jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME);
284 VERIFY_NON_NULL(TAG, jsonObj, ERROR);
285 VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR)
287 b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
288 sizeof(base64Buff), &outLen);
289 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->owner.id)), ERROR);
290 memcpy(doxm->owner.id, base64Buff, outLen);
296 cJSON_Delete(jsonRoot);
297 if (OC_STACK_OK != ret)
299 DeleteDoxmBinData(doxm);
307 * @todo document this function including why code might need to call this.
308 * The current suspicion is that it's not being called as much as it should.
310 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
316 // Convert Doxm data into JSON for update to persistent storage
317 char *jsonStr = BinToDoxmJSON(doxm);
320 cJSON *jsonDoxm = cJSON_Parse(jsonStr);
324 (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_DOXM_NAME, jsonDoxm)))
328 cJSON_Delete(jsonDoxm);
335 static bool ValidateQuery(unsigned char * query)
337 // Send doxm resource data if the state of doxm resource
338 // matches with the query parameters.
339 // else send doxm resource data as NULL
340 // TODO Remove this check and rely on Policy Engine
341 // and Provisioning Mode to enforce provisioning-state
342 // access rules. Eventually, the PE and PM code will
343 // not send a request to the /doxm Entity Handler at all
344 // if it should not respond.
345 OC_LOG (INFO, TAG, PCF("In ValidateQuery"));
351 OicParseQueryIter_t parseIter = {};
353 ParseQueryIterInit(query, &parseIter);
355 while(GetNextQuery(&parseIter))
357 if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
359 if((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
364 else if((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
374 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
376 char* jsonStr = NULL;
377 OCEntityHandlerResult ehRet = OC_EH_OK;
379 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle processing GET request"));
381 //Checking if Get request is a query.
384 OC_LOG (INFO, TAG, PCF("HandleDoxmGetRequest processing query"));
385 if(!ValidateQuery((unsigned char *)ehRequest->query))
392 * For GET or Valid Query request return doxm resource json payload.
393 * For non-valid query return NULL json payload.
394 * A device will 'always' have a default Doxm, so BinToDoxmJSON will
395 * return valid doxm resource json.
398 jsonStr = (ehRet == OC_EH_OK) ? BinToDoxmJSON(gDoxm) : NULL;
400 // Send response payload to request originator
401 if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, jsonStr))
403 OC_LOG (ERROR, TAG, PCF("SendSRMResponse failed in HandleDoxmGetRequest"));
412 static OCEntityHandlerResult HandleDoxmPutRequest (const OCEntityHandlerRequest * ehRequest)
414 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle processing PUT request"));
415 OCEntityHandlerResult ehRet = OC_EH_ERROR;
416 OicUuid_t emptyOwner = {};
419 * Convert JSON Doxm data into binary. This will also validate
420 * the Doxm data received.
422 OicSecDoxm_t* newDoxm = JSONToDoxmBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
426 // Iotivity SRM ONLY supports OIC_JUST_WORKS now
427 if (OIC_JUST_WORKS == newDoxm->oxmSel)
430 * If current state of the device is un-owned, enable
431 * anonymous ECDH cipher in tinyDTLS so that Provisioning
432 * tool can initiate JUST_WORKS ownership transfer process.
434 if ((false == gDoxm->owned) && (false == newDoxm->owned))
436 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle enabling AnonECDHCipherSuite"));
438 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
439 #endif //__WITH_DTLS__
444 * When current state of the device is un-owned and Provisioning
445 * Tool is attempting to change the state to 'Owned' with a
446 * qualified value for the field 'Owner'
448 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
449 (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0))
452 * Generate OwnerPSK and create credential for Provisioning
453 * tool with the generated OwnerPSK.
454 * Update persistent storage and disable anonymous ECDH cipher
460 OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
461 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {};
463 //Generating OwnerPSK
464 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle generating OwnerPSK"));
465 pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
466 (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS),
467 newDoxm->owner.id, sizeof(newDoxm->owner.id),
468 gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
469 ownerPSK, OWNER_PSK_LENGTH_128);
471 VERIFY_SUCCESS(TAG, pskRet == CA_STATUS_OK, ERROR);
473 //Generating new credential for provisioning tool
477 char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(ownerPSK)) + 1] = {};
478 B64Result b64Ret = b64Encode(ownerPSK, sizeof(ownerPSK), base64Buff,
479 sizeof(base64Buff), &outLen);
480 VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
482 OC_LOG (INFO, TAG, PCF("Doxm EntityHandle generating Credential"));
483 OicSecCred_t *cred = GenerateCredential(&newDoxm->owner, SYMMETRIC_PAIR_WISE_KEY,
484 NULL, base64Buff, ownLen, &newDoxm->owner);
485 VERIFY_NON_NULL(TAG, cred, ERROR);
487 //Adding provisioning tool credential to cred Resource.
488 VERIFY_SUCCESS(TAG, OC_STACK_OK == AddCredential(cred), ERROR);
491 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
493 // Update new state in persistent storage
494 if (true == UpdatePersistentStorage(gDoxm))
503 * If persistent storage update failed, revert back the state
504 * for global variable.
506 gDoxm->owned = false;
507 memset(&(gDoxm->owner), 0, sizeof(OicUuid_t));
511 * Disable anonymous ECDH cipher in tinyDTLS since device is now
514 CAEnableAnonECDHCipherSuite(false);
515 #endif //__WITH_DTLS__
522 //Send payload to request originator
523 if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
525 OC_LOG (ERROR, TAG, PCF("SendSRMResponse failed in HandlePstatPostRequest"));
527 DeleteDoxmBinData(newDoxm);
533 * This internal method is the entity handler for DOXM resources.
535 OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
536 OCEntityHandlerRequest * ehRequest,
539 OCEntityHandlerResult ehRet = OC_EH_ERROR;
541 if(NULL == ehRequest)
547 if (flag & OC_REQUEST_FLAG)
549 OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
550 switch (ehRequest->method)
553 ehRet = HandleDoxmGetRequest(ehRequest);
557 ehRet = HandleDoxmPutRequest(ehRequest);
562 SendSRMResponse(ehRequest, ehRet, NULL);
571 * This internal method is used to create '/oic/sec/doxm' resource.
573 OCStackResult CreateDoxmResource()
577 ret = OCCreateResource(&gDoxmHandle,
578 OIC_RSRC_TYPE_SEC_DOXM,
585 if (OC_STACK_OK != ret)
587 OC_LOG (FATAL, TAG, PCF("Unable to instantiate Doxm resource"));
588 DeInitDoxmResource();
594 * Checks if DeviceID is generated during provisioning for the new device.
595 * If DeviceID is NULL then generates the new DeviceID.
596 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
601 if(strcmp((char *)gDoxm->deviceID.id, "") == 0 )
603 OCFillRandomMem(gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id));
604 UpdatePersistentStorage(gDoxm);
609 * Get the default value.
610 * @retval the gDefaultDoxm pointer;
612 static OicSecDoxm_t* GetDoxmDefault()
614 OC_LOG (INFO, TAG, PCF("GetDoxmToDefault"));
615 return &gDefaultDoxm;
619 * This method is used by SRM to retrieve DOXM resource data.
621 * @retval reference to @ref OicSecDoxm_t, binary format of Doxm resource data
623 const OicSecDoxm_t* GetDoxmResourceData()
629 * Initialize DOXM resource by loading data from persistent storage.
631 * @retval OC_STACK_OK for Success, otherwise some error value
633 OCStackResult InitDoxmResource()
635 OCStackResult ret = OC_STACK_ERROR;
637 //Read DOXM resource from PS
638 char* jsonSVRDatabase = GetSVRDatabase();
641 //Convert JSON DOXM into binary format
642 gDoxm = JSONToDoxmBin(jsonSVRDatabase);
645 * If SVR database in persistent storage got corrupted or
646 * is not available for some reason, a default doxm is created
647 * which allows user to initiate doxm provisioning again.
649 if(!jsonSVRDatabase || !gDoxm)
651 gDoxm = GetDoxmDefault();
654 //Instantiate 'oic.sec.doxm'
655 ret = CreateDoxmResource();
656 OICFree(jsonSVRDatabase);
661 * Perform cleanup for DOXM resources.
664 * OC_STACK_OK - no error
665 * OC_STACK_ERROR - stack process error
668 OCStackResult DeInitDoxmResource()
670 OCStackResult ret = OCDeleteResource(gDoxmHandle);
671 if(gDoxm != &gDefaultDoxm)
673 DeleteDoxmBinData(gDoxm);
677 if(OC_STACK_OK == ret)
683 return OC_STACK_ERROR;
689 * This method returns the SRM device ID for this device.
691 * @retval OC_STACK_OK for Success, otherwise some error value
693 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
695 if(deviceID && gDoxm)
697 *deviceID = gDoxm->deviceID;
700 return OC_STACK_ERROR;
704 * @brief Gets the OicUuid_t value for the owner of this device.
706 * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
708 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
710 OCStackResult retVal = OC_STACK_ERROR;
714 *devOwner = gDoxm->owner; // TODO change to devOwner when available
715 retVal = OC_STACK_OK;