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 uint16_t CBOR_SIZE = 512;
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 = 7;
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 */
78 {.id = {0}}, /* OicUuid_t rownerID */
81 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
86 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
88 OICFree(doxm->oxmType[i]);
90 OICFree(doxm->oxmType);
100 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
102 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
104 return OC_STACK_INVALID_PARAM;
106 size_t cborLen = *size;
114 OCStackResult ret = OC_STACK_ERROR;
116 CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
117 CborEncoder doxmMap = { {.ptr = NULL }, .end = 0 };
118 char* strUuid = NULL;
120 int64_t cborEncoderResult = CborNoError;
121 uint8_t mapSize = DOXM_MAP_SIZE;
122 if (doxm->oxmTypeLen > 0)
126 if (doxm->oxmLen > 0)
131 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
132 VERIFY_NON_NULL(TAG, outPayload, ERROR);
133 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
135 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
136 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
138 //OxmType -- Not Mandatory
139 if (doxm->oxmTypeLen > 0)
141 CborEncoder oxmType = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
142 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
143 strlen(OIC_JSON_OXM_TYPE_NAME));
144 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
145 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
146 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
148 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
150 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
151 strlen(doxm->oxmType[i]));
152 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
154 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
155 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
158 //Oxm -- Not Mandatory
159 if (doxm->oxmLen > 0)
161 CborEncoder oxm = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
162 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
163 strlen(OIC_JSON_OXMS_NAME));
164 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
165 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
166 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
168 for (size_t i = 0; i < doxm->oxmLen; i++)
170 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
171 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
173 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
174 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
177 //OxmSel -- Mandatory
178 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
179 strlen(OIC_JSON_OXM_SEL_NAME));
180 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
181 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
182 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
185 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
186 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
187 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
188 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
189 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
192 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
193 strlen(OIC_JSON_OWNED_NAME));
194 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
195 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
196 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
198 //DeviceId -- Mandatory
199 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
200 strlen(OIC_JSON_DEVICE_ID_NAME));
201 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
202 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
203 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
204 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
205 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
209 //devownerid -- Mandatory
210 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
211 strlen(OIC_JSON_DEVOWNERID_NAME));
212 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
213 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
214 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
215 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
216 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
220 //ROwner -- Mandatory
221 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
222 strlen(OIC_JSON_ROWNERID_NAME));
223 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
224 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
225 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
226 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
227 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
232 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
233 strlen(OIC_JSON_DPC_NAME));
234 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
235 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
236 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
238 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
239 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
241 if (CborNoError == cborEncoderResult)
243 *size = encoder.ptr - outPayload;
244 *payload = outPayload;
248 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
250 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
251 // reallocate and try again!
253 // Since the allocated initial memory failed, double the memory.
254 cborLen += encoder.ptr - encoder.end;
255 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
256 cborEncoderResult = CborNoError;
257 ret = DoxmToCBORPayload(doxm, payload, &cborLen);
261 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
267 ret = OC_STACK_ERROR;
273 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
274 OicSecDoxm_t **secDoxm)
276 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm)
278 return OC_STACK_INVALID_PARAM;
281 OCStackResult ret = OC_STACK_ERROR;
285 CborError cborFindResult = CborNoError;
286 int cborLen = (size == 0) ? CBOR_SIZE : size;
287 char* strUuid = NULL;
290 cbor_parser_init(cborPayload, cborLen, 0, &parser, &doxmCbor);
292 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
293 VERIFY_NON_NULL(TAG, doxm, ERROR);
295 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
296 //OxmType -- not Mandatory
297 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
301 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
302 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
303 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
305 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
306 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
308 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
309 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
313 while (cbor_value_is_valid(&oxmType))
315 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
317 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
318 cborFindResult = cbor_value_advance(&oxmType);
319 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
323 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
324 //Oxm -- not Mandatory
325 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
328 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
329 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
330 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
332 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
333 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
335 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
336 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
339 while (cbor_value_is_valid(&oxm))
341 cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
342 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
343 cborFindResult = cbor_value_advance(&oxm);
344 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
348 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
349 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
351 cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
352 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
354 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
356 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
357 doxm->oxmSel = gDoxm->oxmSel;
360 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
361 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
363 cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
364 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
366 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
368 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
369 doxm->sct = gDoxm->sct;
372 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
373 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
375 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
376 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
378 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
380 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
381 doxm->owned = gDoxm->owned;
384 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
385 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
387 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
388 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
390 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
392 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
396 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
397 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
399 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
400 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
401 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
402 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
407 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
408 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
410 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
411 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
412 ret = ConvertStrToUuid(strUuid , &doxm->owner);
413 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
418 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
419 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
421 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
422 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
423 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
424 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
434 if (CborNoError != cborFindResult)
436 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
437 DeleteDoxmBinData(doxm);
440 ret = OC_STACK_ERROR;
446 * @todo document this function including why code might need to call this.
447 * The current suspicion is that it's not being called as much as it should.
449 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
455 // Convert Doxm data into CBOR for update to persistent storage
456 uint8_t *payload = NULL;
458 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size);
459 if (payload && (OC_STACK_OK == res)
460 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
468 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
477 static bool ValidateQuery(const char * query)
479 // Send doxm resource data if the state of doxm resource
480 // matches with the query parameters.
481 // else send doxm resource data as NULL
482 // TODO Remove this check and rely on Policy Engine
483 // and Provisioning Mode to enforce provisioning-state
484 // access rules. Eventually, the PE and PM code will
485 // not send a request to the /doxm Entity Handler at all
486 // if it should not respond.
487 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
493 bool bOwnedQry = false; // does querystring contains 'owned' query ?
494 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
495 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
496 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
498 OicParseQueryIter_t parseIter = {.attrPos = NULL};
500 ParseQueryIterInit((unsigned char*)query, &parseIter);
502 while (GetNextQuery(&parseIter))
504 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
507 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
512 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
519 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
522 OicUuid_t subject = {.id={0}};
524 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
525 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
527 bDeviceIDMatch = true;
532 return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
535 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
537 OCEntityHandlerResult ehRet = OC_EH_OK;
539 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
541 //Checking if Get request is a query.
542 if (ehRequest->query)
544 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
545 if (!ValidateQuery(ehRequest->query))
552 * For GET or Valid Query request return doxm resource CBOR payload.
553 * For non-valid query return NULL json payload.
554 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
555 * return valid doxm resource json.
557 uint8_t *payload = NULL;
560 if (ehRet == OC_EH_OK)
562 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
568 // Send response payload to request originator
569 if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, payload, size))
571 OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmGetRequest");
579 static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
581 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing PUT request");
582 OCEntityHandlerResult ehRet = OC_EH_ERROR;
583 OicUuid_t emptyOwner = {.id = {0} };
586 * Convert CBOR Doxm data into binary. This will also validate
587 * the Doxm data received.
589 OicSecDoxm_t *newDoxm = NULL;
591 if (ehRequest->payload)
593 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData1;
594 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
595 OCStackResult res = CBORPayloadToDoxm(payload, size, &newDoxm);
597 if (newDoxm && OC_STACK_OK == res)
599 if (OIC_JUST_WORKS == newDoxm->oxmSel)
601 if ((false == gDoxm->owned) && (false == newDoxm->owned))
604 * If current state of the device is un-owned, enable
605 * anonymous ECDH cipher in tinyDTLS so that Provisioning
606 * tool can initiate JUST_WORKS ownership transfer process.
608 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
610 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
612 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
613 #endif //__WITH_DTLS__
619 //Save the owner's UUID to derive owner credential
620 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
622 // OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
623 // Generating OwnerPSK
624 // OIC_LOG (INFO, TAG, "Doxm EntityHandle generating OwnerPSK");
625 // Generate new credential for provisioning tool
626 // ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
627 // (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
628 // VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
630 // Update new state in persistent storage
631 if (true == UpdatePersistentStorage(gDoxm))
637 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
642 * Disable anonymous ECDH cipher in tinyDTLS since device is now
645 CAResult_t caRes = CA_STATUS_OK;
646 caRes = CAEnableAnonECDHCipherSuite(false);
647 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
648 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
651 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
652 CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
653 #endif //__WITH_X509__
654 #endif //__WITH_DTLS__
658 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
660 if ((false == gDoxm->owned) && (false == newDoxm->owned))
663 * If current state of the device is un-owned, enable
664 * anonymous ECDH cipher in tinyDTLS so that Provisioning
665 * tool can initiate JUST_WORKS ownership transfer process.
667 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
669 gDoxm->oxmSel = newDoxm->oxmSel;
670 //Update new state in persistent storage
671 if ((UpdatePersistentStorage(gDoxm) == true))
677 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
682 CAResult_t caRes = CA_STATUS_OK;
684 caRes = CAEnableAnonECDHCipherSuite(false);
685 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
686 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
688 caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
689 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
691 char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
692 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
694 //Set the device id to derive temporal PSK
695 SetUuidForRandomPinOxm(&gDoxm->deviceID);
698 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
699 * Credential should not be saved into SVR.
700 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
702 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
703 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
708 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
711 #endif //__WITH_DTLS__
716 //Save the owner's UUID to derive owner credential
717 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
719 //Update new state in persistent storage
720 if (UpdatePersistentStorage(gDoxm) == true)
726 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
735 * When current state of the device is un-owned and Provisioning
736 * Tool is attempting to change the state to 'Owned' with a
737 * qualified value for the field 'Owner'
739 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
740 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
743 // Update new state in persistent storage
744 if (UpdatePersistentStorage(gDoxm))
746 //Update default ACL of security resource to prevent anonymous user access.
747 if(OC_STACK_OK == UpdateDefaultSecProvACL())
753 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
759 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
767 if(OC_EH_OK != ehRet)
769 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
770 "DOXM will be reverted.");
773 * If some error is occured while ownership transfer,
774 * ownership transfer related resource should be revert back to initial status.
776 RestoreDoxmToInitState();
777 RestorePstatToInitState();
780 //Send payload to request originator
781 if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
783 OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmPostRequest");
785 DeleteDoxmBinData(newDoxm);
790 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
791 OCEntityHandlerRequest * ehRequest,
795 OCEntityHandlerResult ehRet = OC_EH_ERROR;
797 if(NULL == ehRequest)
802 if (flag & OC_REQUEST_FLAG)
804 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
806 switch (ehRequest->method)
809 ehRet = HandleDoxmGetRequest(ehRequest);
813 ehRet = HandleDoxmPutRequest(ehRequest);
818 SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
826 OCStackResult CreateDoxmResource()
828 OCStackResult ret = OCCreateResource(&gDoxmHandle,
829 OIC_RSRC_TYPE_SEC_DOXM,
834 OC_OBSERVABLE | OC_SECURE |
835 OC_EXPLICIT_DISCOVERABLE);
837 if (OC_STACK_OK != ret)
839 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
840 DeInitDoxmResource();
846 * Checks if DeviceID is generated during provisioning for the new device.
847 * If DeviceID is NULL then generates the new DeviceID.
848 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
850 static OCStackResult CheckDeviceID()
852 OCStackResult ret = OC_STACK_ERROR;
853 bool validId = false;
854 for (uint8_t i = 0; i < UUID_LENGTH; i++)
856 if (gDoxm->deviceID.id[i] != 0)
865 if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
867 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
872 if (!UpdatePersistentStorage(gDoxm))
874 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
875 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
886 * Get the default value.
888 * @return the default value of doxm, @ref OicSecDoxm_t.
890 static OicSecDoxm_t* GetDoxmDefault()
892 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
893 return &gDefaultDoxm;
896 const OicSecDoxm_t* GetDoxmResourceData()
901 OCStackResult InitDoxmResource()
903 OCStackResult ret = OC_STACK_ERROR;
905 //Read DOXM resource from PS
906 uint8_t *data = NULL;
908 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
909 // If database read failed
910 if (OC_STACK_OK != ret)
912 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
916 // Read DOXM resource from PS
917 ret = CBORPayloadToDoxm(data, size, &gDoxm);
920 * If SVR database in persistent storage got corrupted or
921 * is not available for some reason, a default doxm is created
922 * which allows user to initiate doxm provisioning again.
924 if ((OC_STACK_OK != ret) || !data || !gDoxm)
926 gDoxm = GetDoxmDefault();
929 //In case of the server is shut down unintentionally, we should initialize the owner
930 if(false == gDoxm->owned)
932 OicUuid_t emptyUuid = {.id={0}};
933 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
936 ret = CheckDeviceID();
937 if (ret == OC_STACK_OK)
939 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
940 //Instantiate 'oic.sec.doxm'
941 ret = CreateDoxmResource();
945 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
951 OCStackResult DeInitDoxmResource()
953 OCStackResult ret = OCDeleteResource(gDoxmHandle);
954 if (gDoxm != &gDefaultDoxm)
956 DeleteDoxmBinData(gDoxm);
960 if (OC_STACK_OK == ret)
966 return OC_STACK_ERROR;
970 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
972 if (deviceID && gDoxm)
974 *deviceID = gDoxm->deviceID;
977 return OC_STACK_ERROR;
980 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
982 OCStackResult retVal = OC_STACK_ERROR;
985 OIC_LOG_V(DEBUG, TAG, "gDoxm owned = %d.", gDoxm->owned);
988 *devOwner = gDoxm->owner; // TODO change to devOwner when available
989 retVal = OC_STACK_OK;
996 * Function to restore doxm resurce to initial status.
997 * This function will use in case of error while ownership transfer
999 void RestoreDoxmToInitState()
1003 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1005 OicUuid_t emptyUuid = {.id={0}};
1006 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1007 gDoxm->owned = false;
1008 gDoxm->oxmSel = OIC_JUST_WORKS;
1010 if(!UpdatePersistentStorage(gDoxm))
1012 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");