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"
29 #include "oic_malloc.h"
30 #include "payload_logging.h"
33 #include "ocpayload.h"
34 #include "ocpayloadcbor.h"
35 #include "cainterface.h"
36 #include "ocserverrequest.h"
37 #include "resourcemanager.h"
38 #include "doxmresource.h"
39 #include "pstatresource.h"
40 #include "aclresource.h"
41 #include "amaclresource.h"
42 #include "pconfresource.h"
43 #include "dpairingresource.h"
44 #include "psinterface.h"
45 #include "srmresourcestrings.h"
46 #include "securevirtualresourcetypes.h"
47 #include "credresource.h"
48 #include "srmutility.h"
49 #include "pinoxmcommon.h"
50 #include "oxmverifycommon.h"
53 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
54 #include "pkix_interface.h"
55 #include "ca_adapter_net_ssl.h"
58 #define TAG "OIC_SRM_DOXM"
59 #define CHAR_ZERO ('0')
61 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
62 * The value of payload size is increased until reaching belox max cbor size. */
63 static const uint16_t CBOR_SIZE = 512;
65 /** Max cbor size payload. */
66 static const uint16_t CBOR_MAX_SIZE = 4400;
68 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
69 /** MAX uuid seed size */
70 #define MAX_UUID_SEED_SIZE (64)
71 /** MIN uuid seed size */
72 #define MIN_UUID_SEED_SIZE (8)
74 /** Buffer to save the seed of device UUID */
75 static uint8_t gUuidSeed[MAX_UUID_SEED_SIZE];
76 static size_t gUuidSeedSize = 0;
80 #define MAX_SUBOWNER_SIZE (64)
81 #define MIN_SUBOWNER_SIZE (1)
82 #define DEFAULT_SUBOWNER_SIZE (32)
84 static size_t gMaxSubOwnerSize = DEFAULT_SUBOWNER_SIZE;
87 typedef enum ConfirmState{
88 CONFIRM_STATE_READY = 0,
89 CONFIRM_STATE_WAIT = 1,
90 CONFIRM_STATE_ACCEPTED = 2,
91 CONFIRM_STATE_DENIED = 3
94 static OicSecDoxm_t *gDoxm = NULL;
95 static oc_mutex g_mutexDoxm = NULL;
96 static bool g_isDoxmNull = false;
97 static OCResourceHandle gDoxmHandle = NULL;
98 static InformOxmSelectedCallback_t g_InformOxmSelectedCallback = NULL;
100 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
101 static OicSecDoxm_t gDefaultDoxm =
103 NULL, /* OicUrn_t *oxmType */
104 0, /* size_t oxmTypeLen */
105 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
106 1, /* size_t oxmLen */
107 OIC_JUST_WORKS, /* uint16_t oxmSel */
108 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
109 false, /* bool owned */
110 {.id = {0}}, /* OicUuid_t deviceID */
111 false, /* bool dpc */
112 {.id = {0}}, /* OicUuid_t owner */
113 #ifdef MULTIPLE_OWNER
114 NULL, /* OicSecSubOwner_t sub-owner list */
115 NULL, /* OicSecMomType_t multiple owner mode */
116 #endif //MULTIPLE_OWNER
117 {.id = {0}}, /* OicUuid_t rownerID */
120 static uint16_t gConfirmMsgId = 0;
121 static ConfirmState_t gConfirmState = CONFIRM_STATE_READY;
123 static uint8_t gEmptyUuid[UUID_LENGTH] = {0};
126 * This method is internal method.
127 * the param roParsed is optionally used to know whether cborPayload has
128 * at least read only property value or not.
130 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
131 OicSecDoxm_t **doxm, bool *roParsed);
133 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
138 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
140 OICFree(doxm->oxmType[i]);
142 OICFree(doxm->oxmType);
147 #ifdef MULTIPLE_OWNER
151 //clean sub-owner list
152 if(NULL != doxm->subOwners)
154 OicSecSubOwner_t* subowner = NULL;
155 OicSecSubOwner_t* temp = NULL;
156 LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
158 LL_DELETE(doxm->subOwners, subowner);
162 #endif //MULTIPLE_OWNER
170 oc_mutex_free(g_mutexDoxm);
175 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
178 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
180 return OC_STACK_INVALID_PARAM;
182 size_t cborLen = *size;
190 OCStackResult ret = OC_STACK_ERROR;
194 char* strUuid = NULL;
196 int64_t cborEncoderResult = CborNoError;
198 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
199 VERIFY_NON_NULL(TAG, outPayload, ERROR);
200 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
202 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
203 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
205 //OxmType -- Not Mandatory
206 if (doxm->oxmTypeLen > 0)
209 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
210 strlen(OIC_JSON_OXM_TYPE_NAME));
211 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
212 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
213 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
215 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
217 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
218 strlen(doxm->oxmType[i]));
219 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
221 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
222 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
225 //Oxm -- Not Mandatory
226 if (doxm->oxmLen > 0 && false == rwOnly)
229 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
230 strlen(OIC_JSON_OXMS_NAME));
231 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
232 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
233 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
235 for (size_t i = 0; i < doxm->oxmLen; i++)
237 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
238 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
240 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
241 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
244 //OxmSel -- Mandatory
245 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
246 strlen(OIC_JSON_OXM_SEL_NAME));
247 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
248 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
249 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
254 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
255 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
256 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
257 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
258 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
262 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
263 strlen(OIC_JSON_OWNED_NAME));
264 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
265 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
266 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
270 //DeviceId -- Mandatory
271 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
272 strlen(OIC_JSON_DEVICE_ID_NAME));
273 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
274 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
275 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
276 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
277 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
282 #ifdef MULTIPLE_OWNER
283 //Device SubOwnerID -- Not Mandatory
286 size_t subOwnerLen = 0;
287 OicSecSubOwner_t* subOwner = NULL;
288 LL_FOREACH(doxm->subOwners, subOwner)
293 CborEncoder subOwners;
294 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
295 strlen(OIC_JSON_SUBOWNERID_NAME));
296 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
297 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
298 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
301 LL_FOREACH(doxm->subOwners, subOwner)
303 char* strUuid = NULL;
304 ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
305 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
306 cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
308 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
310 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
311 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
314 //Multiple Owner Mode -- Not Mandatory
317 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
318 strlen(OIC_JSON_MOM_NAME));
319 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
320 cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
321 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
323 #endif //MULTIPLE_OWNER
325 //devownerid -- Mandatory
326 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
327 strlen(OIC_JSON_DEVOWNERID_NAME));
328 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
329 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
330 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
331 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
332 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
336 //ROwner -- Mandatory
337 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
338 strlen(OIC_JSON_ROWNERID_NAME));
339 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
340 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
341 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
342 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
343 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
349 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
350 strlen(OIC_JSON_RT_NAME));
351 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
352 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
353 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
354 for (size_t i = 0; i < 1; i++)
356 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
357 strlen(OIC_RSRC_TYPE_SEC_DOXM));
358 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
360 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
361 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
365 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
366 strlen(OIC_JSON_IF_NAME));
367 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
368 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
369 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
370 for (size_t i = 0; i < 1; i++)
372 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
373 strlen(OC_RSRVD_INTERFACE_DEFAULT));
374 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
376 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
377 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
379 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
380 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
382 if (CborNoError == cborEncoderResult)
384 *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
385 *payload = outPayload;
389 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
391 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
392 // reallocate and try again!
395 // Since the allocated initial memory failed, double the memory.
396 cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
397 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
398 cborEncoderResult = CborNoError;
399 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
403 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
409 ret = OC_STACK_ERROR;
415 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
416 OicSecDoxm_t **secDoxm)
418 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
421 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
422 OicSecDoxm_t **secDoxm, bool *roParsed)
424 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
426 return OC_STACK_INVALID_PARAM;
429 OCStackResult ret = OC_STACK_ERROR;
433 CborError cborFindResult = CborNoError;
434 char* strUuid = NULL;
438 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
440 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
441 VERIFY_NON_NULL(TAG, doxm, ERROR);
443 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
444 //OxmType -- not Mandatory
445 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
449 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
450 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
451 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
453 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
454 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
456 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
457 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
461 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
463 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
465 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
466 cborFindResult = cbor_value_advance(&oxmType);
467 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
471 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
472 //Oxm -- not Mandatory
473 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
476 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
477 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
478 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
480 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
481 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
483 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
484 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
487 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
491 cborFindResult = cbor_value_get_int(&oxm, &tmp);
492 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
493 doxm->oxm[i++] = (OicSecOxm_t)tmp;
494 cborFindResult = cbor_value_advance(&oxm);
495 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
505 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
506 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
507 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
508 doxm->oxmLen = gDoxm->oxmLen;
509 for (size_t i = 0; i < gDoxm->oxmLen; i++)
511 doxm->oxm[i] = gDoxm->oxm[i];
515 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
516 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
520 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
521 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
522 doxm->oxmSel = (OicSecOxm_t)oxmSel;
524 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
526 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
527 doxm->oxmSel = gDoxm->oxmSel;
530 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
531 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
535 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
536 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
537 doxm->sct = (OicSecCredType_t)sct;
544 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
546 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
547 doxm->sct = gDoxm->sct;
550 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
551 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
553 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
554 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
556 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
558 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
559 doxm->owned = gDoxm->owned;
562 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
563 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
565 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
566 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
567 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
568 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
574 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
575 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
578 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
579 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
581 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
582 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
583 ret = ConvertStrToUuid(strUuid , &doxm->owner);
584 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
590 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
591 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
594 #ifdef MULTIPLE_OWNER
595 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
596 if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
599 cborFindResult = cbor_value_get_int(&doxmMap, &mode);
600 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
601 if(NULL == doxm->mom)
603 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
604 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
606 doxm->mom->mode = (OicSecMomType_t)mode;
608 else if(NULL != gDoxm && NULL != gDoxm->mom)
610 // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
611 if(NULL == doxm->mom)
613 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
614 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
616 doxm->mom->mode = gDoxm->mom->mode;
619 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
620 if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
622 size_t subOwnerLen = 0;
623 CborValue subOwnerCbor;
624 cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
625 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
626 VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
628 cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
629 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
631 while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
633 OCStackResult convertRes = OC_STACK_ERROR;
634 OicSecSubOwner_t* subOwner = NULL;
635 char* strUuid = NULL;
638 cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
639 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
641 subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
642 VERIFY_NON_NULL(TAG, subOwner, ERROR);
644 convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
645 VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
646 subOwner->status = MOT_STATUS_DONE;
647 LL_APPEND(doxm->subOwners, subOwner);
649 cborFindResult = cbor_value_advance(&subOwnerCbor);
650 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
653 else if(NULL != gDoxm && NULL != gDoxm->subOwners)
655 // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
656 OicSecSubOwner_t* subOwnerItor = NULL;
657 LL_FOREACH(gDoxm->subOwners, subOwnerItor)
659 OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
660 VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
662 memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
663 subOwnerId->status = MOT_STATUS_DONE;
665 LL_APPEND(doxm->subOwners, subOwnerId);
668 #endif //MULTIPLE_OWNER
670 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
671 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
673 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
674 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
675 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
676 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
682 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
683 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
690 if (CborNoError != cborFindResult)
692 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
693 DeleteDoxmBinData(doxm);
696 ret = OC_STACK_ERROR;
702 * @todo document this function including why code might need to call this.
703 * The current suspicion is that it's not being called as much as it should.
705 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
711 // Convert Doxm data into CBOR for update to persistent storage
712 uint8_t *payload = NULL;
714 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
715 if (payload && (OC_STACK_OK == res)
716 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
724 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
733 static bool ValidateQuery(const char * query)
735 // Send doxm resource data if the state of doxm resource
736 // matches with the query parameters.
737 // else send doxm resource data as NULL
738 // TODO Remove this check and rely on Policy Engine
739 // and Provisioning Mode to enforce provisioning-state
740 // access rules. Eventually, the PE and PM code will
741 // not send a request to the /doxm Entity Handler at all
742 // if it should not respond.
743 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
749 bool bOwnedQry = false; // does querystring contains 'owned' query ?
750 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
751 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
752 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
753 bool bInterfaceQry = false; // does querystring contains 'if' query ?
754 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
755 #ifdef MULTIPLE_OWNER
756 bool bMotMatch = false; // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
757 #endif //MULTIPLE_OWNER
759 OicParseQueryIter_t parseIter = {.attrPos = NULL};
761 ParseQueryIterInit((unsigned char*)query, &parseIter);
763 while (GetNextQuery(&parseIter))
765 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
768 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
773 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
780 #ifdef MULTIPLE_OWNER
781 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
783 OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
784 if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
786 if(GetNextQuery(&parseIter))
788 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
790 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
800 #endif //MULTIPLE_OWNER
802 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
805 OicUuid_t subject = {.id={0}};
807 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
808 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
810 bDeviceIDMatch = true;
814 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
816 bInterfaceQry = true;
817 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
819 bInterfaceMatch = true;
821 return (bInterfaceQry ? bInterfaceMatch: true);
825 return ((bOwnedQry ? bOwnedMatch : true) &&
826 (bDeviceIDQry ? bDeviceIDMatch : true));
829 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
831 OCEntityHandlerResult ehRet = OC_EH_OK;
833 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
835 //Checking if Get request is a query.
836 if (ehRequest->query)
838 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
839 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
840 if (!ValidateQuery(ehRequest->query))
847 * For GET or Valid Query request return doxm resource CBOR payload.
848 * For non-valid query return NULL json payload.
849 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
850 * return valid doxm resource json.
852 uint8_t *payload = NULL;
855 if (ehRet == OC_EH_OK)
857 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
859 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
863 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
864 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
866 // Send response payload to request originator
867 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
868 OC_EH_OK : OC_EH_ERROR;
875 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
880 dst->oxmSel = src->oxmSel;
883 memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
886 memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
889 memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
891 //Update owned status
892 if(dst->owned != src->owned)
894 dst->owned = src->owned;
897 #ifdef MULTIPLE_OWNER
900 OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
903 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
906 dst->mom->mode = src->mom->mode;
910 #endif //MULTIPLE_OWNER
914 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
915 #ifdef MULTIPLE_OWNER
917 * Internal function to get number of sub-owner
919 static size_t GetSubOwnerSize()
921 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
923 size_t numberOfSubOwner = 0;
925 if (gDoxm && gDoxm->subOwners)
927 OicSecSubOwner_t* subowner = NULL;
928 LL_FOREACH(gDoxm->subOwners, subowner)
934 OIC_LOG_V(DEBUG, TAG, "Numer of registered sub-owner=%zd", numberOfSubOwner);
935 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
937 return numberOfSubOwner;
941 * Callback function to handle MOT DTLS handshake result.
942 * @param[out] endpoint remote device information.
943 * @param[out] errorInfo CA Error information.
945 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *endpoint,
946 const CAErrorInfo_t *errorInfo)
948 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
949 if (!endpoint || !errorInfo)
951 OIC_LOG(ERROR, TAG, "Invalid param");
957 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
961 if ((CA_STATUS_OK == errorInfo->result) && (true == gDoxm->owned)
962 && (OIC_PRECONFIG_PIN == gDoxm->oxmSel) && (NULL != gDoxm->mom)
963 && (OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode) && (CA_ADAPTER_TCP != endpoint->adapter))
965 OIC_LOG_V(INFO, TAG, "DTLS session established for sub-owner authentication : (%s:%d)",
966 endpoint->addr, endpoint->port);
968 const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(endpoint);
969 if (authenticatedSubOwnerInfo)
971 if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
972 authenticatedSubOwnerInfo->identity.id_length))
974 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
978 OicSecSubOwner_t* subOwnerInst = NULL;
979 LL_FOREACH(gDoxm->subOwners, subOwnerInst)
981 if(0 == memcmp(subOwnerInst->uuid.id,
982 authenticatedSubOwnerInfo->identity.id,
983 authenticatedSubOwnerInfo->identity.id_length))
989 if (NULL == subOwnerInst)
991 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
994 char* strUuid = NULL;
995 if (OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
997 OIC_LOG(WARNING, TAG, "ConvertUuidToStr error");
999 OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
1001 if (gMaxSubOwnerSize > GetSubOwnerSize())
1003 memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
1004 authenticatedSubOwnerInfo->identity.id_length);
1005 LL_APPEND(gDoxm->subOwners, subOwnerInst);
1006 if (!UpdatePersistentStorage(gDoxm))
1008 OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
1013 OIC_LOG_V(ERROR, TAG, "Number of sub-owner exceeded : (MAX SIZE=%zd)", gMaxSubOwnerSize);
1015 //Close DTLS session
1016 if (CA_STATUS_OK != CAcloseSslSession(endpoint))
1018 OIC_LOG_V(ERROR, TAG, "CAcloseSslSession error for [%s:%d]", endpoint->addr, endpoint->port);
1022 if (OC_STACK_RESOURCE_DELETED != RemoveCredential(&subOwnerInst->uuid))
1024 OIC_LOG_V(ERROR, TAG, "RemoveCredential error for [%s]", strUuid);
1027 // TODO: How to send error to client side?
1036 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
1038 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
1041 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1043 #endif //MULTIPLE_OWNER
1044 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1047 * Function to validate oxmsel with oxms.
1049 * @param[in] supportedMethods Array of supported methods
1050 * @param[in] numberOfMethods number of supported methods
1051 * @param[out] selectedMethod Selected methods
1052 * @return TRUE on success
1054 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
1055 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
1057 bool isValidOxmsel = false;
1059 OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
1060 if (numberOfMethods == 0 || !supportedMethods)
1062 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
1063 return isValidOxmsel;
1066 for (size_t i = 0; i < numberOfMethods; i++)
1068 if (*selectedMethod == supportedMethods[i])
1070 isValidOxmsel = true;
1076 OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
1077 return isValidOxmsel;
1080 OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
1082 return isValidOxmsel;
1085 void SetInformOxmSelCB(InformOxmSelectedCallback_t informOxmSelCB)
1087 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1088 g_InformOxmSelectedCallback = informOxmSelCB;
1089 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1092 void UnsetInformOxmSelCB()
1094 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1095 g_InformOxmSelectedCallback = NULL;
1096 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1099 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
1101 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
1102 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1103 OicUuid_t emptyOwner = {.id = {0} };
1104 static uint16_t previousMsgId = 0;
1105 bool isDuplicatedMsg = false;
1108 * Convert CBOR Doxm data into binary. This will also validate
1109 * the Doxm data received.
1111 OicSecDoxm_t *newDoxm = NULL;
1113 if (ehRequest->payload)
1115 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1116 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1117 bool roParsed = false;
1118 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1119 if (newDoxm && OC_STACK_OK == res)
1122 * message ID is supported for CoAP over UDP only according to RFC 7252
1123 * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1124 * In case of other transport adapter, duplicate message check is not required.
1126 if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1127 previousMsgId == ehRequest->messageID)
1129 isDuplicatedMsg = true;
1132 if (isDuplicatedMsg && ehRequest->messageID == gConfirmMsgId)
1134 if (CONFIRM_STATE_WAIT == gConfirmState)
1136 OIC_LOG(DEBUG, TAG, "Confirm callback already invoked.");
1137 OIC_LOG(DEBUG, TAG, "This request will be ignored.");
1138 DeleteDoxmBinData(newDoxm);
1143 OIC_LOG_V(DEBUG, TAG, "Confirm request already done, Confirm Result = %s", (CONFIRM_STATE_ACCEPTED == gConfirmState ? "ACCEPTED" : "DENIED"));
1144 ehRet = (CONFIRM_STATE_ACCEPTED == gConfirmState ? OC_EH_OK : OC_EH_NOT_ACCEPTABLE);
1149 // Check request on RO property
1150 if (true == roParsed)
1152 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1153 ehRet = OC_EH_NOT_ACCEPTABLE;
1157 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
1160 if (true == gDoxm->owned)
1162 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1164 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1165 ehRet = OC_EH_NOT_ACCEPTABLE;
1168 //Update gDoxm based on newDoxm
1169 updateWriteableProperty(newDoxm, gDoxm);
1171 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1172 #ifdef MULTIPLE_OWNER
1176 if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1178 CAResult_t caRes = CA_STATUS_FAILED;
1179 if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1181 caRes = CAEnableAnonECDHCipherSuite(false);
1182 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1183 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1185 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, ehRequest->devAddr.adapter);
1186 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1187 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1189 //Set the device id to derive temporal PSK
1190 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1194 OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1197 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1201 //if MOM is disabled, revert the DTLS handshake callback
1202 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1204 OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1209 if(newDoxm->subOwners)
1211 OicSecSubOwner_t* subowner = NULL;
1212 OicSecSubOwner_t* temp = NULL;
1214 OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1216 if(gDoxm->subOwners)
1218 LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1220 LL_DELETE(gDoxm->subOwners, subowner);
1227 LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1229 LL_DELETE(newDoxm->subOwners, subowner);
1230 LL_APPEND(gDoxm->subOwners, subowner);
1233 #endif //MULTIPLE_OWNER
1234 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1236 //Update new state in persistent storage
1237 if (UpdatePersistentStorage(gDoxm) == true)
1243 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1244 ehRet = OC_EH_ERROR;
1250 if ((false == gDoxm->owned) && (false == newDoxm->owned))
1252 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1254 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1255 ehRet = OC_EH_NOT_ACCEPTABLE;
1258 if (g_InformOxmSelectedCallback)
1260 g_InformOxmSelectedCallback(newDoxm->oxmSel);
1263 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1264 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1266 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1267 NULL, OIC_OTM_STARTED);
1271 OIC_LOG_V(INFO, TAG, "%s: request owner not empty",__func__);
1272 char* strUuid = NULL;
1273 if (OC_STACK_OK == ConvertUuidToStr(&newDoxm->owner, &strUuid))
1275 OIC_LOG_V(INFO, TAG, "%s: request owner: %s",__func__, strUuid);
1281 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1284 * If current state of the device is un-owned, enable
1285 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1286 * tool can initiate JUST_WORKS ownership transfer process.
1288 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1290 gDoxm->oxmSel = newDoxm->oxmSel;
1291 //Update new state in persistent storage
1292 if ((UpdatePersistentStorage(gDoxm) == true))
1298 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1299 ehRet = OC_EH_ERROR;
1302 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
1303 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1304 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1305 #endif // __WITH_DTLS__ or __WITH_TLS__
1310 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1311 //Save the owner's UUID to derive owner credential
1312 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1314 // Update new state in persistent storage
1315 if (true == UpdatePersistentStorage(gDoxm))
1321 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1322 ehRet = OC_EH_ERROR;
1327 * Disable anonymous ECDH cipher in tinyDTLS since device is now
1330 CAResult_t caRes = CA_STATUS_OK;
1331 caRes = CAEnableAnonECDHCipherSuite(false);
1332 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1333 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1335 //In case of Mutual Verified Just-Works, verify mutualVerifNum
1336 if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1337 false == isDuplicatedMsg)
1339 uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1340 uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1341 OicUuid_t deviceID = {.id = {0}};
1343 //Generate mutualVerifNum
1344 OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1346 char label[LABEL_LEN] = {0};
1347 snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1348 if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1350 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1351 ehRet = OC_EH_ERROR;
1356 CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1359 gDoxm->owner.id, sizeof(gDoxm->owner.id),
1360 gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1361 preMutualVerifNum, OWNER_PSK_LENGTH_128);
1362 if (CA_STATUS_OK != pskRet)
1364 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1365 ehRet = OC_EH_ERROR;
1370 memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1371 sizeof(mutualVerifNum));
1373 gConfirmMsgId = ehRequest->messageID;
1374 gConfirmState = CONFIRM_STATE_WAIT;
1375 //Wait for user confirmation
1376 if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1378 ehRet = OC_EH_NOT_ACCEPTABLE;
1379 gConfirmState = CONFIRM_STATE_DENIED;
1384 gConfirmState = CONFIRM_STATE_ACCEPTED;
1388 #endif // __WITH_DTLS__ or __WITH_TLS__
1391 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1394 * If current state of the device is un-owned, enable
1395 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1396 * tool can initiate JUST_WORKS ownership transfer process.
1398 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1400 gDoxm->oxmSel = newDoxm->oxmSel;
1401 //Update new state in persistent storage
1402 if ((UpdatePersistentStorage(gDoxm) == true))
1408 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1409 ehRet = OC_EH_ERROR;
1412 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1413 CAResult_t caRes = CA_STATUS_OK;
1415 caRes = CAEnableAnonECDHCipherSuite(false);
1416 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1417 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1419 caRes = CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
1420 ehRequest->devAddr.adapter);
1421 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1423 if (!isDuplicatedMsg)
1425 char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1426 if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1428 //Set the device id to derive temporal PSK
1429 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1432 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1433 * Credential should not be saved into SVR.
1434 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1436 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1437 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1442 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1443 ehRet = OC_EH_ERROR;
1446 #endif // __WITH_DTLS__ or __WITH_TLS__
1448 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1451 //Save the owner's UUID to derive owner credential
1452 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1454 // In case of random-pin based OTM, close the PIN display if callback is registered.
1455 if (!isDuplicatedMsg)
1460 //Update new state in persistent storage
1461 if (UpdatePersistentStorage(gDoxm) == true)
1467 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1468 ehRet = OC_EH_ERROR;
1471 #endif // __WITH_DTLS__ or __WITH_TLS__
1473 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1474 else if (OIC_MANUFACTURER_CERTIFICATE == newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1476 //Get user confirmation
1477 if (false == newDoxm->owned &&
1478 false == isDuplicatedMsg &&
1479 memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1481 gConfirmMsgId = ehRequest->messageID;
1482 gConfirmState = CONFIRM_STATE_WAIT;
1483 if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1485 ehRet = OC_EH_NOT_ACCEPTABLE;
1486 gConfirmState = CONFIRM_STATE_DENIED;
1492 gConfirmState = CONFIRM_STATE_ACCEPTED;
1496 //Save the owner's UUID to derive owner credential
1497 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1498 gDoxm->oxmSel = newDoxm->oxmSel;
1499 //Update new state in persistent storage
1500 if (UpdatePersistentStorage(gDoxm))
1506 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1507 ehRet = OC_EH_ERROR;
1509 CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1510 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1511 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1513 //Unset pre-selected ciphersuite, if any
1514 caRes = CASelectCipherSuite(0, ehRequest->devAddr.adapter);
1515 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1516 OIC_LOG(DEBUG, TAG, "No ciphersuite preferred");
1518 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1519 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1521 #endif // __WITH_DTLS__ or __WITH_TLS__
1525 * When current state of the device is un-owned and Provisioning
1526 * Tool is attempting to change the state to 'Owned' with a
1527 * qualified value for the field 'Owner'
1529 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1530 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1532 //Change the SVR's resource owner as owner device.
1533 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1534 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1536 ehRet = OC_EH_ERROR;
1539 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1540 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1542 ehRet = OC_EH_ERROR;
1545 ownerRes = SetCredRownerId(&gDoxm->owner);
1546 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1548 ehRet = OC_EH_ERROR;
1551 ownerRes = SetPstatRownerId(&gDoxm->owner);
1552 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1554 ehRet = OC_EH_ERROR;
1558 gDoxm->owned = true;
1559 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1561 // Update new state in persistent storage
1562 if (UpdatePersistentStorage(gDoxm))
1564 //Update default ACE of security resource to prevent anonymous user access.
1565 if(OC_STACK_OK == UpdateDefaultSecProvACE())
1571 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1572 ehRet = OC_EH_ERROR;
1577 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1578 ehRet = OC_EH_ERROR;
1580 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1581 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1582 OIC_CON_MFG_CERT== gDoxm->oxmSel)
1584 CAregisterPkixInfoHandler(GetPkixInfo);
1585 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1588 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1589 &gDoxm->owner, OIC_OTM_DONE);
1590 #endif // __WITH_DTLS__ or __WITH_TLS__
1596 if(OC_EH_OK != ehRet)
1599 * If some error is occured while ownership transfer,
1600 * ownership transfer related resource should be revert back to initial status.
1606 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1608 if (!isDuplicatedMsg)
1610 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1611 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1612 NULL, OIC_OTM_ERROR);
1614 RestoreDoxmToInitState();
1615 RestorePstatToInitState();
1616 OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1622 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1626 previousMsgId = ehRequest->messageID;
1628 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1629 CAEndpoint_t peer = {0};
1630 OCDevAddr devAddr = ehRequest->devAddr;
1632 memcpy(&peer.addr, &devAddr.addr, sizeof(peer.addr));
1633 peer.port = devAddr.port;
1634 peer.adapter = (CATransportAdapter_t)devAddr.adapter;
1636 if ((devAddr.flags & OC_FLAG_SECURE) && (false == CAIsExistSslPeer(&peer)))
1638 OIC_LOG_V(WARNING, TAG, "Not Exist Peer");
1643 //Send payload to request originator
1644 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1645 OC_EH_OK : OC_EH_ERROR;
1648 //Send payload to request originator
1649 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1650 OC_EH_OK : OC_EH_ERROR;
1653 DeleteDoxmBinData(newDoxm);
1658 #ifdef MULTIPLE_OWNER
1659 static OCEntityHandlerResult HandleDoxmDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1661 OIC_LOG(DEBUG, TAG, "Processing DoxmDeleteRequest");
1663 OCEntityHandlerResult ehRet = OC_EH_BAD_REQ;
1665 if (NULL == ehRequest->query)
1670 OicParseQueryIter_t parseIter = { .attrPos=NULL };
1671 OicUuid_t subject = {.id={0}};
1673 //Parsing REST query to get the subject
1674 ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1675 while (GetNextQuery(&parseIter))
1677 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBOWNERID_NAME,
1678 parseIter.attrLen) == 0)
1680 if (0 == strncmp((const char*)parseIter.valPos, WILDCARD_RESOURCE_URI,
1681 strlen(WILDCARD_RESOURCE_URI)))
1683 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&WILDCARD_SUBJECT_ID))
1685 ehRet = OC_EH_RESOURCE_DELETED;
1690 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
1691 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1693 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&subject))
1695 ehRet = OC_EH_RESOURCE_DELETED;
1701 //Send response to request originator
1702 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1703 OC_EH_OK : OC_EH_ERROR;
1709 #endif //MULTIPLE_OWNER
1711 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1712 OCEntityHandlerRequest * ehRequest,
1713 void* callbackParam)
1715 (void)callbackParam;
1716 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1718 if(NULL == ehRequest)
1723 oc_mutex_lock(g_mutexDoxm);
1727 oc_mutex_unlock(g_mutexDoxm);
1728 return OC_EH_SERVICE_UNAVAILABLE;
1731 if (flag & OC_REQUEST_FLAG)
1733 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1735 switch (ehRequest->method)
1738 ehRet = HandleDoxmGetRequest(ehRequest);
1742 ehRet = HandleDoxmPostRequest(ehRequest);
1745 #ifdef MULTIPLE_OWNER
1746 case OC_REST_DELETE:
1747 ehRet = HandleDoxmDeleteRequest(ehRequest);
1749 #endif //MULTIPLE_OWNER
1752 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1753 OC_EH_OK : OC_EH_ERROR;
1757 oc_mutex_unlock(g_mutexDoxm);
1763 OCStackResult CreateDoxmResource()
1765 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1766 OIC_RSRC_TYPE_SEC_DOXM,
1767 OC_RSRVD_INTERFACE_DEFAULT,
1774 if (OC_STACK_OK != ret)
1776 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1777 DeInitDoxmResource();
1783 * Checks if DeviceID is generated during provisioning for the new device.
1784 * If DeviceID is NULL then generates the new DeviceID.
1785 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1787 static OCStackResult CheckDeviceID()
1789 OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
1791 OCStackResult ret = OC_STACK_ERROR;
1792 bool validId = false;
1796 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
1797 return OC_STACK_INVALID_PARAM;
1800 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1802 if (gDoxm->deviceID.id[i] != 0)
1811 char* strUuid = NULL;
1812 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1813 //If seed value is exist, generate UUID using seed with SHA256
1814 if (0 != gUuidSeedSize)
1816 uint8_t hashVal[MBEDTLS_MD_MAX_SIZE] = {0};
1817 mbedtls_md_context_t sha_ctx;
1820 OIC_LOG(DEBUG, TAG, "UUID will be generated using seed w/ SHA256");
1821 OIC_LOG(DEBUG, TAG, "Seed value : ");
1822 OIC_LOG_BUFFER(DEBUG, TAG, gUuidSeed, gUuidSeedSize);
1824 mbedtls_md_init( &sha_ctx );
1825 mbedret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
1828 mbedtls_md_starts( &sha_ctx );
1829 mbedtls_md_update( &sha_ctx, gUuidSeed, gUuidSeedSize);
1830 mbedtls_md_finish(&sha_ctx, (unsigned char*)hashVal);
1831 memcpy(gDoxm->deviceID.id, hashVal, sizeof(gDoxm->deviceID.id));
1836 OIC_LOG_V(ERROR, TAG, "mbedtls_md_setup() returned -0x%04x\n", -mbedret);
1837 ret = OC_STACK_ERROR;
1839 mbedtls_md_free( &sha_ctx );
1843 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
1845 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1846 return OC_STACK_ERROR;
1851 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
1853 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1859 if (OC_STACK_OK == ConvertUuidToStr(&gDoxm->deviceID, &strUuid))
1861 OIC_LOG_V(DEBUG, TAG, "Generated device UUID is [%s]", strUuid);
1866 OIC_LOG(WARNING, TAG, "Failed to convert UUID to string");
1870 if (!UpdatePersistentStorage(gDoxm))
1872 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1873 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1881 OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
1887 * Get the default value.
1889 * @return the default value of doxm, @ref OicSecDoxm_t.
1891 static OicSecDoxm_t* GetDoxmDefault()
1893 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1894 return &gDefaultDoxm;
1897 const OicSecDoxm_t* GetDoxmResourceData()
1902 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1904 * Internal API to prepare MOT
1906 static void PrepareMOT(const OicSecDoxm_t* doxm)
1908 OIC_LOG(INFO, TAG, "IN PrepareMOT");
1909 VERIFY_NON_NULL(TAG, doxm, ERROR);
1911 if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1913 CAResult_t caRes = CA_STATUS_FAILED;
1915 OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1917 if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1919 caRes = CAEnableAnonECDHCipherSuite(false);
1920 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1921 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1923 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP);
1924 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1926 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_TCP);
1927 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1929 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1931 //Set the device id to derive temporal PSK
1932 SetUuidForPinBasedOxm(&doxm->deviceID);
1936 OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1940 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1943 OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1946 OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1948 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1950 OCStackResult InitDoxmResource()
1952 OCStackResult ret = OC_STACK_ERROR;
1956 g_mutexDoxm = oc_mutex_new();
1959 return OC_STACK_ERROR;
1963 gConfirmState = CONFIRM_STATE_READY;
1966 //Read DOXM resource from PS
1967 uint8_t *data = NULL;
1969 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1970 // If database read failed
1971 if (OC_STACK_OK != ret)
1973 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1977 // Read DOXM resource from PS
1978 ret = CBORPayloadToDoxm(data, size, &gDoxm);
1981 * If SVR database in persistent storage got corrupted or
1982 * is not available for some reason, a default doxm is created
1983 * which allows user to initiate doxm provisioning again.
1985 if ((OC_STACK_OK != ret) || !data || !gDoxm)
1987 gDoxm = GetDoxmDefault();
1990 oc_mutex_lock(g_mutexDoxm);
1991 g_isDoxmNull = false;
1992 oc_mutex_unlock(g_mutexDoxm);
1994 //In case of the server is shut down unintentionally, we should initialize the owner
1995 if(gDoxm && (false == gDoxm->owned))
1997 OicUuid_t emptyUuid = {.id={0}};
1998 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1999 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
2000 InvokeOtmEventHandler(NULL, 0, NULL, OIC_OTM_READY);
2004 ret = CheckDeviceID();
2005 if (ret == OC_STACK_OK)
2007 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
2008 //Instantiate 'oic.sec.doxm'
2009 ret = CreateDoxmResource();
2013 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
2017 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2018 //if MOT is enabled, MOT should be prepared.
2019 if(gDoxm && gDoxm->owned)
2023 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2028 OCStackResult DeInitDoxmResource()
2030 oc_mutex_lock(g_mutexDoxm);
2031 OCStackResult ret = OCDeleteResource(gDoxmHandle);
2032 if (gDoxm != &gDefaultDoxm)
2034 DeleteDoxmBinData(gDoxm);
2037 g_isDoxmNull = true;
2039 if (OC_STACK_OK == ret)
2041 oc_mutex_unlock(g_mutexDoxm);
2046 oc_mutex_unlock(g_mutexDoxm);
2047 return OC_STACK_ERROR;
2051 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
2053 if (deviceID && gDoxm)
2055 *deviceID = gDoxm->deviceID;
2058 return OC_STACK_ERROR;
2061 OCStackResult GetDoxmIsOwned(bool *isOwned)
2063 if (isOwned && gDoxm)
2065 *isOwned = gDoxm->owned;
2068 return OC_STACK_ERROR;
2071 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2072 OCStackResult SetDoxmDeviceIDSeed(const uint8_t* seed, size_t seedSize)
2074 OIC_LOG_V(INFO, TAG, "In %s", __func__);
2078 return OC_STACK_INVALID_PARAM;
2080 if (MAX_UUID_SEED_SIZE < seedSize)
2082 OIC_LOG_V(ERROR, TAG, "Seed size is too long (MAX size is %d bytes)", MAX_UUID_SEED_SIZE);
2083 return OC_STACK_INVALID_PARAM;
2085 if (MIN_UUID_SEED_SIZE > seedSize)
2087 OIC_LOG_V(ERROR, TAG, "Seed size is too small (MIN size is %d bytes)", MIN_UUID_SEED_SIZE);
2088 return OC_STACK_INVALID_PARAM;
2091 memset(gUuidSeed, 0x00, sizeof(gUuidSeed));
2092 memcpy(gUuidSeed, seed, seedSize);
2093 gUuidSeedSize = seedSize;
2095 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2102 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
2104 bool isOwnerUpdated = false;
2105 bool isRownerUpdated = false;
2106 if (NULL == deviceID)
2108 return OC_STACK_INVALID_PARAM;
2112 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
2113 return OC_STACK_NO_RESOURCE;
2116 #ifdef __WITH_DTLS__
2117 //for normal device.
2118 if (true == gDoxm->owned
2119 && memcmp(gEmptyUuid, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0
2120 && memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
2122 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
2123 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
2124 return OC_STACK_ERROR;
2126 #endif //__WITH_DTLS
2128 //Save the previous UUID
2130 memcpy(prevUuid.id, gDoxm->deviceID.id, sizeof(prevUuid.id));
2132 //Change the device UUID
2133 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
2135 //Change the owner ID if necessary
2136 if (memcmp(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2138 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
2139 isOwnerUpdated = true;
2141 //Change the resource owner ID if necessary
2142 if (memcmp(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2144 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
2145 isRownerUpdated = true;
2147 // TODO: T.B.D Change resource owner for pstat, acl and cred
2150 if (!UpdatePersistentStorage(gDoxm))
2152 //revert UUID in case of PSI error
2153 memcpy(gDoxm->deviceID.id, prevUuid.id, sizeof(prevUuid.id));
2156 memcpy(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id));
2158 if (isRownerUpdated)
2160 memcpy(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id));
2162 // TODO: T.B.D Revert resource owner for pstat, acl and cred
2164 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
2165 return OC_STACK_ERROR;
2170 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
2172 OCStackResult retVal = OC_STACK_ERROR;
2175 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
2179 *devownerid = gDoxm->owner;
2180 retVal = OC_STACK_OK;
2186 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
2188 OCStackResult retVal = OC_STACK_ERROR;
2193 *rowneruuid = gDoxm->rownerID;
2194 retVal = OC_STACK_OK;
2200 #ifdef MULTIPLE_OWNER
2202 * Compare the UUID to SubOwner.
2204 * @param[in] uuid device UUID
2206 * @return true if context->subjectId exist subowner list, else false.
2208 bool IsSubOwner(const OicUuid_t* uuid)
2210 bool retVal = false;
2217 if (gDoxm && gDoxm->subOwners)
2219 if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
2224 OicSecSubOwner_t* subOwner = NULL;
2225 LL_FOREACH(gDoxm->subOwners, subOwner)
2227 if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
2235 #endif //MULTIPLE_OWNER
2237 OCStackResult SetMOTStatus(bool enable)
2239 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2240 #ifdef MULTIPLE_OWNER
2241 OCStackResult ret = OC_STACK_NO_MEMORY;
2242 uint8_t *cborPayload = NULL;
2244 bool isDeallocateRequired = false;
2246 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
2248 if (NULL == gDoxm->mom && !enable)
2250 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2254 if (NULL == gDoxm->mom)
2256 gDoxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
2257 VERIFY_NON_NULL(TAG, gDoxm->mom, ERROR);
2258 isDeallocateRequired = true;
2261 gDoxm->mom->mode = (enable ? OIC_MULTIPLE_OWNER_ENABLE : OIC_MULTIPLE_OWNER_DISABLE);
2262 gDoxm->oxmSel = OIC_PRECONFIG_PIN;
2264 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2265 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2267 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2268 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2270 isDeallocateRequired = false;
2273 if (isDeallocateRequired)
2275 OICFree(gDoxm->mom);
2279 OICFree(cborPayload);
2281 OIC_LOG_V(DEBUG, TAG, "Out %s : %d", __func__, ret);
2285 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2286 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2287 return OC_STACK_ERROR;
2288 #endif //MULTIPLE_OWNER
2291 OCStackResult RemoveSubOwner(const OicUuid_t* subOwner)
2293 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2294 #ifdef MULTIPLE_OWNER
2295 OCStackResult ret = OC_STACK_ERROR;
2296 bool isDeleted = false;
2298 if (NULL == subOwner)
2300 OIC_LOG(ERROR, TAG, "Invalid sub owner UUID.");
2301 return OC_STACK_INVALID_PARAM;
2305 OIC_LOG(ERROR, TAG, "Doxm resource is NULL");
2306 return OC_STACK_NO_RESOURCE;
2308 if ( NULL == gDoxm->subOwners)
2310 OIC_LOG(WARNING, TAG, "Sub Owner list is empty.");
2311 return OC_STACK_ERROR;
2314 OicSecSubOwner_t* curSubOwner = NULL;
2315 OicSecSubOwner_t* tempSubOwner = NULL;
2316 LL_FOREACH_SAFE(gDoxm->subOwners, curSubOwner, tempSubOwner)
2318 if (memcmp(curSubOwner->uuid.id, subOwner->id, sizeof(subOwner->id)) == 0 ||
2319 memcmp(WILDCARD_SUBJECT_ID.id, subOwner->id, sizeof(OicUuid_t)) == 0)
2321 char* strUuid = NULL;
2322 ret = ConvertUuidToStr(&curSubOwner->uuid, &strUuid);
2323 if (OC_STACK_OK != ret)
2325 OIC_LOG_V(ERROR, TAG, "ConvertUuidToStr error : %d", ret);
2329 OIC_LOG_V(INFO, TAG, "[%s] will be removed from sub owner list.", strUuid);
2330 LL_DELETE(gDoxm->subOwners, curSubOwner);
2332 //Remove the cred for sub owner
2333 ret = RemoveCredential(&curSubOwner->uuid);
2334 if (OC_STACK_RESOURCE_DELETED != ret)
2336 OIC_LOG_V(WARNING, TAG, "RemoveCredential error for [%s] : %d", strUuid, ret);
2340 // TODO: Remove the ACL for sub owner (Currently ACL is not required for sub-owner)
2350 //Update persistent storage
2351 if (UpdatePersistentStorage(gDoxm))
2353 ret = OC_STACK_RESOURCE_DELETED;
2357 OIC_LOG(ERROR, TAG, "UpdatePersistentStorage error");
2358 ret = OC_STACK_ERROR;
2362 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2365 OC_UNUSED(subOwner);
2366 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2367 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2368 return OC_STACK_ERROR;
2369 #endif //MULTIPLE_OWNER
2373 OCStackResult SetNumberOfSubOwner(size_t numOfSubOwner)
2375 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2376 #ifdef MULTIPLE_OWNER
2377 if (MAX_SUBOWNER_SIZE < numOfSubOwner || MIN_SUBOWNER_SIZE > numOfSubOwner)
2379 OIC_LOG_V(ERROR, TAG, "Invalid number of sub owner : %zd", numOfSubOwner);
2380 return OC_STACK_INVALID_PARAM;
2382 gMaxSubOwnerSize = numOfSubOwner;
2383 OIC_LOG_V(DEBUG, TAG, "Number of SubOwner = %zd", gMaxSubOwnerSize);
2384 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2387 OC_UNUSED(numOfSubOwner);
2388 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2389 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2390 return OC_STACK_ERROR;
2391 #endif //MULTIPLE_OWNER
2395 * Function to restore doxm resurce to initial status.
2396 * This function will use in case of error while ownership transfer
2398 void RestoreDoxmToInitState()
2401 gConfirmState = CONFIRM_STATE_READY;
2406 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
2408 OicUuid_t emptyUuid = {.id={0}};
2409 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
2410 gDoxm->owned = false;
2411 gDoxm->oxmSel = OIC_JUST_WORKS;
2413 if(!UpdatePersistentStorage(gDoxm))
2415 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
2420 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
2422 OCStackResult ret = OC_STACK_ERROR;
2423 uint8_t *cborPayload = NULL;
2428 ret = OC_STACK_NO_RESOURCE;
2432 if( newROwner && (false == gDoxm->owned) )
2434 gDoxm->owned = true;
2435 memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
2436 memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
2438 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2439 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2441 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2442 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2444 OICFree(cborPayload);
2450 OICFree(cborPayload);