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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
32 #include "oic_malloc.h"
33 #include "payload_logging.h"
36 #include "ocpayload.h"
37 #include "cainterface.h"
38 #include "ocserverrequest.h"
39 #include "resourcemanager.h"
40 #include "doxmresource.h"
41 #include "pstatresource.h"
42 #include "aclresource.h"
43 #include "psinterface.h"
44 #include "srmresourcestrings.h"
45 #include "securevirtualresourcetypes.h"
46 #include "credresource.h"
47 #include "srmutility.h"
48 #include "pinoxmcommon.h"
50 #define TAG "SRM-DOXM"
52 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
53 * The value of payload size is increased until reaching belox max cbor size. */
54 static const uint8_t CBOR_SIZE = 255;
56 /** Max cbor size payload. */
57 static const uint16_t CBOR_MAX_SIZE = 4400;
59 /** DOXM Map size - Number of mandatory items. */
60 static const uint8_t DOXM_MAP_SIZE = 5;
62 static OicSecDoxm_t *gDoxm = NULL;
63 static OCResourceHandle gDoxmHandle = NULL;
65 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
66 static OicSecDoxm_t gDefaultDoxm =
68 NULL, /* OicUrn_t *oxmType */
69 0, /* size_t oxmTypeLen */
70 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
71 1, /* size_t oxmLen */
72 OIC_JUST_WORKS, /* uint16_t oxmSel */
73 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
74 false, /* bool owned */
75 {.id = {0}}, /* OicUuid_t deviceID */
77 {.id = {0}}, /* OicUuid_t owner */
80 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
85 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
87 OICFree(doxm->oxmType[i]);
89 OICFree(doxm->oxmType);
99 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
101 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
103 return OC_STACK_INVALID_PARAM;
106 size_t cborLen = *size;
115 OCStackResult ret = OC_STACK_ERROR;
117 CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
118 CborEncoder doxmMap = { {.ptr = NULL }, .end = 0 };
120 CborError cborEncoderResult = CborNoError;
122 uint8_t mapSize = DOXM_MAP_SIZE;
124 if (doxm->oxmTypeLen > 0)
128 if (doxm->oxmLen > 0)
133 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
134 VERIFY_NON_NULL(TAG, outPayload, ERROR);
135 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
137 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
138 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
140 //OxmType -- Not Mandatory
141 if (doxm->oxmTypeLen > 0)
143 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
144 strlen(OIC_JSON_OXM_TYPE_NAME));
145 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
146 CborEncoder oxmType = { {.ptr = NULL }, .end = 0 };
147 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
148 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
150 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
152 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
153 strlen(doxm->oxmType[i]));
154 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
156 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
157 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
160 //Oxm -- Not Mandatory
161 if (doxm->oxmLen > 0)
163 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_NAME,
164 strlen(OIC_JSON_OXM_NAME));
165 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
166 CborEncoder oxm = { {.ptr = NULL }, .end = 0 };
167 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
168 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
170 for (size_t i = 0; i < doxm->oxmLen; i++)
172 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
173 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
175 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
176 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
179 //OxmSel -- Mandatory
180 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
181 strlen(OIC_JSON_OXM_SEL_NAME));
182 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
183 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
184 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
187 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
188 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
189 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
190 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
191 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
194 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
195 strlen(OIC_JSON_OWNED_NAME));
196 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
197 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
198 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
200 //TODO: Need more clarification on deviceIDFormat field type.
202 //DeviceIdFormat -- Mandatory
203 cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_DEVICE_ID_FORMAT_NAME, doxm->deviceIDFormat);
206 //DeviceId -- Mandatory
207 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
208 strlen(OIC_JSON_DEVICE_ID_NAME));
209 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
210 cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->deviceID.id,
211 sizeof(doxm->deviceID.id));
212 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
215 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
216 strlen(OIC_JSON_DPC_NAME));
217 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
218 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
219 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
222 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNER_NAME,
223 strlen(OIC_JSON_OWNER_NAME));
224 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner tag.");
225 cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->owner.id,
226 sizeof(doxm->owner.id));
227 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Value");
229 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
230 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
232 *size = encoder.ptr - outPayload;
233 *payload = outPayload;
237 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
239 // reallocate and try again!
241 // Since the allocated initial memory failed, double the memory.
242 cborLen += encoder.ptr - encoder.end;
243 cborEncoderResult = CborNoError;
244 ret = DoxmToCBORPayload(doxm, payload, &cborLen);
247 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
253 ret = OC_STACK_ERROR;
259 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
260 OicSecDoxm_t **secDoxm)
262 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm)
264 return OC_STACK_INVALID_PARAM;
267 OCStackResult ret = OC_STACK_ERROR;
270 CborValue doxmCbor = { .parser = NULL };
271 CborParser parser = { .end = NULL };
272 CborError cborFindResult = CborNoError;
278 cbor_parser_init(cborPayload, cborLen, 0, &parser, &doxmCbor);
279 CborValue doxmMap = { .parser = NULL } ;
280 OicSecDoxm_t *doxm = NULL;
281 cborFindResult = cbor_value_enter_container(&doxmCbor, &doxmMap);
282 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Doxm Map.")
284 doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
285 VERIFY_NON_NULL(TAG, doxm, ERROR);
287 while (cbor_value_is_valid(&doxmMap))
291 cborFindResult = cbor_value_dup_text_string(&doxmMap, &name, &len, NULL);
292 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Doxm Map Name.")
293 cborFindResult = cbor_value_advance(&doxmMap);
294 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Doxm Map.")
296 CborType type = cbor_value_get_type(&doxmMap);
298 //OxmType -- not Mandatory
299 if (0 == strcmp(OIC_JSON_OXM_TYPE_NAME, name))
301 CborValue oxmType = { .parser = NULL };
303 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
304 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
305 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
307 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
308 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
310 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
311 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
315 while (cbor_value_is_valid(&oxmType))
317 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
319 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
320 cborFindResult = cbor_value_advance(&oxmType);
321 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
325 //Oxm -- not Mandatory
326 if (0 == strcmp(OIC_JSON_OXM_NAME, name))
328 CborValue oxm = { .parser = NULL };
330 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
331 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
332 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
334 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
335 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
337 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
338 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
341 while (cbor_value_is_valid(&oxm))
343 cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
344 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
345 cborFindResult = cbor_value_advance(&oxm);
346 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
350 if (0 == strcmp(OIC_JSON_OXM_SEL_NAME, name))
352 cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
353 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
356 if (0 == strcmp(OIC_JSON_SUPPORTED_CRED_TYPE_NAME, name))
358 cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
359 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
362 if (0 == strcmp(OIC_JSON_OWNED_NAME, name))
364 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
365 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
368 if (0 == strcmp(OIC_JSON_DPC_NAME, name))
370 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
371 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
374 if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
377 cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id, &len, NULL);
378 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DeviceId Value.")
379 memcpy(doxm->deviceID.id, id, len);
382 if (0 == strcmp(OIC_JSON_OWNER_NAME, name))
385 cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id , &len, NULL);
386 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Name Value.")
387 memcpy(doxm->owner.id, id, len);
390 if (CborMapType != type && cbor_value_is_valid(&doxmMap))
392 cborFindResult = cbor_value_advance(&doxmMap);
393 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing DoxmMap.")
402 if (CborNoError != cborFindResult)
404 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
405 DeleteDoxmBinData(doxm);
407 ret = OC_STACK_ERROR;
413 * @todo document this function including why code might need to call this.
414 * The current suspicion is that it's not being called as much as it should.
416 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
422 // Convert Doxm data into CBOR for update to persistent storage
423 uint8_t *payload = NULL;
425 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size);
426 if (payload && (OC_STACK_OK == res)
427 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
437 static bool ValidateQuery(const char * query)
439 // Send doxm resource data if the state of doxm resource
440 // matches with the query parameters.
441 // else send doxm resource data as NULL
442 // TODO Remove this check and rely on Policy Engine
443 // and Provisioning Mode to enforce provisioning-state
444 // access rules. Eventually, the PE and PM code will
445 // not send a request to the /doxm Entity Handler at all
446 // if it should not respond.
447 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
453 bool bOwnedQry = false; // does querystring contains 'owned' query ?
454 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
455 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
456 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
458 OicParseQueryIter_t parseIter = {.attrPos = NULL};
460 ParseQueryIterInit((unsigned char*)query, &parseIter);
462 while (GetNextQuery(&parseIter))
464 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
467 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
472 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
479 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
482 OicUuid_t subject = {.id={0}};
484 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
485 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
487 bDeviceIDMatch = true;
492 return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
495 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
497 OCEntityHandlerResult ehRet = OC_EH_OK;
499 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
501 //Checking if Get request is a query.
502 if (ehRequest->query)
504 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
505 if (!ValidateQuery(ehRequest->query))
512 * For GET or Valid Query request return doxm resource CBOR payload.
513 * For non-valid query return NULL json payload.
514 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
515 * return valid doxm resource json.
517 uint8_t *payload = NULL;
519 if (ehRet == OC_EH_OK)
522 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
528 // Send response payload to request originator
529 if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, payload))
531 OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmGetRequest");
539 static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
541 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing PUT request");
542 OCEntityHandlerResult ehRet = OC_EH_ERROR;
543 OicUuid_t emptyOwner = {.id = {0} };
546 * Convert CBOR Doxm data into binary. This will also validate
547 * the Doxm data received.
549 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData1;
550 OicSecDoxm_t *newDoxm = NULL;
554 OCStackResult res = CBORPayloadToDoxm(payload, CBOR_SIZE, &newDoxm);
556 if (newDoxm && OC_STACK_OK == res)
558 // Iotivity SRM ONLY supports OIC_JUST_WORKS now
559 if (OIC_JUST_WORKS == newDoxm->oxmSel)
562 * If current state of the device is un-owned, enable
563 * anonymous ECDH cipher in tinyDTLS so that Provisioning
564 * tool can initiate JUST_WORKS ownership transfer process.
566 if ((false == gDoxm->owned) && (false == newDoxm->owned))
568 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
570 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
571 #endif //__WITH_DTLS__
577 //Save the owner's UUID to derive owner credential
578 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
580 // OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
581 // Generating OwnerPSK
582 // OIC_LOG (INFO, TAG, "Doxm EntityHandle generating OwnerPSK");
583 // Generate new credential for provisioning tool
584 // ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
585 // (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
586 // VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
588 // Update new state in persistent storage
589 if (true == UpdatePersistentStorage(gDoxm))
595 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
600 * Disable anonymous ECDH cipher in tinyDTLS since device is now
603 CAResult_t caRes = CA_STATUS_OK;
604 caRes = CAEnableAnonECDHCipherSuite(false);
605 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
606 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
609 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
610 CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
611 #endif //__WITH_X509__
612 #endif //__WITH_DTLS__
616 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
618 if ((false == gDoxm->owned) && (false == newDoxm->owned))
621 * If current state of the device is un-owned, enable
622 * anonymous ECDH cipher in tinyDTLS so that Provisioning
623 * tool can initiate JUST_WORKS ownership transfer process.
625 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
627 gDoxm->oxmSel = newDoxm->oxmSel;
628 //Update new state in persistent storage
629 if ((UpdatePersistentStorage(gDoxm) == true))
635 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
640 CAResult_t caRes = CA_STATUS_OK;
642 caRes = CAEnableAnonECDHCipherSuite(false);
643 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
644 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
646 caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
647 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
649 char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
650 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
652 //Set the device id to derive temporal PSK
653 SetUuidForRandomPinOxm(&gDoxm->deviceID);
656 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
657 * Credential should not be saved into SVR.
658 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
660 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
661 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
666 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
669 #endif //__WITH_DTLS__
674 //Save the owner's UUID to derive owner credential
675 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
677 //Update new state in persistent storage
678 if (UpdatePersistentStorage(gDoxm) == true)
684 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
693 * When current state of the device is un-owned and Provisioning
694 * Tool is attempting to change the state to 'Owned' with a
695 * qualified value for the field 'Owner'
697 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
698 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
701 // Update new state in persistent storage
702 if (UpdatePersistentStorage(gDoxm))
704 //Update default ACL of security resource to prevent anonymous user access.
705 if(OC_STACK_OK == UpdateDefaultSecProvACL())
711 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
717 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
724 if(OC_EH_OK != ehRet)
726 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
727 "DOXM will be reverted.");
730 * If some error is occured while ownership transfer,
731 * ownership transfer related resource should be revert back to initial status.
733 RestoreDoxmToInitState();
734 RestorePstatToInitState();
737 //Send payload to request originator
738 if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL))
740 OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmPostRequest");
742 DeleteDoxmBinData(newDoxm);
747 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
748 OCEntityHandlerRequest * ehRequest,
752 OCEntityHandlerResult ehRet = OC_EH_ERROR;
754 if(NULL == ehRequest)
759 if (flag & OC_REQUEST_FLAG)
761 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
763 switch (ehRequest->method)
766 ehRet = HandleDoxmGetRequest(ehRequest);
770 ehRet = HandleDoxmPutRequest(ehRequest);
775 SendSRMCBORResponse(ehRequest, ehRet, NULL);
783 OCStackResult CreateDoxmResource()
785 OCStackResult ret = OCCreateResource(&gDoxmHandle,
786 OIC_RSRC_TYPE_SEC_DOXM,
791 OC_OBSERVABLE | OC_SECURE |
792 OC_EXPLICIT_DISCOVERABLE);
794 if (OC_STACK_OK != ret)
796 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
797 DeInitDoxmResource();
803 * Checks if DeviceID is generated during provisioning for the new device.
804 * If DeviceID is NULL then generates the new DeviceID.
805 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
807 static OCStackResult CheckDeviceID()
809 OCStackResult ret = OC_STACK_ERROR;
810 bool validId = false;
811 for (uint8_t i = 0; i < UUID_LENGTH; i++)
813 if (gDoxm->deviceID.id[i] != 0)
822 if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
824 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
829 if (UpdatePersistentStorage(gDoxm))
831 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
832 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
843 * Get the default value.
845 * @return the default value of doxm, @ref OicSecDoxm_t.
847 static OicSecDoxm_t* GetDoxmDefault()
849 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
850 return &gDefaultDoxm;
853 const OicSecDoxm_t* GetDoxmResourceData()
858 OCStackResult InitDoxmResource()
860 OCStackResult ret = OC_STACK_ERROR;
862 //Read DOXM resource from PS
863 uint8_t *data = NULL;
865 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
866 // If database read failed
867 if (OC_STACK_OK != ret)
869 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
873 // Read DOXM resource from PS
874 ret = CBORPayloadToDoxm(data, size, &gDoxm);
877 * If SVR database in persistent storage got corrupted or
878 * is not available for some reason, a default doxm is created
879 * which allows user to initiate doxm provisioning again.
881 if ((OC_STACK_OK != ret) || !data || !gDoxm)
883 gDoxm = GetDoxmDefault();
886 //In case of the server is shut down unintentionally, we should initialize the owner
887 if(false == gDoxm->owned)
889 OicUuid_t emptyUuid = {.id={0}};
890 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
893 ret = CheckDeviceID();
894 if (ret == OC_STACK_OK)
896 //Instantiate 'oic.sec.doxm'
897 ret = CreateDoxmResource();
901 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
907 OCStackResult DeInitDoxmResource()
909 OCStackResult ret = OCDeleteResource(gDoxmHandle);
910 if (gDoxm != &gDefaultDoxm)
912 DeleteDoxmBinData(gDoxm);
916 if (OC_STACK_OK == ret)
922 return OC_STACK_ERROR;
926 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
928 if (deviceID && gDoxm)
930 *deviceID = gDoxm->deviceID;
933 return OC_STACK_ERROR;
936 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
938 OCStackResult retVal = OC_STACK_ERROR;
943 *devOwner = gDoxm->owner; // TODO change to devOwner when available
944 retVal = OC_STACK_OK;
951 * Function to restore doxm resurce to initial status.
952 * This function will use in case of error while ownership transfer
954 void RestoreDoxmToInitState()
958 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
960 OicUuid_t emptyUuid = {.id={0}};
961 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
962 gDoxm->owned = false;
963 gDoxm->oxmSel = OIC_JUST_WORKS;
965 if(!UpdatePersistentStorage(gDoxm))
967 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");