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 #include "iotivity_config.h"
33 #include "oic_malloc.h"
34 #include "payload_logging.h"
37 #include "ocpayload.h"
38 #include "ocpayloadcbor.h"
39 #include "cainterface.h"
40 #include "ocserverrequest.h"
41 #include "resourcemanager.h"
42 #include "doxmresource.h"
43 #include "pstatresource.h"
44 #include "aclresource.h"
45 #include "amaclresource.h"
46 #include "pconfresource.h"
47 #include "dpairingresource.h"
48 #include "psinterface.h"
49 #include "srmresourcestrings.h"
50 #include "securevirtualresourcetypes.h"
51 #include "credresource.h"
52 #include "srmutility.h"
53 #include "pinoxmcommon.h"
55 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
56 #include "pkix_interface.h"
59 #define TAG "OIC_SRM_DOXM"
60 #define CHAR_ZERO ('0')
62 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
63 * The value of payload size is increased until reaching belox max cbor size. */
64 static const uint16_t CBOR_SIZE = 512;
66 /** Max cbor size payload. */
67 static const uint16_t CBOR_MAX_SIZE = 4400;
69 static OicSecDoxm_t *gDoxm = NULL;
70 static OCResourceHandle gDoxmHandle = NULL;
72 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
73 static OicSecDoxm_t gDefaultDoxm =
75 NULL, /* OicUrn_t *oxmType */
76 0, /* size_t oxmTypeLen */
77 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
78 1, /* size_t oxmLen */
79 OIC_JUST_WORKS, /* uint16_t oxmSel */
80 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
81 false, /* bool owned */
82 {.id = {0}}, /* OicUuid_t deviceID */
84 {.id = {0}}, /* OicUuid_t owner */
85 #ifdef _ENABLE_MULTIPLE_OWNER_
86 NULL, /* OicSecSubOwner_t sub-owner list */
87 NULL, /* OicSecMomType_t multiple owner mode */
88 #endif //_ENABLE_MULTIPLE_OWNER_
89 {.id = {0}}, /* OicUuid_t rownerID */
93 * This method is internal method.
94 * the param roParsed is optionally used to know whether cborPayload has
95 * at least read only property value or not.
97 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
98 OicSecDoxm_t **doxm, bool *roParsed);
100 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
105 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
107 OICFree(doxm->oxmType[i]);
109 OICFree(doxm->oxmType);
114 #ifdef _ENABLE_MULTIPLE_OWNER_
118 //clean sub-owner list
119 if(NULL != doxm->subOwners)
121 OicSecSubOwner_t* subowner = NULL;
122 OicSecSubOwner_t* temp = NULL;
123 LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
125 LL_DELETE(doxm->subOwners, subowner);
129 #endif //_ENABLE_MULTIPLE_OWNER_
136 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
139 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
141 return OC_STACK_INVALID_PARAM;
143 size_t cborLen = *size;
151 OCStackResult ret = OC_STACK_ERROR;
155 char* strUuid = NULL;
157 int64_t cborEncoderResult = CborNoError;
159 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
160 VERIFY_NON_NULL(TAG, outPayload, ERROR);
161 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
163 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
164 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
166 //OxmType -- Not Mandatory
167 if (doxm->oxmTypeLen > 0)
170 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
171 strlen(OIC_JSON_OXM_TYPE_NAME));
172 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
173 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
174 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
176 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
178 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
179 strlen(doxm->oxmType[i]));
180 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
182 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
183 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
186 //Oxm -- Not Mandatory
187 if (doxm->oxmLen > 0 && false == rwOnly)
190 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
191 strlen(OIC_JSON_OXMS_NAME));
192 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
193 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
194 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
196 for (size_t i = 0; i < doxm->oxmLen; i++)
198 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
199 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
201 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
202 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
205 //OxmSel -- Mandatory
206 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
207 strlen(OIC_JSON_OXM_SEL_NAME));
208 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
209 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
210 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
215 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
216 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
217 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
218 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
219 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
223 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
224 strlen(OIC_JSON_OWNED_NAME));
225 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
226 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
227 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
231 //DeviceId -- Mandatory
232 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
233 strlen(OIC_JSON_DEVICE_ID_NAME));
234 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
235 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
236 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
237 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
238 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
243 #ifdef _ENABLE_MULTIPLE_OWNER_
244 //Device SubOwnerID -- Not Mandatory
247 size_t subOwnerLen = 0;
248 OicSecSubOwner_t* subOwner = NULL;
249 LL_FOREACH(doxm->subOwners, subOwner)
254 CborEncoder subOwners;
255 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
256 strlen(OIC_JSON_SUBOWNERID_NAME));
257 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
258 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
259 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
262 LL_FOREACH(doxm->subOwners, subOwner)
264 char* strUuid = NULL;
265 ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
266 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
267 cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
269 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
271 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
272 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
275 //Multiple Owner Mode -- Not Mandatory
278 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
279 strlen(OIC_JSON_MOM_NAME));
280 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
281 cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
282 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
284 #endif //_ENABLE_MULTIPLE_OWNER_
286 //devownerid -- Mandatory
287 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
288 strlen(OIC_JSON_DEVOWNERID_NAME));
289 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
290 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
291 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
292 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
293 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
297 //ROwner -- Mandatory
298 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
299 strlen(OIC_JSON_ROWNERID_NAME));
300 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
301 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
302 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
303 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
304 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
308 //x.org.iotivity.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
309 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
310 strlen(OIC_JSON_DPC_NAME));
311 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
312 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
313 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
317 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
318 strlen(OIC_JSON_RT_NAME));
319 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
320 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
321 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
322 for (size_t i = 0; i < 1; i++)
324 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
325 strlen(OIC_RSRC_TYPE_SEC_DOXM));
326 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
328 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
329 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
333 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
334 strlen(OIC_JSON_IF_NAME));
335 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
336 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
337 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
338 for (size_t i = 0; i < 1; i++)
340 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
341 strlen(OC_RSRVD_INTERFACE_DEFAULT));
342 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
344 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
345 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
347 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
348 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
350 if (CborNoError == cborEncoderResult)
352 *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
353 *payload = outPayload;
357 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
359 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
360 // reallocate and try again!
362 // Since the allocated initial memory failed, double the memory.
363 cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
364 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
365 cborEncoderResult = CborNoError;
366 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
370 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
376 ret = OC_STACK_ERROR;
382 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
383 OicSecDoxm_t **secDoxm)
385 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
388 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
389 OicSecDoxm_t **secDoxm, bool *roParsed)
391 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
393 return OC_STACK_INVALID_PARAM;
396 OCStackResult ret = OC_STACK_ERROR;
400 CborError cborFindResult = CborNoError;
401 char* strUuid = NULL;
405 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
407 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
408 VERIFY_NON_NULL(TAG, doxm, ERROR);
410 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
411 //OxmType -- not Mandatory
412 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
416 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
417 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
418 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
420 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
421 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
423 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
424 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
428 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
430 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
432 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
433 cborFindResult = cbor_value_advance(&oxmType);
434 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
438 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
439 //Oxm -- not Mandatory
440 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
443 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
444 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
445 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
447 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
448 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
450 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
451 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
454 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
458 cborFindResult = cbor_value_get_int(&oxm, &tmp);
459 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
460 doxm->oxm[i++] = (OicSecOxm_t)tmp;
461 cborFindResult = cbor_value_advance(&oxm);
462 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
472 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
473 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
474 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
475 doxm->oxmLen = gDoxm->oxmLen;
476 for (size_t i = 0; i < gDoxm->oxmLen; i++)
478 doxm->oxm[i] = gDoxm->oxm[i];
482 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
483 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
487 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
488 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
489 doxm->oxmSel = (OicSecOxm_t)oxmSel;
491 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
493 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
494 doxm->oxmSel = gDoxm->oxmSel;
497 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
498 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
502 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
503 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
504 doxm->sct = (OicSecCredType_t)sct;
511 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
513 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
514 doxm->sct = gDoxm->sct;
517 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
518 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
520 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
521 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
523 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
525 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
526 doxm->owned = gDoxm->owned;
529 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
530 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
532 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
533 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
535 else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc
537 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
538 doxm->dpc = gDoxm->dpc;
541 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
542 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
544 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
545 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
546 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
547 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
553 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
554 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
557 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
558 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
560 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
561 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
562 ret = ConvertStrToUuid(strUuid , &doxm->owner);
563 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
569 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
570 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
573 #ifdef _ENABLE_MULTIPLE_OWNER_
574 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
575 if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
578 cborFindResult = cbor_value_get_int(&doxmMap, &mode);
579 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
580 if(NULL == doxm->mom)
582 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
583 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
585 doxm->mom->mode = (OicSecMomType_t)mode;
587 else if(NULL != gDoxm && NULL != gDoxm->mom)
589 // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
590 if(NULL == doxm->mom)
592 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
593 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
595 doxm->mom->mode = gDoxm->mom->mode;
598 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
599 if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
601 size_t subOwnerLen = 0;
602 CborValue subOwnerCbor;
603 cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
604 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
605 VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
607 cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
608 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
610 while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
612 OCStackResult convertRes = OC_STACK_ERROR;
613 OicSecSubOwner_t* subOwner = NULL;
614 char* strUuid = NULL;
617 cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
618 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
620 subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
621 VERIFY_NON_NULL(TAG, subOwner, ERROR);
623 convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
624 VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
625 subOwner->status = MOT_STATUS_DONE;
626 LL_APPEND(doxm->subOwners, subOwner);
628 cborFindResult = cbor_value_advance(&subOwnerCbor);
629 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
632 else if(NULL != gDoxm && NULL != gDoxm->subOwners)
634 // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
635 OicSecSubOwner_t* subOwnerItor = NULL;
636 LL_FOREACH(gDoxm->subOwners, subOwnerItor)
638 OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
639 VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
641 memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
642 subOwnerId->status = MOT_STATUS_DONE;
644 LL_APPEND(doxm->subOwners, subOwnerId);
647 #endif //_ENABLE_MULTIPLE_OWNER_
649 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
650 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
652 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
653 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
654 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
655 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
661 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
662 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
669 if (CborNoError != cborFindResult)
671 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
672 DeleteDoxmBinData(doxm);
675 ret = OC_STACK_ERROR;
681 * @todo document this function including why code might need to call this.
682 * The current suspicion is that it's not being called as much as it should.
684 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
690 // Convert Doxm data into CBOR for update to persistent storage
691 uint8_t *payload = NULL;
693 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
694 if (payload && (OC_STACK_OK == res)
695 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
703 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
712 static bool ValidateQuery(const char * query)
714 // Send doxm resource data if the state of doxm resource
715 // matches with the query parameters.
716 // else send doxm resource data as NULL
717 // TODO Remove this check and rely on Policy Engine
718 // and Provisioning Mode to enforce provisioning-state
719 // access rules. Eventually, the PE and PM code will
720 // not send a request to the /doxm Entity Handler at all
721 // if it should not respond.
722 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
728 bool bOwnedQry = false; // does querystring contains 'owned' query ?
729 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
730 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
731 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
732 bool bInterfaceQry = false; // does querystring contains 'if' query ?
733 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
734 #ifdef _ENABLE_MULTIPLE_OWNER_
735 bool bMotQry = false; // does querystring contains 'mom' and 'owned' query ?
736 bool bMotMatch = false; // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
737 #endif //_ENABLE_MULTIPLE_OWNER_
739 OicParseQueryIter_t parseIter = {.attrPos = NULL};
741 ParseQueryIterInit((unsigned char*)query, &parseIter);
743 while (GetNextQuery(&parseIter))
745 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
748 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
753 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
760 #ifdef _ENABLE_MULTIPLE_OWNER_
761 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
764 OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
765 if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
767 if(GetNextQuery(&parseIter))
769 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
771 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
781 #endif //_ENABLE_MULTIPLE_OWNER_
783 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
786 OicUuid_t subject = {.id={0}};
788 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
789 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
791 bDeviceIDMatch = true;
795 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
797 bInterfaceQry = true;
798 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
800 bInterfaceMatch = true;
802 return (bInterfaceQry ? bInterfaceMatch: true);
806 #ifdef _ENABLE_MULTIPLE_OWNER_
807 return ((bOwnedQry ? bOwnedMatch : true) &&
808 (bDeviceIDQry ? bDeviceIDMatch : true) &&
809 (bMotQry ? bMotMatch : true));
811 return ((bOwnedQry ? bOwnedMatch : true) &&
812 (bDeviceIDQry ? bDeviceIDMatch : true));
813 #endif //_ENABLE_MULTIPLE_OWNER_
816 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
818 OCEntityHandlerResult ehRet = OC_EH_OK;
820 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
822 //Checking if Get request is a query.
823 if (ehRequest->query)
825 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
826 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
827 if (!ValidateQuery(ehRequest->query))
834 * For GET or Valid Query request return doxm resource CBOR payload.
835 * For non-valid query return NULL json payload.
836 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
837 * return valid doxm resource json.
839 uint8_t *payload = NULL;
842 if (ehRet == OC_EH_OK)
844 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
846 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
850 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
851 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
853 // Send response payload to request originator
854 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
855 OC_EH_OK : OC_EH_ERROR;
862 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
867 dst->oxmSel = src->oxmSel;
870 memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
873 memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
876 memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
878 //Update owned status
879 if(dst->owned != src->owned)
881 dst->owned = src->owned;
887 OicSecOxm_t* tempOxm = (OicSecOxm_t*)OICMalloc(sizeof(OicSecOxm_t) * src->oxmLen);
890 for(size_t i = 0; i < src->oxmLen; i++)
892 tempOxm[i] = src->oxm[i];
897 dst->oxmLen = src->oxmLen;
901 #ifdef _ENABLE_MULTIPLE_OWNER_
904 OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
907 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
910 dst->mom->mode = src->mom->mode;
914 #endif //_ENABLE_MULTIPLE_OWNER_
918 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
919 #ifdef _ENABLE_MULTIPLE_OWNER_
921 * Callback function to handle MOT DTLS handshake result.
922 * @param[out] object remote device information.
923 * @param[out] errorInfo CA Error information.
925 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *object,
926 const CAErrorInfo_t *errorInfo)
928 OIC_LOG(DEBUG, TAG, "IN MultipleOwnerDTLSHandshakeCB");
930 if(CA_STATUS_OK == errorInfo->result)
932 const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(object);
933 if(authenticatedSubOwnerInfo)
935 OicSecSubOwner_t* subOwnerInst = NULL;
936 LL_FOREACH(gDoxm->subOwners, subOwnerInst)
938 if(0 == memcmp(subOwnerInst->uuid.id,
939 authenticatedSubOwnerInfo->identity.id,
940 authenticatedSubOwnerInfo->identity.id_length))
946 if(NULL == subOwnerInst)
948 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
951 OIC_LOG(DEBUG, TAG, "Adding New SubOwner");
952 memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
953 authenticatedSubOwnerInfo->identity.id_length);
954 LL_APPEND(gDoxm->subOwners, subOwnerInst);
955 if(!UpdatePersistentStorage(gDoxm))
957 OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
964 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
966 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
969 OIC_LOG(DEBUG, TAG, "OUT MultipleOwnerDTLSHandshakeCB");
971 #endif //_ENABLE_MULTIPLE_OWNER_
972 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
974 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
976 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
977 OCEntityHandlerResult ehRet = OC_EH_ERROR;
978 OicUuid_t emptyOwner = {.id = {0} };
979 static uint16_t previousMsgId = 0;
982 * Convert CBOR Doxm data into binary. This will also validate
983 * the Doxm data received.
985 OicSecDoxm_t *newDoxm = NULL;
987 if (ehRequest->payload)
989 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
990 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
991 bool roParsed = false;
992 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
993 if (newDoxm && OC_STACK_OK == res)
995 // Check request on RO property
996 if (true == roParsed)
998 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
999 ehRet = OC_EH_NOT_ACCEPTABLE;
1004 if (true == gDoxm->owned)
1006 //Update gDoxm based on newDoxm
1007 updateWriteableProperty(newDoxm, gDoxm);
1009 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1010 #ifdef _ENABLE_MULTIPLE_OWNER_
1014 if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1016 CAResult_t caRes = CA_STATUS_FAILED;
1017 if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1019 caRes = CAEnableAnonECDHCipherSuite(false);
1020 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1021 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1023 caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, ehRequest->devAddr.adapter);
1024 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1025 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1027 //Set the device id to derive temporal PSK
1028 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1032 OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1035 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1039 //if MOM is disabled, revert the DTLS handshake callback
1040 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1042 OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1047 if(newDoxm->subOwners)
1049 OicSecSubOwner_t* subowner = NULL;
1050 OicSecSubOwner_t* temp = NULL;
1052 OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1054 if(gDoxm->subOwners)
1056 LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1058 LL_DELETE(gDoxm->subOwners, subowner);
1065 LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1067 LL_DELETE(newDoxm->subOwners, subowner);
1068 LL_APPEND(gDoxm->subOwners, subowner);
1071 #endif //_ENABLE_MULTIPLE_OWNER_
1072 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1074 //Update new state in persistent storage
1075 if (UpdatePersistentStorage(gDoxm) == true)
1081 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1082 ehRet = OC_EH_ERROR;
1088 if ((false == gDoxm->owned) && (false == newDoxm->owned))
1090 if (OIC_JUST_WORKS == newDoxm->oxmSel)
1093 * If current state of the device is un-owned, enable
1094 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1095 * tool can initiate JUST_WORKS ownership transfer process.
1097 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1099 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
1100 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1101 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1102 #endif // __WITH_DTLS__ or __WITH_TLS__
1107 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1108 //Save the owner's UUID to derive owner credential
1109 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1111 // Update new state in persistent storage
1112 if (true == UpdatePersistentStorage(gDoxm))
1118 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1119 ehRet = OC_EH_ERROR;
1123 * Disable anonymous ECDH cipher in tinyDTLS since device is now
1126 CAResult_t caRes = CA_STATUS_OK;
1127 caRes = CAEnableAnonECDHCipherSuite(false);
1128 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1129 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1131 #endif // __WITH_DTLS__ or __WITH_TLS__
1134 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1137 * If current state of the device is un-owned, enable
1138 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1139 * tool can initiate JUST_WORKS ownership transfer process.
1141 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1143 gDoxm->oxmSel = newDoxm->oxmSel;
1144 //Update new state in persistent storage
1145 if ((UpdatePersistentStorage(gDoxm) == true))
1151 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1152 ehRet = OC_EH_ERROR;
1155 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1156 CAResult_t caRes = CA_STATUS_OK;
1158 caRes = CAEnableAnonECDHCipherSuite(false);
1159 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1160 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1162 caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
1163 ehRequest->devAddr.adapter);
1164 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1166 char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1167 //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
1168 if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
1170 if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1172 //Set the device id to derive temporal PSK
1173 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1176 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1177 * Credential should not be saved into SVR.
1178 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1180 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1181 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1186 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1187 ehRet = OC_EH_ERROR;
1190 else if(previousMsgId != ehRequest->messageID)
1192 if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1194 //Set the device id to derive temporal PSK
1195 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1198 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1199 * Credential should not be saved into SVR.
1200 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1202 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1203 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1208 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1209 ehRet = OC_EH_ERROR;
1213 #endif // __WITH_DTLS__ or __WITH_TLS__
1215 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1218 //Save the owner's UUID to derive owner credential
1219 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1221 //Update new state in persistent storage
1222 if (UpdatePersistentStorage(gDoxm) == true)
1228 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1229 ehRet = OC_EH_ERROR;
1232 #endif // __WITH_DTLS__ or __WITH_TLS__
1234 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1235 else if (OIC_MANUFACTURER_CERTIFICATE == newDoxm->oxmSel)
1237 //Save the owner's UUID to derive owner credential
1238 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1239 gDoxm->oxmSel = newDoxm->oxmSel;
1240 //Update new state in persistent storage
1241 if (UpdatePersistentStorage(gDoxm))
1247 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1248 ehRet = OC_EH_ERROR;
1250 CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1251 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1252 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1254 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1255 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1257 #endif // __WITH_DTLS__ or __WITH_TLS__
1261 * When current state of the device is un-owned and Provisioning
1262 * Tool is attempting to change the state to 'Owned' with a
1263 * qualified value for the field 'Owner'
1265 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1266 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1268 //Change the SVR's resource owner as owner device.
1269 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1270 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1272 ehRet = OC_EH_ERROR;
1275 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1276 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1278 ehRet = OC_EH_ERROR;
1281 ownerRes = SetCredRownerId(&gDoxm->owner);
1282 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1284 ehRet = OC_EH_ERROR;
1287 ownerRes = SetPstatRownerId(&gDoxm->owner);
1288 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1290 ehRet = OC_EH_ERROR;
1293 ownerRes = SetDpairingRownerId(&gDoxm->owner);
1294 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1296 ehRet = OC_EH_ERROR;
1299 ownerRes = SetPconfRownerId(&gDoxm->owner);
1300 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1302 ehRet = OC_EH_ERROR;
1306 gDoxm->owned = true;
1307 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1309 // Update new state in persistent storage
1310 if (UpdatePersistentStorage(gDoxm))
1312 //Update default ACE of security resource to prevent anonymous user access.
1313 if(OC_STACK_OK == UpdateDefaultSecProvACE())
1319 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1320 ehRet = OC_EH_ERROR;
1325 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1326 ehRet = OC_EH_ERROR;
1328 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1329 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel)
1331 CAregisterPkixInfoHandler(GetPkixInfo);
1332 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1334 #endif // __WITH_DTLS__ or __WITH_TLS__
1340 if(OC_EH_OK != ehRet)
1344 * If some error is occured while ownership transfer,
1345 * ownership transfer related resource should be revert back to initial status.
1349 if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
1351 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
1352 "DOXM will be reverted.");
1353 RestoreDoxmToInitState();
1354 RestorePstatToInitState();
1359 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1364 previousMsgId = ehRequest->messageID;
1367 //Send payload to request originator
1368 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1369 OC_EH_OK : OC_EH_ERROR;
1371 DeleteDoxmBinData(newDoxm);
1376 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1377 OCEntityHandlerRequest * ehRequest,
1378 void* callbackParam)
1380 (void)callbackParam;
1381 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1383 if(NULL == ehRequest)
1388 if (flag & OC_REQUEST_FLAG)
1390 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1392 switch (ehRequest->method)
1395 ehRet = HandleDoxmGetRequest(ehRequest);
1399 ehRet = HandleDoxmPostRequest(ehRequest);
1403 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1404 OC_EH_OK : OC_EH_ERROR;
1412 OCStackResult CreateDoxmResource()
1414 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1415 OIC_RSRC_TYPE_SEC_DOXM,
1416 OC_RSRVD_INTERFACE_DEFAULT,
1423 if (OC_STACK_OK != ret)
1425 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1426 DeInitDoxmResource();
1432 * Checks if DeviceID is generated during provisioning for the new device.
1433 * If DeviceID is NULL then generates the new DeviceID.
1434 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1436 static OCStackResult CheckDeviceID()
1438 OCStackResult ret = OC_STACK_ERROR;
1439 bool validId = false;
1440 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1442 if (gDoxm->deviceID.id[i] != 0)
1451 if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1453 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1458 if (!UpdatePersistentStorage(gDoxm))
1460 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1461 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1472 * Get the default value.
1474 * @return the default value of doxm, @ref OicSecDoxm_t.
1476 static OicSecDoxm_t* GetDoxmDefault()
1478 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1479 return &gDefaultDoxm;
1482 const OicSecDoxm_t* GetDoxmResourceData()
1487 #if defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1489 * Internal API to prepare MOT
1491 static void PrepareMOT(const OicSecDoxm_t* doxm)
1493 OIC_LOG(INFO, TAG, "IN PrepareMOT");
1494 VERIFY_NON_NULL(TAG, doxm, ERROR);
1496 if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1498 CAResult_t caRes = CA_STATUS_FAILED;
1500 OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1502 if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1504 caRes = CAEnableAnonECDHCipherSuite(false);
1505 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1506 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1508 caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP);
1509 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1511 caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_TCP);
1512 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1514 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1516 //Set the device id to derive temporal PSK
1517 SetUuidForPinBasedOxm(&doxm->deviceID);
1521 OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1525 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1528 OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1531 OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1533 #endif //defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1535 OCStackResult InitDoxmResource()
1537 OCStackResult ret = OC_STACK_ERROR;
1539 //Read DOXM resource from PS
1540 uint8_t *data = NULL;
1542 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1543 // If database read failed
1544 if (OC_STACK_OK != ret)
1546 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1550 // Read DOXM resource from PS
1551 ret = CBORPayloadToDoxm(data, size, &gDoxm);
1554 * If SVR database in persistent storage got corrupted or
1555 * is not available for some reason, a default doxm is created
1556 * which allows user to initiate doxm provisioning again.
1558 if ((OC_STACK_OK != ret) || !data || !gDoxm)
1560 gDoxm = GetDoxmDefault();
1563 //In case of the server is shut down unintentionally, we should initialize the owner
1564 if(false == gDoxm->owned)
1566 OicUuid_t emptyUuid = {.id={0}};
1567 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1570 ret = CheckDeviceID();
1571 if (ret == OC_STACK_OK)
1573 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1574 //Instantiate 'oic.sec.doxm'
1575 ret = CreateDoxmResource();
1579 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1583 #if defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1584 //if MOT is enabled, MOT should be prepared.
1585 if(gDoxm && gDoxm->owned)
1589 #endif // defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1594 OCStackResult DeInitDoxmResource()
1596 OCStackResult ret = OCDeleteResource(gDoxmHandle);
1597 if (gDoxm != &gDefaultDoxm)
1599 DeleteDoxmBinData(gDoxm);
1603 if (OC_STACK_OK == ret)
1609 return OC_STACK_ERROR;
1613 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1615 if (deviceID && gDoxm)
1617 *deviceID = gDoxm->deviceID;
1620 return OC_STACK_ERROR;
1623 OCStackResult GetDoxmIsOwned(bool *isOwned)
1625 if (isOwned && gDoxm)
1627 *isOwned = gDoxm->owned;
1630 return OC_STACK_ERROR;
1633 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1637 if(NULL == deviceID)
1639 return OC_STACK_INVALID_PARAM;
1643 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1644 return OC_STACK_NO_RESOURCE;
1647 //Check the device's OTM state
1649 #ifdef __WITH_DTLS__
1650 //for normal device.
1651 if(true == gDoxm->owned &&
1652 memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
1654 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1655 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1656 return OC_STACK_ERROR;
1658 #endif //__WITH_DTLS
1660 //Save the previous UUID
1662 memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1665 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1668 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1669 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1673 if(!UpdatePersistentStorage(gDoxm))
1675 //revert UUID in case of update error
1676 memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1679 memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1680 memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1683 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1684 return OC_STACK_ERROR;
1689 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1691 OCStackResult retVal = OC_STACK_ERROR;
1694 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
1698 *devownerid = gDoxm->owner;
1699 retVal = OC_STACK_OK;
1705 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1707 OCStackResult retVal = OC_STACK_ERROR;
1712 *rowneruuid = gDoxm->rownerID;
1713 retVal = OC_STACK_OK;
1719 #ifdef _ENABLE_MULTIPLE_OWNER_
1721 * Compare the UUID to SubOwner.
1723 * @param[in] uuid device UUID
1725 * @return true if context->subjectId exist subowner list, else false.
1727 bool IsSubOwner(const OicUuid_t* uuid)
1729 bool retVal = false;
1736 if (gDoxm && gDoxm->subOwners)
1738 OicSecSubOwner_t* subOwner = NULL;
1739 LL_FOREACH(gDoxm->subOwners, subOwner)
1741 if(memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
1749 #endif //_ENABLE_MULTIPLE_OWNER_
1752 * Function to restore doxm resurce to initial status.
1753 * This function will use in case of error while ownership transfer
1755 void RestoreDoxmToInitState()
1759 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1761 OicUuid_t emptyUuid = {.id={0}};
1762 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1763 gDoxm->owned = false;
1764 gDoxm->oxmSel = OIC_JUST_WORKS;
1766 if(!UpdatePersistentStorage(gDoxm))
1768 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");