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 #include "oic_string.h"
55 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
56 #include "pkix_interface.h"
57 #include "ca_adapter_net_ssl.h"
60 #define TAG "OIC_SRM_DOXM"
61 #define CHAR_ZERO ('0')
63 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
64 * The value of payload size is increased until reaching belox max cbor size. */
65 static const uint16_t CBOR_SIZE = 512;
67 /** Max cbor size payload. */
68 static const uint16_t CBOR_MAX_SIZE = 4400;
70 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
71 /** MAX uuid seed size */
72 #define MAX_UUID_SEED_SIZE (64)
73 /** MIN uuid seed size */
74 #define MIN_UUID_SEED_SIZE (8)
76 /** Buffer to save the seed of device UUID */
77 static uint8_t gUuidSeed[MAX_UUID_SEED_SIZE];
78 static size_t gUuidSeedSize = 0;
82 #define MAX_SUBOWNER_SIZE (64)
83 #define MIN_SUBOWNER_SIZE (1)
84 #define DEFAULT_SUBOWNER_SIZE (32)
86 static size_t gMaxSubOwnerSize = DEFAULT_SUBOWNER_SIZE;
89 typedef enum ConfirmState{
90 CONFIRM_STATE_READY = 0,
91 CONFIRM_STATE_WAIT = 1,
92 CONFIRM_STATE_ACCEPTED = 2,
93 CONFIRM_STATE_DENIED = 3
96 static OicSecDoxm_t *gDoxm = NULL;
97 static oc_mutex g_mutexDoxm = NULL;
98 static bool g_isDoxmNull = false;
99 static OCResourceHandle gDoxmHandle = NULL;
100 static oc_mutex g_mutexWait;
101 static oc_thread g_waitConfirmThreadId;
103 static InformOxmSelectedCallback_t g_InformOxmSelectedCallback = NULL;
104 static bool g_isConfirmResult;
106 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
107 static OicSecDoxm_t gDefaultDoxm =
109 NULL, /* OicUrn_t *oxmType */
110 0, /* size_t oxmTypeLen */
111 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
112 1, /* size_t oxmLen */
113 OIC_JUST_WORKS, /* uint16_t oxmSel */
114 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
115 false, /* bool owned */
116 {.id = {0}}, /* OicUuid_t deviceID */
117 false, /* bool dpc */
118 {.id = {0}}, /* OicUuid_t owner */
119 #ifdef MULTIPLE_OWNER
120 NULL, /* OicSecSubOwner_t sub-owner list */
121 NULL, /* OicSecMomType_t multiple owner mode */
122 #endif //MULTIPLE_OWNER
123 {.id = {0}}, /* OicUuid_t rownerID */
126 static uint16_t gConfirmMsgId = 0;
127 static ConfirmState_t gConfirmState = CONFIRM_STATE_READY;
129 static uint8_t gEmptyUuid[UUID_LENGTH] = {0};
132 * This method is internal method.
133 * the param roParsed is optionally used to know whether cborPayload has
134 * at least read only property value or not.
136 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
137 OicSecDoxm_t **doxm, bool *roParsed);
139 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
144 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
146 OICFree(doxm->oxmType[i]);
148 OICFree(doxm->oxmType);
153 #ifdef MULTIPLE_OWNER
157 //clean sub-owner list
158 if(NULL != doxm->subOwners)
160 OicSecSubOwner_t* subowner = NULL;
161 OicSecSubOwner_t* temp = NULL;
162 LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
164 LL_DELETE(doxm->subOwners, subowner);
168 #endif //MULTIPLE_OWNER
176 oc_mutex_free(g_mutexDoxm);
181 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
184 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
186 return OC_STACK_INVALID_PARAM;
188 size_t cborLen = *size;
196 OCStackResult ret = OC_STACK_ERROR;
200 char* strUuid = NULL;
202 int64_t cborEncoderResult = CborNoError;
204 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
205 VERIFY_NON_NULL(TAG, outPayload, ERROR);
206 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
208 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
209 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
211 //OxmType -- Not Mandatory
212 if (doxm->oxmTypeLen > 0)
215 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
216 strlen(OIC_JSON_OXM_TYPE_NAME));
217 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
218 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
219 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
221 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
223 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
224 strlen(doxm->oxmType[i]));
225 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
227 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
228 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
231 //Oxm -- Not Mandatory
232 if (doxm->oxmLen > 0 && false == rwOnly)
235 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
236 strlen(OIC_JSON_OXMS_NAME));
237 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
238 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
239 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
241 for (size_t i = 0; i < doxm->oxmLen; i++)
243 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
244 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
246 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
247 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
250 //OxmSel -- Mandatory
251 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
252 strlen(OIC_JSON_OXM_SEL_NAME));
253 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
254 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
255 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
260 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
261 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
262 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
263 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
264 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
268 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
269 strlen(OIC_JSON_OWNED_NAME));
270 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
271 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
272 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
276 //DeviceId -- Mandatory
277 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
278 strlen(OIC_JSON_DEVICE_ID_NAME));
279 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
280 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
281 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
282 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
283 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
288 #ifdef MULTIPLE_OWNER
289 //Device SubOwnerID -- Not Mandatory
292 size_t subOwnerLen = 0;
293 OicSecSubOwner_t* subOwner = NULL;
294 LL_FOREACH(doxm->subOwners, subOwner)
299 CborEncoder subOwners;
300 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
301 strlen(OIC_JSON_SUBOWNERID_NAME));
302 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
303 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
304 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
307 LL_FOREACH(doxm->subOwners, subOwner)
309 char* strUuid = NULL;
310 ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
311 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
312 cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
314 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
316 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
317 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
320 //Multiple Owner Mode -- Not Mandatory
323 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
324 strlen(OIC_JSON_MOM_NAME));
325 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
326 cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
327 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
329 #endif //MULTIPLE_OWNER
331 //devownerid -- Mandatory
332 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
333 strlen(OIC_JSON_DEVOWNERID_NAME));
334 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
335 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
336 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
337 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
338 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
342 //ROwner -- Mandatory
343 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
344 strlen(OIC_JSON_ROWNERID_NAME));
345 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
346 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
347 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
348 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
349 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
355 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
356 strlen(OIC_JSON_RT_NAME));
357 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
358 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
359 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
360 for (size_t i = 0; i < 1; i++)
362 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
363 strlen(OIC_RSRC_TYPE_SEC_DOXM));
364 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
366 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
367 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
371 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
372 strlen(OIC_JSON_IF_NAME));
373 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
374 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
375 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
376 for (size_t i = 0; i < 1; i++)
378 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
379 strlen(OC_RSRVD_INTERFACE_DEFAULT));
380 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
382 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
383 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
385 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
386 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
388 if (CborNoError == cborEncoderResult)
390 *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
391 *payload = outPayload;
395 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
397 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
398 // reallocate and try again!
401 // Since the allocated initial memory failed, double the memory.
402 cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
403 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
404 cborEncoderResult = CborNoError;
405 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
409 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
415 ret = OC_STACK_ERROR;
421 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
422 OicSecDoxm_t **secDoxm)
424 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
427 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
428 OicSecDoxm_t **secDoxm, bool *roParsed)
430 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
432 return OC_STACK_INVALID_PARAM;
435 OCStackResult ret = OC_STACK_ERROR;
439 CborError cborFindResult = CborNoError;
440 char* strUuid = NULL;
444 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
446 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
447 VERIFY_NON_NULL(TAG, doxm, ERROR);
449 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
450 //OxmType -- not Mandatory
451 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
455 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
456 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
457 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
459 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
460 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
462 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
463 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
467 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
469 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
471 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
472 cborFindResult = cbor_value_advance(&oxmType);
473 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
477 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
478 //Oxm -- not Mandatory
479 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
482 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
483 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
484 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
486 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
487 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
489 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
490 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
493 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
497 cborFindResult = cbor_value_get_int(&oxm, &tmp);
498 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
499 doxm->oxm[i++] = (OicSecOxm_t)tmp;
500 cborFindResult = cbor_value_advance(&oxm);
501 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
511 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
512 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
513 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
514 doxm->oxmLen = gDoxm->oxmLen;
515 for (size_t i = 0; i < gDoxm->oxmLen; i++)
517 doxm->oxm[i] = gDoxm->oxm[i];
521 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
522 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
526 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
527 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
528 doxm->oxmSel = (OicSecOxm_t)oxmSel;
530 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
532 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
533 doxm->oxmSel = gDoxm->oxmSel;
536 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
537 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
541 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
542 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
543 doxm->sct = (OicSecCredType_t)sct;
550 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
552 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
553 doxm->sct = gDoxm->sct;
556 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
557 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
559 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
560 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
562 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
564 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
565 doxm->owned = gDoxm->owned;
568 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
569 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
571 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
572 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
573 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
574 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
580 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
581 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
584 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
585 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
587 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
588 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
589 ret = ConvertStrToUuid(strUuid , &doxm->owner);
590 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
596 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
597 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
600 #ifdef MULTIPLE_OWNER
601 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
602 if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
605 cborFindResult = cbor_value_get_int(&doxmMap, &mode);
606 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
607 if(NULL == doxm->mom)
609 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
610 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
612 doxm->mom->mode = (OicSecMomType_t)mode;
614 else if(NULL != gDoxm && NULL != gDoxm->mom)
616 // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
617 if(NULL == doxm->mom)
619 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
620 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
622 doxm->mom->mode = gDoxm->mom->mode;
625 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
626 if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
628 size_t subOwnerLen = 0;
629 CborValue subOwnerCbor;
630 cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
631 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
632 VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
634 cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
635 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
637 while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
639 OCStackResult convertRes = OC_STACK_ERROR;
640 OicSecSubOwner_t* subOwner = NULL;
641 char* strUuid = NULL;
644 cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
645 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
647 subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
648 VERIFY_NON_NULL(TAG, subOwner, ERROR);
650 convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
651 VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
652 subOwner->status = MOT_STATUS_DONE;
653 LL_APPEND(doxm->subOwners, subOwner);
655 cborFindResult = cbor_value_advance(&subOwnerCbor);
656 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
659 else if(NULL != gDoxm && NULL != gDoxm->subOwners)
661 // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
662 OicSecSubOwner_t* subOwnerItor = NULL;
663 LL_FOREACH(gDoxm->subOwners, subOwnerItor)
665 OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
666 VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
668 memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
669 subOwnerId->status = MOT_STATUS_DONE;
671 LL_APPEND(doxm->subOwners, subOwnerId);
674 #endif //MULTIPLE_OWNER
676 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
677 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
679 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
680 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
681 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
682 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
688 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
689 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
696 if (CborNoError != cborFindResult)
698 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
699 DeleteDoxmBinData(doxm);
702 ret = OC_STACK_ERROR;
708 * @todo document this function including why code might need to call this.
709 * The current suspicion is that it's not being called as much as it should.
711 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
717 // Convert Doxm data into CBOR for update to persistent storage
718 uint8_t *payload = NULL;
720 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
721 if (payload && (OC_STACK_OK == res)
722 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
730 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
739 static bool ValidateQuery(const char * query)
741 // Send doxm resource data if the state of doxm resource
742 // matches with the query parameters.
743 // else send doxm resource data as NULL
744 // TODO Remove this check and rely on Policy Engine
745 // and Provisioning Mode to enforce provisioning-state
746 // access rules. Eventually, the PE and PM code will
747 // not send a request to the /doxm Entity Handler at all
748 // if it should not respond.
749 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
755 bool bOwnedQry = false; // does querystring contains 'owned' query ?
756 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
757 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
758 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
759 bool bInterfaceQry = false; // does querystring contains 'if' query ?
760 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
761 #ifdef MULTIPLE_OWNER
762 bool bMotMatch = false; // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
763 #endif //MULTIPLE_OWNER
765 OicParseQueryIter_t parseIter = {.attrPos = NULL};
767 ParseQueryIterInit((unsigned char*)query, &parseIter);
769 while (GetNextQuery(&parseIter))
771 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
774 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
779 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
786 #ifdef MULTIPLE_OWNER
787 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
789 OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
790 if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
792 if(GetNextQuery(&parseIter))
794 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
796 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
806 #endif //MULTIPLE_OWNER
808 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
811 OicUuid_t subject = {.id={0}};
813 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
814 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
816 bDeviceIDMatch = true;
820 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
822 bInterfaceQry = true;
823 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
825 bInterfaceMatch = true;
827 return (bInterfaceQry ? bInterfaceMatch: true);
831 return ((bOwnedQry ? bOwnedMatch : true) &&
832 (bDeviceIDQry ? bDeviceIDMatch : true));
835 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
837 OCEntityHandlerResult ehRet = OC_EH_OK;
839 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
841 //Checking if Get request is a query.
842 if (ehRequest->query)
844 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
845 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
846 if (!ValidateQuery(ehRequest->query))
853 * For GET or Valid Query request return doxm resource CBOR payload.
854 * For non-valid query return NULL json payload.
855 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
856 * return valid doxm resource json.
858 uint8_t *payload = NULL;
861 if (ehRet == OC_EH_OK)
863 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
865 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
869 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
870 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
872 // Send response payload to request originator
873 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
874 OC_EH_OK : OC_EH_ERROR;
881 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
886 dst->oxmSel = src->oxmSel;
889 memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
892 memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
895 memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
897 //Update owned status
898 if(dst->owned != src->owned)
900 dst->owned = src->owned;
903 #ifdef MULTIPLE_OWNER
906 OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
909 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
912 dst->mom->mode = src->mom->mode;
916 #endif //MULTIPLE_OWNER
920 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
921 #ifdef MULTIPLE_OWNER
923 * Internal function to get number of sub-owner
925 static size_t GetSubOwnerSize()
927 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
929 size_t numberOfSubOwner = 0;
931 if (gDoxm && gDoxm->subOwners)
933 OicSecSubOwner_t* subowner = NULL;
934 LL_FOREACH(gDoxm->subOwners, subowner)
940 OIC_LOG_V(DEBUG, TAG, "Numer of registered sub-owner=%zd", numberOfSubOwner);
941 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
943 return numberOfSubOwner;
947 * Callback function to handle MOT DTLS handshake result.
948 * @param[out] endpoint remote device information.
949 * @param[out] errorInfo CA Error information.
951 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *endpoint,
952 const CAErrorInfo_t *errorInfo)
954 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
955 if (!endpoint || !errorInfo)
957 OIC_LOG(ERROR, TAG, "Invalid param");
963 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
967 if ((CA_STATUS_OK == errorInfo->result) && (true == gDoxm->owned)
968 && (OIC_PRECONFIG_PIN == gDoxm->oxmSel) && (NULL != gDoxm->mom)
969 && (OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode) && (CA_ADAPTER_TCP != endpoint->adapter))
971 OIC_LOG_V(INFO, TAG, "DTLS session established for sub-owner authentication : (%s:%d)",
972 endpoint->addr, endpoint->port);
974 const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(endpoint);
975 if (authenticatedSubOwnerInfo)
977 if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
978 authenticatedSubOwnerInfo->identity.id_length))
980 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
984 OicSecSubOwner_t* subOwnerInst = NULL;
985 LL_FOREACH(gDoxm->subOwners, subOwnerInst)
987 if(0 == memcmp(subOwnerInst->uuid.id,
988 authenticatedSubOwnerInfo->identity.id,
989 authenticatedSubOwnerInfo->identity.id_length))
995 if (NULL == subOwnerInst)
997 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
1000 char* strUuid = NULL;
1001 if (OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
1003 OIC_LOG(WARNING, TAG, "ConvertUuidToStr error");
1005 OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
1007 if (gMaxSubOwnerSize > GetSubOwnerSize())
1009 memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
1010 authenticatedSubOwnerInfo->identity.id_length);
1011 LL_APPEND(gDoxm->subOwners, subOwnerInst);
1012 if (!UpdatePersistentStorage(gDoxm))
1014 OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
1019 OIC_LOG_V(ERROR, TAG, "Number of sub-owner exceeded : (MAX SIZE=%zd)", gMaxSubOwnerSize);
1021 //Close DTLS session
1022 if (CA_STATUS_OK != CAcloseSslSession(endpoint))
1024 OIC_LOG_V(ERROR, TAG, "CAcloseSslSession error for [%s:%d]", endpoint->addr, endpoint->port);
1028 if (OC_STACK_RESOURCE_DELETED != RemoveCredential(&subOwnerInst->uuid))
1030 OIC_LOG_V(ERROR, TAG, "RemoveCredential error for [%s]", strUuid);
1033 // TODO: How to send error to client side?
1042 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
1044 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
1047 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1049 #endif //MULTIPLE_OWNER
1050 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1053 * Function to validate oxmsel with oxms.
1055 * @param[in] supportedMethods Array of supported methods
1056 * @param[in] numberOfMethods number of supported methods
1057 * @param[out] selectedMethod Selected methods
1058 * @return TRUE on success
1060 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
1061 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
1063 bool isValidOxmsel = false;
1065 OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
1066 if (numberOfMethods == 0 || !supportedMethods)
1068 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
1069 return isValidOxmsel;
1072 for (size_t i = 0; i < numberOfMethods; i++)
1074 if (*selectedMethod == supportedMethods[i])
1076 isValidOxmsel = true;
1082 OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
1083 return isValidOxmsel;
1086 OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
1088 return isValidOxmsel;
1091 void SetInformOxmSelCB(InformOxmSelectedCallback_t informOxmSelCB)
1093 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1094 g_InformOxmSelectedCallback = informOxmSelCB;
1095 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1098 void UnsetInformOxmSelCB()
1100 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1101 g_InformOxmSelectedCallback = NULL;
1102 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1105 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1106 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest);
1108 static void DestroyEntityHandlerRequest(OCEntityHandlerRequest * ehRequest)
1110 if (ehRequest == NULL) {
1111 OIC_LOG(WARNING, TAG, "ehRequest is NULL");
1115 OICFree(ehRequest->query);
1117 if (ehRequest->payload) {
1118 OICFree(((OCSecurityPayload *)ehRequest->payload)->securityData);
1119 OICFree(ehRequest->payload);
1125 void * WaitConfirm(OCEntityHandlerRequest * ehRequest)
1127 bool confirmResult = false, confirmState = false;
1129 oc_mutex_lock(g_mutexWait);
1130 oc_cond_wait(g_condWait, g_mutexWait);
1131 oc_cond_free(g_condWait);
1134 oc_mutex_unlock(g_mutexWait);
1135 oc_mutex_free(g_mutexWait);
1138 g_isConfirmResult = true;
1139 GetAsyncVerifyUserResult(&confirmResult, &confirmState);
1140 if (confirmResult == true)
1142 gConfirmState = CONFIRM_STATE_ACCEPTED;
1143 HandleDoxmPostRequest(ehRequest);
1144 g_isConfirmResult = false;
1149 gConfirmState = CONFIRM_STATE_DENIED;
1150 HandleDoxmPostRequest(ehRequest);
1151 g_isConfirmResult = false;
1155 DestroyEntityHandlerRequest(ehRequest);
1160 static OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
1162 OIC_LOG(INFO, TAG, "Copying received request for slow response");
1164 if (!entityHandlerRequest)
1166 OIC_LOG_V(ERROR, TAG, "%s: entityHandlerRequest is NULL", __func__);
1170 OCEntityHandlerRequest *copyOfRequest =
1171 (OCEntityHandlerRequest *)OICCalloc(1, sizeof(OCEntityHandlerRequest));
1174 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1178 memcpy(copyOfRequest, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
1180 if (entityHandlerRequest->query)
1182 copyOfRequest->query = OICStrdup(entityHandlerRequest->query);
1183 if(!copyOfRequest->query)
1185 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1186 OICFree(copyOfRequest);
1191 if (entityHandlerRequest->payload)
1193 copyOfRequest->payload =
1194 (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1195 if(!copyOfRequest->payload)
1197 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1198 OICFree(copyOfRequest->query);
1199 OICFree(copyOfRequest);
1203 if (((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize)
1205 ((OCSecurityPayload *)copyOfRequest->payload)->securityData =
1206 (uint8_t *)OICCalloc(1, ((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize);
1207 if(!((OCSecurityPayload *)copyOfRequest->payload)->securityData)
1209 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1210 OICFree(copyOfRequest->payload);
1211 OICFree(copyOfRequest->query);
1212 OICFree(copyOfRequest);
1216 memcpy(((OCSecurityPayload *)copyOfRequest->payload)->securityData,
1217 ((OCSecurityPayload *)entityHandlerRequest->payload)->securityData,
1218 ((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize);
1220 ((OCSecurityPayload *)(copyOfRequest->payload))->payloadSize =
1221 ((OCSecurityPayload *)(entityHandlerRequest->payload))->payloadSize;
1224 copyOfRequest->payload->type = entityHandlerRequest->payload->type;
1225 copyOfRequest->messageID = entityHandlerRequest->messageID;
1228 // Ignore vendor specific header options for example
1229 copyOfRequest->numRcvdVendorSpecificHeaderOptions = 0;
1230 copyOfRequest->rcvdVendorSpecificHeaderOptions = NULL;
1234 OIC_LOG(INFO, TAG, "Copied client request");
1238 OIC_LOG(ERROR, TAG, "Error copying client request");
1240 return copyOfRequest;
1242 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1244 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
1246 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
1247 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1248 OicUuid_t emptyOwner = {.id = {0} };
1249 static uint16_t previousMsgId = 0;
1250 bool isDuplicatedMsg = false;
1253 * Convert CBOR Doxm data into binary. This will also validate
1254 * the Doxm data received.
1256 OicSecDoxm_t *newDoxm = NULL;
1258 if (ehRequest->payload)
1260 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1261 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1262 bool roParsed = false;
1263 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1264 if (newDoxm && OC_STACK_OK == res)
1267 * message ID is supported for CoAP over UDP only according to RFC 7252
1268 * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1269 * In case of other transport adapter, duplicate message check is not required.
1271 if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1272 previousMsgId == ehRequest->messageID && g_isConfirmResult == false)
1274 isDuplicatedMsg = true;
1277 if (isDuplicatedMsg && ehRequest->messageID == gConfirmMsgId)
1279 if (CONFIRM_STATE_WAIT == gConfirmState)
1281 OIC_LOG(DEBUG, TAG, "Confirm callback already invoked.");
1282 OIC_LOG(DEBUG, TAG, "This request will be ignored.");
1283 DeleteDoxmBinData(newDoxm);
1288 OIC_LOG_V(DEBUG, TAG, "Confirm request already done, Confirm Result = %s", (CONFIRM_STATE_ACCEPTED == gConfirmState ? "ACCEPTED" : "DENIED"));
1289 ehRet = (CONFIRM_STATE_ACCEPTED == gConfirmState ? OC_EH_OK : OC_EH_NOT_ACCEPTABLE);
1294 // Check request on RO property
1295 if (true == roParsed)
1297 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1298 ehRet = OC_EH_NOT_ACCEPTABLE;
1302 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
1305 if (true == gDoxm->owned)
1307 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1309 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1310 ehRet = OC_EH_NOT_ACCEPTABLE;
1314 if(0 != memcmp(&gDoxm->owner.id, &newDoxm->owner.id, sizeof(gDoxm->owner.id)))
1316 OIC_LOG(ERROR, TAG, "Not acceptable request for owned property");
1317 ehRet = OC_EH_NOT_ACCEPTABLE;
1320 //Update gDoxm based on newDoxm
1321 updateWriteableProperty(newDoxm, gDoxm);
1323 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1324 #ifdef MULTIPLE_OWNER
1328 if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1330 CAResult_t caRes = CA_STATUS_FAILED;
1331 if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1333 caRes = CAEnableAnonECDHCipherSuite(false);
1334 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1335 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1337 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, ehRequest->devAddr.adapter);
1338 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1339 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1341 //Set the device id to derive temporal PSK
1342 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1346 OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1349 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1353 //if MOM is disabled, revert the DTLS handshake callback
1354 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1356 OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1361 if(newDoxm->subOwners)
1363 OicSecSubOwner_t* subowner = NULL;
1364 OicSecSubOwner_t* temp = NULL;
1366 OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1368 if(gDoxm->subOwners)
1370 LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1372 LL_DELETE(gDoxm->subOwners, subowner);
1379 LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1381 LL_DELETE(newDoxm->subOwners, subowner);
1382 LL_APPEND(gDoxm->subOwners, subowner);
1385 #endif //MULTIPLE_OWNER
1386 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1388 //Update new state in persistent storage
1389 if (UpdatePersistentStorage(gDoxm) == true)
1395 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1396 ehRet = OC_EH_ERROR;
1402 if ((false == gDoxm->owned) && (false == newDoxm->owned))
1404 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1406 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1407 ehRet = OC_EH_NOT_ACCEPTABLE;
1410 if (g_InformOxmSelectedCallback)
1412 g_InformOxmSelectedCallback(newDoxm->oxmSel);
1415 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1416 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1418 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1419 NULL, OIC_OTM_STARTED);
1423 OIC_LOG_V(INFO, TAG, "%s: request owner not empty",__func__);
1424 char* strUuid = NULL;
1425 if (OC_STACK_OK == ConvertUuidToStr(&newDoxm->owner, &strUuid))
1427 OIC_LOG_V(INFO, TAG, "%s: request owner: %s",__func__, strUuid);
1433 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1436 * If current state of the device is un-owned, enable
1437 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1438 * tool can initiate JUST_WORKS ownership transfer process.
1440 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1442 gDoxm->oxmSel = newDoxm->oxmSel;
1443 //Update new state in persistent storage
1444 if ((UpdatePersistentStorage(gDoxm) == true))
1450 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1451 ehRet = OC_EH_ERROR;
1454 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
1455 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1456 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1457 #endif // __WITH_DTLS__ or __WITH_TLS__
1462 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1463 //Save the owner's UUID to derive owner credential
1464 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1466 // Update new state in persistent storage
1467 if (true == UpdatePersistentStorage(gDoxm))
1473 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1474 ehRet = OC_EH_ERROR;
1479 * Disable anonymous ECDH cipher in tinyDTLS since device is now
1482 CAResult_t caRes = CA_STATUS_OK;
1483 caRes = CAEnableAnonECDHCipherSuite(false);
1484 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1485 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1487 //In case of Mutual Verified Just-Works, verify mutualVerifNum
1488 if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1489 false == isDuplicatedMsg)
1491 uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1492 uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1493 OicUuid_t deviceID = {.id = {0}};
1495 //Generate mutualVerifNum
1496 OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1498 char label[LABEL_LEN] = {0};
1499 snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1500 if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1502 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1503 ehRet = OC_EH_ERROR;
1508 CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1511 gDoxm->owner.id, sizeof(gDoxm->owner.id),
1512 gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1513 preMutualVerifNum, OWNER_PSK_LENGTH_128);
1514 if (CA_STATUS_OK != pskRet)
1516 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1517 ehRet = OC_EH_ERROR;
1522 memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1523 sizeof(mutualVerifNum));
1525 gConfirmMsgId = ehRequest->messageID;
1526 gConfirmState = CONFIRM_STATE_WAIT;
1527 //Wait for user confirmation
1528 if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1530 ehRet = OC_EH_NOT_ACCEPTABLE;
1531 gConfirmState = CONFIRM_STATE_DENIED;
1536 gConfirmState = CONFIRM_STATE_ACCEPTED;
1540 #endif // __WITH_DTLS__ or __WITH_TLS__
1543 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1546 * If current state of the device is un-owned, enable
1547 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1548 * tool can initiate JUST_WORKS ownership transfer process.
1550 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1552 gDoxm->oxmSel = newDoxm->oxmSel;
1553 //Update new state in persistent storage
1554 if ((UpdatePersistentStorage(gDoxm) == true))
1560 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1561 ehRet = OC_EH_ERROR;
1564 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1565 CAResult_t caRes = CA_STATUS_OK;
1567 caRes = CAEnableAnonECDHCipherSuite(false);
1568 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1569 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1571 caRes = CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
1572 ehRequest->devAddr.adapter);
1573 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1575 if (!isDuplicatedMsg)
1577 char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1578 if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1580 //Set the device id to derive temporal PSK
1581 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1584 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1585 * Credential should not be saved into SVR.
1586 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1588 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1589 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1594 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1595 ehRet = OC_EH_ERROR;
1598 #endif // __WITH_DTLS__ or __WITH_TLS__
1600 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1603 //Save the owner's UUID to derive owner credential
1604 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1606 // In case of random-pin based OTM, close the PIN display if callback is registered.
1607 if (!isDuplicatedMsg)
1612 //Update new state in persistent storage
1613 if (UpdatePersistentStorage(gDoxm) == true)
1619 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1620 ehRet = OC_EH_ERROR;
1623 #endif // __WITH_DTLS__ or __WITH_TLS__
1625 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1626 else if (OIC_MANUFACTURER_CERTIFICATE == newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1628 if (CONFIRM_STATE_ACCEPTED != gConfirmState && CONFIRM_STATE_DENIED != gConfirmState)
1630 //Get user confirmation
1631 if (false == newDoxm->owned &&
1632 false == isDuplicatedMsg &&
1633 memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1635 gConfirmMsgId = ehRequest->messageID;
1636 gConfirmState = CONFIRM_STATE_WAIT;
1638 if (OC_STACK_OK != VerifyUserConfirm())
1640 if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1642 ehRet = OC_EH_NOT_ACCEPTABLE;
1643 gConfirmState = CONFIRM_STATE_DENIED;
1649 OCEntityHandlerRequest * ehRequestCopy = CopyRequest(ehRequest);
1650 VERIFY_NON_NULL(TAG, ehRequestCopy, ERROR);
1652 g_condWait = oc_cond_new();
1653 g_mutexWait = oc_mutex_new();
1654 if (oc_thread_new (&g_waitConfirmThreadId, WaitConfirm, ehRequestCopy))
1656 oc_thread_detach(g_waitConfirmThreadId);
1659 previousMsgId = ehRequest->messageID;
1665 else if (CONFIRM_STATE_DENIED == gConfirmState)
1667 ehRet = OC_EH_NOT_ACCEPTABLE;
1671 //Save the owner's UUID to derive owner credential
1672 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1673 gDoxm->oxmSel = newDoxm->oxmSel;
1674 //Update new state in persistent storage
1675 if (UpdatePersistentStorage(gDoxm))
1681 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1682 ehRet = OC_EH_ERROR;
1684 CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1685 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1686 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1688 //Unset pre-selected ciphersuite, if any
1689 caRes = CASelectCipherSuite(0, ehRequest->devAddr.adapter);
1690 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1691 OIC_LOG(DEBUG, TAG, "No ciphersuite preferred");
1693 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1694 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1696 #endif // __WITH_DTLS__ or __WITH_TLS__
1700 * When current state of the device is un-owned and Provisioning
1701 * Tool is attempting to change the state to 'Owned' with a
1702 * qualified value for the field 'Owner'
1704 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1705 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1707 //Change the SVR's resource owner as owner device.
1708 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1709 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1711 ehRet = OC_EH_ERROR;
1714 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1715 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1717 ehRet = OC_EH_ERROR;
1720 ownerRes = SetCredRownerId(&gDoxm->owner);
1721 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1723 ehRet = OC_EH_ERROR;
1726 ownerRes = SetPstatRownerId(&gDoxm->owner);
1727 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1729 ehRet = OC_EH_ERROR;
1733 gDoxm->owned = true;
1734 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1736 // Update new state in persistent storage
1737 if (UpdatePersistentStorage(gDoxm))
1739 //Update default ACE of security resource to prevent anonymous user access.
1740 if(OC_STACK_OK == UpdateDefaultSecProvACE())
1746 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1747 ehRet = OC_EH_ERROR;
1752 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1753 ehRet = OC_EH_ERROR;
1755 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1756 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1757 OIC_CON_MFG_CERT== gDoxm->oxmSel)
1759 CAregisterPkixInfoHandler(GetPkixInfo);
1760 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1763 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1764 &gDoxm->owner, OIC_OTM_DONE);
1765 #endif // __WITH_DTLS__ or __WITH_TLS__
1771 if(OC_EH_OK != ehRet)
1774 * If some error is occured while ownership transfer,
1775 * ownership transfer related resource should be revert back to initial status.
1781 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1783 if (!isDuplicatedMsg)
1785 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1786 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1787 NULL, OIC_OTM_ERROR);
1789 RestoreDoxmToInitState();
1790 RestorePstatToInitState();
1791 OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1797 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1801 previousMsgId = ehRequest->messageID;
1803 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1804 CAEndpoint_t peer = {0};
1805 OCDevAddr devAddr = ehRequest->devAddr;
1807 memcpy(&peer.addr, &devAddr.addr, sizeof(peer.addr));
1808 peer.port = devAddr.port;
1809 peer.adapter = (CATransportAdapter_t)devAddr.adapter;
1811 if ((devAddr.flags & OC_FLAG_SECURE) && (false == CAIsExistSslPeer(&peer)))
1813 OIC_LOG_V(WARNING, TAG, "Not Exist Peer");
1818 //Send payload to request originator
1819 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1820 OC_EH_OK : OC_EH_ERROR;
1823 //Send payload to request originator
1824 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1825 OC_EH_OK : OC_EH_ERROR;
1828 DeleteDoxmBinData(newDoxm);
1833 #ifdef MULTIPLE_OWNER
1834 static OCEntityHandlerResult HandleDoxmDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1836 OIC_LOG(DEBUG, TAG, "Processing DoxmDeleteRequest");
1838 OCEntityHandlerResult ehRet = OC_EH_BAD_REQ;
1840 if (NULL == ehRequest->query)
1845 OicParseQueryIter_t parseIter = { .attrPos=NULL };
1846 OicUuid_t subject = {.id={0}};
1848 //Parsing REST query to get the subject
1849 ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1850 while (GetNextQuery(&parseIter))
1852 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBOWNERID_NAME,
1853 parseIter.attrLen) == 0)
1855 if (0 == strncmp((const char*)parseIter.valPos, WILDCARD_RESOURCE_URI,
1856 strlen(WILDCARD_RESOURCE_URI)))
1858 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&WILDCARD_SUBJECT_ID))
1860 ehRet = OC_EH_RESOURCE_DELETED;
1865 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
1866 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1868 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&subject))
1870 ehRet = OC_EH_RESOURCE_DELETED;
1876 //Send response to request originator
1877 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1878 OC_EH_OK : OC_EH_ERROR;
1884 #endif //MULTIPLE_OWNER
1886 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1887 OCEntityHandlerRequest * ehRequest,
1888 void* callbackParam)
1890 (void)callbackParam;
1891 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1893 if(NULL == ehRequest)
1898 oc_mutex_lock(g_mutexDoxm);
1902 oc_mutex_unlock(g_mutexDoxm);
1903 return OC_EH_SERVICE_UNAVAILABLE;
1906 if (flag & OC_REQUEST_FLAG)
1908 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1910 switch (ehRequest->method)
1913 ehRet = HandleDoxmGetRequest(ehRequest);
1917 ehRet = HandleDoxmPostRequest(ehRequest);
1920 #ifdef MULTIPLE_OWNER
1921 case OC_REST_DELETE:
1922 ehRet = HandleDoxmDeleteRequest(ehRequest);
1924 #endif //MULTIPLE_OWNER
1927 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1928 OC_EH_OK : OC_EH_ERROR;
1932 oc_mutex_unlock(g_mutexDoxm);
1938 OCStackResult CreateDoxmResource()
1940 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1941 OIC_RSRC_TYPE_SEC_DOXM,
1942 OC_RSRVD_INTERFACE_DEFAULT,
1949 if (OC_STACK_OK != ret)
1951 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1952 DeInitDoxmResource();
1958 * Checks if DeviceID is generated during provisioning for the new device.
1959 * If DeviceID is NULL then generates the new DeviceID.
1960 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1962 static OCStackResult CheckDeviceID()
1964 OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
1966 OCStackResult ret = OC_STACK_ERROR;
1967 bool validId = false;
1971 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
1972 return OC_STACK_INVALID_PARAM;
1975 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1977 if (gDoxm->deviceID.id[i] != 0)
1986 char* strUuid = NULL;
1987 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1988 //If seed value is exist, generate UUID using seed with SHA256
1989 if (0 != gUuidSeedSize)
1991 uint8_t hashVal[MBEDTLS_MD_MAX_SIZE] = {0};
1992 mbedtls_md_context_t sha_ctx;
1995 OIC_LOG(DEBUG, TAG, "UUID will be generated using seed w/ SHA256");
1996 OIC_LOG(DEBUG, TAG, "Seed value : ");
1997 OIC_LOG_BUFFER(DEBUG, TAG, gUuidSeed, gUuidSeedSize);
1999 mbedtls_md_init( &sha_ctx );
2000 mbedret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
2003 mbedtls_md_starts( &sha_ctx );
2004 mbedtls_md_update( &sha_ctx, gUuidSeed, gUuidSeedSize);
2005 mbedtls_md_finish(&sha_ctx, (unsigned char*)hashVal);
2006 memcpy(gDoxm->deviceID.id, hashVal, sizeof(gDoxm->deviceID.id));
2011 OIC_LOG_V(ERROR, TAG, "mbedtls_md_setup() returned -0x%04x\n", -mbedret);
2012 ret = OC_STACK_ERROR;
2014 mbedtls_md_free( &sha_ctx );
2018 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
2020 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
2021 return OC_STACK_ERROR;
2026 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
2028 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
2034 if (OC_STACK_OK == ConvertUuidToStr(&gDoxm->deviceID, &strUuid))
2036 OIC_LOG_V(DEBUG, TAG, "Generated device UUID is [%s]", strUuid);
2041 OIC_LOG(WARNING, TAG, "Failed to convert UUID to string");
2045 if (!UpdatePersistentStorage(gDoxm))
2047 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
2048 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
2056 OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
2062 * Get the default value.
2064 * @return the default value of doxm, @ref OicSecDoxm_t.
2066 static OicSecDoxm_t* GetDoxmDefault()
2068 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
2069 return &gDefaultDoxm;
2072 const OicSecDoxm_t* GetDoxmResourceData()
2077 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2079 * Internal API to prepare MOT
2081 static void PrepareMOT(const OicSecDoxm_t* doxm)
2083 OIC_LOG(INFO, TAG, "IN PrepareMOT");
2084 VERIFY_NON_NULL(TAG, doxm, ERROR);
2086 if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
2088 CAResult_t caRes = CA_STATUS_FAILED;
2090 OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
2092 if(OIC_PRECONFIG_PIN == doxm->oxmSel)
2094 caRes = CAEnableAnonECDHCipherSuite(false);
2095 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2096 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
2098 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP);
2099 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2101 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_TCP);
2102 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2104 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
2106 //Set the device id to derive temporal PSK
2107 SetUuidForPinBasedOxm(&doxm->deviceID);
2111 OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
2115 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
2118 OIC_LOG(INFO, TAG, "OUT PrepareMOT");
2121 OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
2123 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2125 OCStackResult InitDoxmResource()
2127 OCStackResult ret = OC_STACK_ERROR;
2131 g_mutexDoxm = oc_mutex_new();
2134 return OC_STACK_ERROR;
2138 gConfirmState = CONFIRM_STATE_READY;
2141 //Read DOXM resource from PS
2142 uint8_t *data = NULL;
2144 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
2145 // If database read failed
2146 if (OC_STACK_OK != ret)
2148 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
2152 // Read DOXM resource from PS
2153 ret = CBORPayloadToDoxm(data, size, &gDoxm);
2156 * If SVR database in persistent storage got corrupted or
2157 * is not available for some reason, a default doxm is created
2158 * which allows user to initiate doxm provisioning again.
2160 if ((OC_STACK_OK != ret) || !data || !gDoxm)
2162 gDoxm = GetDoxmDefault();
2165 oc_mutex_lock(g_mutexDoxm);
2166 g_isDoxmNull = false;
2167 oc_mutex_unlock(g_mutexDoxm);
2169 //In case of the server is shut down unintentionally, we should initialize the owner
2170 if(gDoxm && (false == gDoxm->owned))
2172 OicUuid_t emptyUuid = {.id={0}};
2173 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
2174 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
2175 InvokeOtmEventHandler(NULL, 0, NULL, OIC_OTM_READY);
2179 ret = CheckDeviceID();
2180 if (ret == OC_STACK_OK)
2182 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
2183 //Instantiate 'oic.sec.doxm'
2184 ret = CreateDoxmResource();
2188 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
2192 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2193 //if MOT is enabled, MOT should be prepared.
2194 if(gDoxm && gDoxm->owned)
2198 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2203 OCStackResult DeInitDoxmResource()
2205 oc_mutex_lock(g_mutexDoxm);
2206 OCStackResult ret = OCDeleteResource(gDoxmHandle);
2207 if (gDoxm != &gDefaultDoxm)
2209 DeleteDoxmBinData(gDoxm);
2212 g_isDoxmNull = true;
2214 if (OC_STACK_OK == ret)
2216 oc_mutex_unlock(g_mutexDoxm);
2221 oc_mutex_unlock(g_mutexDoxm);
2222 return OC_STACK_ERROR;
2226 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
2228 if (deviceID && gDoxm)
2230 *deviceID = gDoxm->deviceID;
2233 return OC_STACK_ERROR;
2236 OCStackResult GetDoxmIsOwned(bool *isOwned)
2238 if (isOwned && gDoxm)
2240 *isOwned = gDoxm->owned;
2243 return OC_STACK_ERROR;
2246 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2247 OCStackResult SetDoxmDeviceIDSeed(const uint8_t* seed, size_t seedSize)
2249 OIC_LOG_V(INFO, TAG, "In %s", __func__);
2253 return OC_STACK_INVALID_PARAM;
2255 if (MAX_UUID_SEED_SIZE < seedSize)
2257 OIC_LOG_V(ERROR, TAG, "Seed size is too long (MAX size is %d bytes)", MAX_UUID_SEED_SIZE);
2258 return OC_STACK_INVALID_PARAM;
2260 if (MIN_UUID_SEED_SIZE > seedSize)
2262 OIC_LOG_V(ERROR, TAG, "Seed size is too small (MIN size is %d bytes)", MIN_UUID_SEED_SIZE);
2263 return OC_STACK_INVALID_PARAM;
2266 memset(gUuidSeed, 0x00, sizeof(gUuidSeed));
2267 memcpy(gUuidSeed, seed, seedSize);
2268 gUuidSeedSize = seedSize;
2270 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2277 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
2279 bool isOwnerUpdated = false;
2280 bool isRownerUpdated = false;
2281 if (NULL == deviceID)
2283 return OC_STACK_INVALID_PARAM;
2287 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
2288 return OC_STACK_NO_RESOURCE;
2291 #ifdef __WITH_DTLS__
2292 //for normal device.
2293 if (true == gDoxm->owned
2294 && memcmp(gEmptyUuid, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0
2295 && memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
2297 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
2298 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
2299 return OC_STACK_ERROR;
2301 #endif //__WITH_DTLS
2303 //Save the previous UUID
2305 memcpy(prevUuid.id, gDoxm->deviceID.id, sizeof(prevUuid.id));
2307 //Change the device UUID
2308 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
2310 //Change the owner ID if necessary
2311 if (memcmp(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2313 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
2314 isOwnerUpdated = true;
2316 //Change the resource owner ID if necessary
2317 if (memcmp(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2319 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
2320 isRownerUpdated = true;
2322 // TODO: T.B.D Change resource owner for pstat, acl and cred
2325 if (!UpdatePersistentStorage(gDoxm))
2327 //revert UUID in case of PSI error
2328 memcpy(gDoxm->deviceID.id, prevUuid.id, sizeof(prevUuid.id));
2331 memcpy(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id));
2333 if (isRownerUpdated)
2335 memcpy(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id));
2337 // TODO: T.B.D Revert resource owner for pstat, acl and cred
2339 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
2340 return OC_STACK_ERROR;
2345 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
2347 OCStackResult retVal = OC_STACK_ERROR;
2350 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
2354 *devownerid = gDoxm->owner;
2355 retVal = OC_STACK_OK;
2361 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
2363 OCStackResult retVal = OC_STACK_ERROR;
2368 *rowneruuid = gDoxm->rownerID;
2369 retVal = OC_STACK_OK;
2375 #ifdef MULTIPLE_OWNER
2377 * Compare the UUID to SubOwner.
2379 * @param[in] uuid device UUID
2381 * @return true if context->subjectId exist subowner list, else false.
2383 bool IsSubOwner(const OicUuid_t* uuid)
2385 bool retVal = false;
2392 if (gDoxm && gDoxm->subOwners)
2394 if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
2399 OicSecSubOwner_t* subOwner = NULL;
2400 LL_FOREACH(gDoxm->subOwners, subOwner)
2402 if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
2410 #endif //MULTIPLE_OWNER
2412 OCStackResult SetMOTStatus(bool enable)
2414 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2415 #ifdef MULTIPLE_OWNER
2416 OCStackResult ret = OC_STACK_NO_MEMORY;
2417 uint8_t *cborPayload = NULL;
2419 bool isDeallocateRequired = false;
2421 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
2423 if (NULL == gDoxm->mom && !enable)
2425 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2429 if (NULL == gDoxm->mom)
2431 gDoxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
2432 VERIFY_NON_NULL(TAG, gDoxm->mom, ERROR);
2433 isDeallocateRequired = true;
2436 gDoxm->mom->mode = (enable ? OIC_MULTIPLE_OWNER_ENABLE : OIC_MULTIPLE_OWNER_DISABLE);
2437 gDoxm->oxmSel = OIC_PRECONFIG_PIN;
2439 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2440 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2442 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2443 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2445 isDeallocateRequired = false;
2448 if (isDeallocateRequired)
2450 OICFree(gDoxm->mom);
2454 OICFree(cborPayload);
2456 OIC_LOG_V(DEBUG, TAG, "Out %s : %d", __func__, ret);
2460 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2461 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2462 return OC_STACK_ERROR;
2463 #endif //MULTIPLE_OWNER
2466 OCStackResult RemoveSubOwner(const OicUuid_t* subOwner)
2468 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2469 #ifdef MULTIPLE_OWNER
2470 OCStackResult ret = OC_STACK_ERROR;
2471 bool isDeleted = false;
2473 if (NULL == subOwner)
2475 OIC_LOG(ERROR, TAG, "Invalid sub owner UUID.");
2476 return OC_STACK_INVALID_PARAM;
2480 OIC_LOG(ERROR, TAG, "Doxm resource is NULL");
2481 return OC_STACK_NO_RESOURCE;
2483 if ( NULL == gDoxm->subOwners)
2485 OIC_LOG(WARNING, TAG, "Sub Owner list is empty.");
2486 return OC_STACK_ERROR;
2489 OicSecSubOwner_t* curSubOwner = NULL;
2490 OicSecSubOwner_t* tempSubOwner = NULL;
2491 LL_FOREACH_SAFE(gDoxm->subOwners, curSubOwner, tempSubOwner)
2493 if (memcmp(curSubOwner->uuid.id, subOwner->id, sizeof(subOwner->id)) == 0 ||
2494 memcmp(WILDCARD_SUBJECT_ID.id, subOwner->id, sizeof(OicUuid_t)) == 0)
2496 char* strUuid = NULL;
2497 ret = ConvertUuidToStr(&curSubOwner->uuid, &strUuid);
2498 if (OC_STACK_OK != ret)
2500 OIC_LOG_V(ERROR, TAG, "ConvertUuidToStr error : %d", ret);
2504 OIC_LOG_V(INFO, TAG, "[%s] will be removed from sub owner list.", strUuid);
2505 LL_DELETE(gDoxm->subOwners, curSubOwner);
2507 //Remove the cred for sub owner
2508 ret = RemoveCredential(&curSubOwner->uuid);
2509 if (OC_STACK_RESOURCE_DELETED != ret)
2511 OIC_LOG_V(WARNING, TAG, "RemoveCredential error for [%s] : %d", strUuid, ret);
2515 // TODO: Remove the ACL for sub owner (Currently ACL is not required for sub-owner)
2525 //Update persistent storage
2526 if (UpdatePersistentStorage(gDoxm))
2528 ret = OC_STACK_RESOURCE_DELETED;
2532 OIC_LOG(ERROR, TAG, "UpdatePersistentStorage error");
2533 ret = OC_STACK_ERROR;
2537 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2540 OC_UNUSED(subOwner);
2541 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2542 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2543 return OC_STACK_ERROR;
2544 #endif //MULTIPLE_OWNER
2548 OCStackResult SetNumberOfSubOwner(size_t numOfSubOwner)
2550 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2551 #ifdef MULTIPLE_OWNER
2552 if (MAX_SUBOWNER_SIZE < numOfSubOwner || MIN_SUBOWNER_SIZE > numOfSubOwner)
2554 OIC_LOG_V(ERROR, TAG, "Invalid number of sub owner : %zd", numOfSubOwner);
2555 return OC_STACK_INVALID_PARAM;
2557 gMaxSubOwnerSize = numOfSubOwner;
2558 OIC_LOG_V(DEBUG, TAG, "Number of SubOwner = %zd", gMaxSubOwnerSize);
2559 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2562 OC_UNUSED(numOfSubOwner);
2563 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2564 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2565 return OC_STACK_ERROR;
2566 #endif //MULTIPLE_OWNER
2570 * Function to restore doxm resurce to initial status.
2571 * This function will use in case of error while ownership transfer
2573 void RestoreDoxmToInitState()
2576 gConfirmState = CONFIRM_STATE_READY;
2581 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
2583 OicUuid_t emptyUuid = {.id={0}};
2584 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
2585 gDoxm->owned = false;
2586 gDoxm->oxmSel = OIC_JUST_WORKS;
2588 if(!UpdatePersistentStorage(gDoxm))
2590 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
2595 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
2597 OCStackResult ret = OC_STACK_ERROR;
2598 uint8_t *cborPayload = NULL;
2603 ret = OC_STACK_NO_RESOURCE;
2607 if( newROwner && (false == gDoxm->owned) )
2609 gDoxm->owned = true;
2610 memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
2611 memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
2613 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2614 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2616 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2617 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2619 OICFree(cborPayload);
2625 OICFree(cborPayload);