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"
52 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
53 #include "pkix_interface.h"
54 #include "ca_adapter_net_ssl.h"
57 #define TAG "OIC_SRM_DOXM"
58 #define CHAR_ZERO ('0')
60 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
61 * The value of payload size is increased until reaching belox max cbor size. */
62 static const uint16_t CBOR_SIZE = 512;
64 /** Max cbor size payload. */
65 static const uint16_t CBOR_MAX_SIZE = 4400;
67 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
68 /** MAX uuid seed size */
69 #define MAX_UUID_SEED_SIZE (64)
70 /** MIN uuid seed size */
71 #define MIN_UUID_SEED_SIZE (8)
73 /** Buffer to save the seed of device UUID */
74 static uint8_t gUuidSeed[MAX_UUID_SEED_SIZE];
75 static size_t gUuidSeedSize = 0;
79 #define MAX_SUBOWNER_SIZE (64)
80 #define MIN_SUBOWNER_SIZE (1)
81 #define DEFAULT_SUBOWNER_SIZE (32)
83 static size_t gMaxSubOwnerSize = DEFAULT_SUBOWNER_SIZE;
86 typedef enum ConfirmState{
87 CONFIRM_STATE_READY = 0,
88 CONFIRM_STATE_WAIT = 1,
89 CONFIRM_STATE_ACCEPTED = 2,
90 CONFIRM_STATE_DENIED = 3
93 static OicSecDoxm_t *gDoxm = NULL;
94 static OCResourceHandle gDoxmHandle = NULL;
96 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
97 static OicSecDoxm_t gDefaultDoxm =
99 NULL, /* OicUrn_t *oxmType */
100 0, /* size_t oxmTypeLen */
101 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
102 1, /* size_t oxmLen */
103 OIC_JUST_WORKS, /* uint16_t oxmSel */
104 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
105 false, /* bool owned */
106 {.id = {0}}, /* OicUuid_t deviceID */
107 false, /* bool dpc */
108 {.id = {0}}, /* OicUuid_t owner */
109 #ifdef MULTIPLE_OWNER
110 NULL, /* OicSecSubOwner_t sub-owner list */
111 NULL, /* OicSecMomType_t multiple owner mode */
112 #endif //MULTIPLE_OWNER
113 {.id = {0}}, /* OicUuid_t rownerID */
116 static uint16_t gConfirmMsgId = 0;
117 static ConfirmState_t gConfirmState = CONFIRM_STATE_READY;
121 * This method is internal method.
122 * the param roParsed is optionally used to know whether cborPayload has
123 * at least read only property value or not.
125 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
126 OicSecDoxm_t **doxm, bool *roParsed);
128 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
133 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
135 OICFree(doxm->oxmType[i]);
137 OICFree(doxm->oxmType);
142 #ifdef MULTIPLE_OWNER
146 //clean sub-owner list
147 if(NULL != doxm->subOwners)
149 OicSecSubOwner_t* subowner = NULL;
150 OicSecSubOwner_t* temp = NULL;
151 LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
153 LL_DELETE(doxm->subOwners, subowner);
157 #endif //MULTIPLE_OWNER
164 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
167 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
169 return OC_STACK_INVALID_PARAM;
171 size_t cborLen = *size;
179 OCStackResult ret = OC_STACK_ERROR;
183 char* strUuid = NULL;
185 int64_t cborEncoderResult = CborNoError;
187 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
188 VERIFY_NON_NULL(TAG, outPayload, ERROR);
189 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
191 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
192 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
194 //OxmType -- Not Mandatory
195 if (doxm->oxmTypeLen > 0)
198 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
199 strlen(OIC_JSON_OXM_TYPE_NAME));
200 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
201 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
202 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
204 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
206 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
207 strlen(doxm->oxmType[i]));
208 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
210 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
211 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
214 //Oxm -- Not Mandatory
215 if (doxm->oxmLen > 0 && false == rwOnly)
218 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
219 strlen(OIC_JSON_OXMS_NAME));
220 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
221 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
222 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
224 for (size_t i = 0; i < doxm->oxmLen; i++)
226 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
227 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
229 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
230 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
233 //OxmSel -- Mandatory
234 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
235 strlen(OIC_JSON_OXM_SEL_NAME));
236 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
237 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
238 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
243 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
244 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
245 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
246 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
247 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
251 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
252 strlen(OIC_JSON_OWNED_NAME));
253 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
254 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
255 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
259 //DeviceId -- Mandatory
260 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
261 strlen(OIC_JSON_DEVICE_ID_NAME));
262 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
263 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
264 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
265 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
266 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
271 #ifdef MULTIPLE_OWNER
272 //Device SubOwnerID -- Not Mandatory
275 size_t subOwnerLen = 0;
276 OicSecSubOwner_t* subOwner = NULL;
277 LL_FOREACH(doxm->subOwners, subOwner)
282 CborEncoder subOwners;
283 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
284 strlen(OIC_JSON_SUBOWNERID_NAME));
285 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
286 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
287 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
290 LL_FOREACH(doxm->subOwners, subOwner)
292 char* strUuid = NULL;
293 ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
294 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
295 cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
297 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
299 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
300 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
303 //Multiple Owner Mode -- Not Mandatory
306 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
307 strlen(OIC_JSON_MOM_NAME));
308 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
309 cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
310 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
312 #endif //MULTIPLE_OWNER
314 //devownerid -- Mandatory
315 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
316 strlen(OIC_JSON_DEVOWNERID_NAME));
317 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
318 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
319 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
320 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
321 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
325 //ROwner -- Mandatory
326 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
327 strlen(OIC_JSON_ROWNERID_NAME));
328 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
329 ret = ConvertUuidToStr(&doxm->rownerID, &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 ROwner Id Value.");
338 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
339 strlen(OIC_JSON_RT_NAME));
340 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
341 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
342 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
343 for (size_t i = 0; i < 1; i++)
345 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
346 strlen(OIC_RSRC_TYPE_SEC_DOXM));
347 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
349 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
350 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
354 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
355 strlen(OIC_JSON_IF_NAME));
356 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
357 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
358 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
359 for (size_t i = 0; i < 1; i++)
361 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
362 strlen(OC_RSRVD_INTERFACE_DEFAULT));
363 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
365 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
366 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
368 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
369 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
371 if (CborNoError == cborEncoderResult)
373 *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
374 *payload = outPayload;
378 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
380 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
381 // reallocate and try again!
384 // Since the allocated initial memory failed, double the memory.
385 cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
386 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
387 cborEncoderResult = CborNoError;
388 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
392 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
398 ret = OC_STACK_ERROR;
404 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
405 OicSecDoxm_t **secDoxm)
407 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
410 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
411 OicSecDoxm_t **secDoxm, bool *roParsed)
413 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
415 return OC_STACK_INVALID_PARAM;
418 OCStackResult ret = OC_STACK_ERROR;
422 CborError cborFindResult = CborNoError;
423 char* strUuid = NULL;
427 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
429 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
430 VERIFY_NON_NULL(TAG, doxm, ERROR);
432 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
433 //OxmType -- not Mandatory
434 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
438 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
439 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
440 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
442 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
443 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
445 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
446 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
450 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
452 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
454 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
455 cborFindResult = cbor_value_advance(&oxmType);
456 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
460 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
461 //Oxm -- not Mandatory
462 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
465 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
466 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
467 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
469 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
470 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
472 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
473 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
476 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
480 cborFindResult = cbor_value_get_int(&oxm, &tmp);
481 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
482 doxm->oxm[i++] = (OicSecOxm_t)tmp;
483 cborFindResult = cbor_value_advance(&oxm);
484 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
494 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
495 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
496 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
497 doxm->oxmLen = gDoxm->oxmLen;
498 for (size_t i = 0; i < gDoxm->oxmLen; i++)
500 doxm->oxm[i] = gDoxm->oxm[i];
504 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
505 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
509 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
510 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
511 doxm->oxmSel = (OicSecOxm_t)oxmSel;
513 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
515 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
516 doxm->oxmSel = gDoxm->oxmSel;
519 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
520 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
524 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
525 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
526 doxm->sct = (OicSecCredType_t)sct;
533 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
535 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
536 doxm->sct = gDoxm->sct;
539 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
540 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
542 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
543 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
545 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
547 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
548 doxm->owned = gDoxm->owned;
551 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
552 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
554 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
555 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
556 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
557 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
563 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
564 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
567 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
568 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
570 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
571 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
572 ret = ConvertStrToUuid(strUuid , &doxm->owner);
573 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
579 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
580 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
583 #ifdef MULTIPLE_OWNER
584 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
585 if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
588 cborFindResult = cbor_value_get_int(&doxmMap, &mode);
589 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
590 if(NULL == doxm->mom)
592 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
593 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
595 doxm->mom->mode = (OicSecMomType_t)mode;
597 else if(NULL != gDoxm && NULL != gDoxm->mom)
599 // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
600 if(NULL == doxm->mom)
602 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
603 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
605 doxm->mom->mode = gDoxm->mom->mode;
608 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
609 if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
611 size_t subOwnerLen = 0;
612 CborValue subOwnerCbor;
613 cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
614 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
615 VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
617 cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
618 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
620 while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
622 OCStackResult convertRes = OC_STACK_ERROR;
623 OicSecSubOwner_t* subOwner = NULL;
624 char* strUuid = NULL;
627 cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
628 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
630 subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
631 VERIFY_NON_NULL(TAG, subOwner, ERROR);
633 convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
634 VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
635 subOwner->status = MOT_STATUS_DONE;
636 LL_APPEND(doxm->subOwners, subOwner);
638 cborFindResult = cbor_value_advance(&subOwnerCbor);
639 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
642 else if(NULL != gDoxm && NULL != gDoxm->subOwners)
644 // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
645 OicSecSubOwner_t* subOwnerItor = NULL;
646 LL_FOREACH(gDoxm->subOwners, subOwnerItor)
648 OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
649 VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
651 memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
652 subOwnerId->status = MOT_STATUS_DONE;
654 LL_APPEND(doxm->subOwners, subOwnerId);
657 #endif //MULTIPLE_OWNER
659 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
660 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
662 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
663 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
664 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
665 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
671 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
672 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
679 if (CborNoError != cborFindResult)
681 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
682 DeleteDoxmBinData(doxm);
685 ret = OC_STACK_ERROR;
691 * @todo document this function including why code might need to call this.
692 * The current suspicion is that it's not being called as much as it should.
694 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
700 // Convert Doxm data into CBOR for update to persistent storage
701 uint8_t *payload = NULL;
703 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
704 if (payload && (OC_STACK_OK == res)
705 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
713 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
722 static bool ValidateQuery(const char * query)
724 // Send doxm resource data if the state of doxm resource
725 // matches with the query parameters.
726 // else send doxm resource data as NULL
727 // TODO Remove this check and rely on Policy Engine
728 // and Provisioning Mode to enforce provisioning-state
729 // access rules. Eventually, the PE and PM code will
730 // not send a request to the /doxm Entity Handler at all
731 // if it should not respond.
732 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
738 bool bOwnedQry = false; // does querystring contains 'owned' query ?
739 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
740 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
741 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
742 bool bInterfaceQry = false; // does querystring contains 'if' query ?
743 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
744 #ifdef MULTIPLE_OWNER
745 bool bMotMatch = false; // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
746 #endif //MULTIPLE_OWNER
748 OicParseQueryIter_t parseIter = {.attrPos = NULL};
750 ParseQueryIterInit((unsigned char*)query, &parseIter);
752 while (GetNextQuery(&parseIter))
754 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
757 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
762 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
769 #ifdef MULTIPLE_OWNER
770 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
772 OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
773 if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
775 if(GetNextQuery(&parseIter))
777 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
779 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
789 #endif //MULTIPLE_OWNER
791 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
794 OicUuid_t subject = {.id={0}};
796 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
797 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
799 bDeviceIDMatch = true;
803 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
805 bInterfaceQry = true;
806 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
808 bInterfaceMatch = true;
810 return (bInterfaceQry ? bInterfaceMatch: true);
814 return ((bOwnedQry ? bOwnedMatch : true) &&
815 (bDeviceIDQry ? bDeviceIDMatch : true));
818 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
820 OCEntityHandlerResult ehRet = OC_EH_OK;
822 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
824 //Checking if Get request is a query.
825 if (ehRequest->query)
827 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
828 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
829 if (!ValidateQuery(ehRequest->query))
836 * For GET or Valid Query request return doxm resource CBOR payload.
837 * For non-valid query return NULL json payload.
838 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
839 * return valid doxm resource json.
841 uint8_t *payload = NULL;
844 if (ehRet == OC_EH_OK)
846 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
848 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
852 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
853 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
855 // Send response payload to request originator
856 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
857 OC_EH_OK : OC_EH_ERROR;
864 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
869 dst->oxmSel = src->oxmSel;
872 memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
875 memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
878 memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
880 //Update owned status
881 if(dst->owned != src->owned)
883 dst->owned = src->owned;
886 #ifdef MULTIPLE_OWNER
889 OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
892 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
895 dst->mom->mode = src->mom->mode;
899 #endif //MULTIPLE_OWNER
903 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
904 #ifdef MULTIPLE_OWNER
906 * Internal function to get number of sub-owner
908 static size_t GetSubOwnerSize()
910 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
912 size_t numberOfSubOwner = 0;
914 if (gDoxm && gDoxm->subOwners)
916 OicSecSubOwner_t* subowner = NULL;
917 LL_FOREACH(gDoxm->subOwners, subowner)
923 OIC_LOG_V(DEBUG, TAG, "Numer of registered sub-owner=%d", numberOfSubOwner);
924 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
926 return numberOfSubOwner;
930 * Callback function to handle MOT DTLS handshake result.
931 * @param[out] endpoint remote device information.
932 * @param[out] errorInfo CA Error information.
934 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *endpoint,
935 const CAErrorInfo_t *errorInfo)
937 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
938 if (!endpoint || !errorInfo)
940 OIC_LOG(ERROR, TAG, "Invalid param");
946 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
950 if ((CA_STATUS_OK == errorInfo->result) && (true == gDoxm->owned)
951 && (OIC_PRECONFIG_PIN == gDoxm->oxmSel) && (NULL != gDoxm->mom)
952 && (OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode) && (CA_ADAPTER_TCP != endpoint->adapter))
954 OIC_LOG_V(INFO, TAG, "DTLS session established for sub-owner authentication : (%s:%d)",
955 endpoint->addr, endpoint->port);
957 const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(endpoint);
958 if (authenticatedSubOwnerInfo)
960 if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
961 authenticatedSubOwnerInfo->identity.id_length))
963 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
967 OicSecSubOwner_t* subOwnerInst = NULL;
968 LL_FOREACH(gDoxm->subOwners, subOwnerInst)
970 if(0 == memcmp(subOwnerInst->uuid.id,
971 authenticatedSubOwnerInfo->identity.id,
972 authenticatedSubOwnerInfo->identity.id_length))
978 if (NULL == subOwnerInst)
980 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
983 char* strUuid = NULL;
984 if (OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
986 OIC_LOG(WARNING, TAG, "ConvertUuidToStr error");
988 OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
990 if (gMaxSubOwnerSize > GetSubOwnerSize())
992 memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
993 authenticatedSubOwnerInfo->identity.id_length);
994 LL_APPEND(gDoxm->subOwners, subOwnerInst);
995 if (!UpdatePersistentStorage(gDoxm))
997 OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
1002 OIC_LOG_V(ERROR, TAG, "Number of sub-owner exceeded : (MAX SIZE=%d)", gMaxSubOwnerSize);
1004 //Close DTLS session
1005 if (CA_STATUS_OK != CAcloseSslSession(endpoint))
1007 OIC_LOG_V(ERROR, TAG, "CAcloseSslSession error for [%s:%d]", endpoint->addr, endpoint->port);
1011 if (OC_STACK_RESOURCE_DELETED != RemoveCredential(&subOwnerInst->uuid))
1013 OIC_LOG_V(ERROR, TAG, "RemoveCredential error for [%s]", strUuid);
1016 // TODO: How to send error to client side?
1025 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
1027 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
1030 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1032 #endif //MULTIPLE_OWNER
1033 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1036 * Function to validate oxmsel with oxms.
1038 * @param[in] supportedMethods Array of supported methods
1039 * @param[in] numberOfMethods number of supported methods
1040 * @param[out] selectedMethod Selected methods
1041 * @return TRUE on success
1043 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
1044 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
1046 bool isValidOxmsel = false;
1048 OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
1049 if (numberOfMethods == 0 || !supportedMethods)
1051 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
1052 return isValidOxmsel;
1055 for (size_t i = 0; i < numberOfMethods; i++)
1057 if (*selectedMethod == supportedMethods[i])
1059 isValidOxmsel = true;
1065 OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
1066 return isValidOxmsel;
1069 OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
1071 return isValidOxmsel;
1074 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
1076 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
1077 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1078 OicUuid_t emptyOwner = {.id = {0} };
1079 static uint16_t previousMsgId = 0;
1080 bool isDuplicatedMsg = false;
1083 * Convert CBOR Doxm data into binary. This will also validate
1084 * the Doxm data received.
1086 OicSecDoxm_t *newDoxm = NULL;
1088 if (ehRequest->payload)
1090 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1091 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1092 bool roParsed = false;
1093 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1094 if (newDoxm && OC_STACK_OK == res)
1097 * message ID is supported for CoAP over UDP only according to RFC 7252
1098 * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1099 * In case of other transport adapter, duplicate message check is not required.
1101 if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1102 previousMsgId == ehRequest->messageID)
1104 isDuplicatedMsg = true;
1107 if (isDuplicatedMsg && ehRequest->messageID == gConfirmMsgId)
1109 if (CONFIRM_STATE_WAIT == gConfirmState)
1111 OIC_LOG(DEBUG, TAG, "Confirm callback already invoked.");
1112 OIC_LOG(DEBUG, TAG, "This request will be ignored.");
1113 DeleteDoxmBinData(newDoxm);
1118 OIC_LOG_V(DEBUG, TAG, "Confirm request already done, Confirm Result = %s", (CONFIRM_STATE_ACCEPTED == gConfirmState ? "ACCEPTED" : "DENIED"));
1119 ehRet = (CONFIRM_STATE_ACCEPTED == gConfirmState ? OC_EH_OK : OC_EH_NOT_ACCEPTABLE);
1124 // Check request on RO property
1125 if (true == roParsed)
1127 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1128 ehRet = OC_EH_NOT_ACCEPTABLE;
1132 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
1135 if (true == gDoxm->owned)
1137 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1139 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1140 ehRet = OC_EH_NOT_ACCEPTABLE;
1143 //Update gDoxm based on newDoxm
1144 updateWriteableProperty(newDoxm, gDoxm);
1146 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1147 #ifdef MULTIPLE_OWNER
1151 if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1153 CAResult_t caRes = CA_STATUS_FAILED;
1154 if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1156 caRes = CAEnableAnonECDHCipherSuite(false);
1157 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1158 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1160 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, ehRequest->devAddr.adapter);
1161 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1162 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1164 //Set the device id to derive temporal PSK
1165 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1169 OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1172 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1176 //if MOM is disabled, revert the DTLS handshake callback
1177 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1179 OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1184 if(newDoxm->subOwners)
1186 OicSecSubOwner_t* subowner = NULL;
1187 OicSecSubOwner_t* temp = NULL;
1189 OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1191 if(gDoxm->subOwners)
1193 LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1195 LL_DELETE(gDoxm->subOwners, subowner);
1202 LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1204 LL_DELETE(newDoxm->subOwners, subowner);
1205 LL_APPEND(gDoxm->subOwners, subowner);
1208 #endif //MULTIPLE_OWNER
1209 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1211 //Update new state in persistent storage
1212 if (UpdatePersistentStorage(gDoxm) == true)
1218 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1219 ehRet = OC_EH_ERROR;
1225 if ((false == gDoxm->owned) && (false == newDoxm->owned))
1227 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1229 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1230 ehRet = OC_EH_NOT_ACCEPTABLE;
1234 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1235 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1237 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1238 NULL, OIC_OTM_STARTED);
1242 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1245 * If current state of the device is un-owned, enable
1246 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1247 * tool can initiate JUST_WORKS ownership transfer process.
1249 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1251 gDoxm->oxmSel = newDoxm->oxmSel;
1252 //Update new state in persistent storage
1253 if ((UpdatePersistentStorage(gDoxm) == true))
1259 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1260 ehRet = OC_EH_ERROR;
1263 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
1264 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1265 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1266 #endif // __WITH_DTLS__ or __WITH_TLS__
1271 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1272 //Save the owner's UUID to derive owner credential
1273 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1275 // Update new state in persistent storage
1276 if (true == UpdatePersistentStorage(gDoxm))
1282 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1283 ehRet = OC_EH_ERROR;
1288 * Disable anonymous ECDH cipher in tinyDTLS since device is now
1291 CAResult_t caRes = CA_STATUS_OK;
1292 caRes = CAEnableAnonECDHCipherSuite(false);
1293 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1294 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1296 //In case of Mutual Verified Just-Works, verify mutualVerifNum
1297 if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1298 false == isDuplicatedMsg)
1300 uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1301 uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1302 OicUuid_t deviceID = {.id = {0}};
1304 //Generate mutualVerifNum
1305 OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1307 char label[LABEL_LEN] = {0};
1308 snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1309 if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1311 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1312 ehRet = OC_EH_ERROR;
1317 CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1320 gDoxm->owner.id, sizeof(gDoxm->owner.id),
1321 gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1322 preMutualVerifNum, OWNER_PSK_LENGTH_128);
1323 if (CA_STATUS_OK != pskRet)
1325 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1326 ehRet = OC_EH_ERROR;
1331 memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1332 sizeof(mutualVerifNum));
1334 gConfirmMsgId = ehRequest->messageID;
1335 gConfirmState = CONFIRM_STATE_WAIT;
1336 //Wait for user confirmation
1337 if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1339 ehRet = OC_EH_NOT_ACCEPTABLE;
1340 gConfirmState = CONFIRM_STATE_DENIED;
1345 gConfirmState = CONFIRM_STATE_ACCEPTED;
1349 #endif // __WITH_DTLS__ or __WITH_TLS__
1352 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1355 * If current state of the device is un-owned, enable
1356 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1357 * tool can initiate JUST_WORKS ownership transfer process.
1359 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1361 gDoxm->oxmSel = newDoxm->oxmSel;
1362 //Update new state in persistent storage
1363 if ((UpdatePersistentStorage(gDoxm) == true))
1369 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1370 ehRet = OC_EH_ERROR;
1373 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1374 CAResult_t caRes = CA_STATUS_OK;
1376 caRes = CAEnableAnonECDHCipherSuite(false);
1377 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1378 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1380 caRes = CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
1381 ehRequest->devAddr.adapter);
1382 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1384 if (!isDuplicatedMsg)
1386 char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1387 if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1389 //Set the device id to derive temporal PSK
1390 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1393 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1394 * Credential should not be saved into SVR.
1395 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1397 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1398 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1403 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1404 ehRet = OC_EH_ERROR;
1407 #endif // __WITH_DTLS__ or __WITH_TLS__
1409 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1412 //Save the owner's UUID to derive owner credential
1413 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1415 // In case of random-pin based OTM, close the PIN display if callback is registered.
1416 if (!isDuplicatedMsg)
1421 //Update new state in persistent storage
1422 if (UpdatePersistentStorage(gDoxm) == true)
1428 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1429 ehRet = OC_EH_ERROR;
1432 #endif // __WITH_DTLS__ or __WITH_TLS__
1434 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1435 else if (OIC_MANUFACTURER_CERTIFICATE == newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1437 //Get user confirmation
1438 if (false == newDoxm->owned &&
1439 false == isDuplicatedMsg &&
1440 memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1442 gConfirmMsgId = ehRequest->messageID;
1443 gConfirmState = CONFIRM_STATE_WAIT;
1444 if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1446 ehRet = OC_EH_NOT_ACCEPTABLE;
1447 gConfirmState = CONFIRM_STATE_DENIED;
1453 gConfirmState = CONFIRM_STATE_ACCEPTED;
1457 //Save the owner's UUID to derive owner credential
1458 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1459 gDoxm->oxmSel = newDoxm->oxmSel;
1460 //Update new state in persistent storage
1461 if (UpdatePersistentStorage(gDoxm))
1467 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1468 ehRet = OC_EH_ERROR;
1470 CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1471 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1472 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1474 //Unset pre-selected ciphersuite, if any
1475 caRes = CASelectCipherSuite(0, ehRequest->devAddr.adapter);
1476 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1477 OIC_LOG(DEBUG, TAG, "No ciphersuite preferred");
1479 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1480 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1482 #endif // __WITH_DTLS__ or __WITH_TLS__
1486 * When current state of the device is un-owned and Provisioning
1487 * Tool is attempting to change the state to 'Owned' with a
1488 * qualified value for the field 'Owner'
1490 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1491 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1493 //Change the SVR's resource owner as owner device.
1494 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1495 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1497 ehRet = OC_EH_ERROR;
1500 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1501 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1503 ehRet = OC_EH_ERROR;
1506 ownerRes = SetCredRownerId(&gDoxm->owner);
1507 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1509 ehRet = OC_EH_ERROR;
1512 ownerRes = SetPstatRownerId(&gDoxm->owner);
1513 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1515 ehRet = OC_EH_ERROR;
1519 gDoxm->owned = true;
1520 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1522 // Update new state in persistent storage
1523 if (UpdatePersistentStorage(gDoxm))
1525 //Update default ACE of security resource to prevent anonymous user access.
1526 if(OC_STACK_OK == UpdateDefaultSecProvACE())
1532 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1533 ehRet = OC_EH_ERROR;
1538 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1539 ehRet = OC_EH_ERROR;
1541 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1542 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1543 OIC_CON_MFG_CERT== gDoxm->oxmSel)
1545 CAregisterPkixInfoHandler(GetPkixInfo);
1546 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1549 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1550 &gDoxm->owner, OIC_OTM_DONE);
1551 #endif // __WITH_DTLS__ or __WITH_TLS__
1557 if(OC_EH_OK != ehRet)
1560 * If some error is occured while ownership transfer,
1561 * ownership transfer related resource should be revert back to initial status.
1567 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1569 if (!isDuplicatedMsg)
1571 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1572 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1573 NULL, OIC_OTM_ERROR);
1575 RestoreDoxmToInitState();
1576 RestorePstatToInitState();
1577 OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1583 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1587 previousMsgId = ehRequest->messageID;
1589 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1590 CAEndpoint_t peer = {0};
1591 OCDevAddr devAddr = ehRequest->devAddr;
1593 memcpy(&peer.addr, &devAddr.addr, sizeof(peer.addr));
1594 peer.port = devAddr.port;
1595 peer.adapter = (CATransportAdapter_t)devAddr.adapter;
1597 if ((devAddr.flags & OC_FLAG_SECURE) && (false == CAIsExistSslPeer(&peer)))
1599 OIC_LOG_V(WARNING, TAG, "Not Exist Peer");
1604 //Send payload to request originator
1605 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1606 OC_EH_OK : OC_EH_ERROR;
1609 //Send payload to request originator
1610 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1611 OC_EH_OK : OC_EH_ERROR;
1614 DeleteDoxmBinData(newDoxm);
1619 #ifdef MULTIPLE_OWNER
1620 static OCEntityHandlerResult HandleDoxmDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1622 OIC_LOG(DEBUG, TAG, "Processing DoxmDeleteRequest");
1624 OCEntityHandlerResult ehRet = OC_EH_BAD_REQ;
1626 if (NULL == ehRequest->query)
1631 OicParseQueryIter_t parseIter = { .attrPos=NULL };
1632 OicUuid_t subject = {.id={0}};
1634 //Parsing REST query to get the subject
1635 ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1636 while (GetNextQuery(&parseIter))
1638 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBOWNERID_NAME,
1639 parseIter.attrLen) == 0)
1641 if (0 == strncmp((const char*)parseIter.valPos, WILDCARD_RESOURCE_URI,
1642 strlen(WILDCARD_RESOURCE_URI)))
1644 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&WILDCARD_SUBJECT_ID))
1646 ehRet = OC_EH_RESOURCE_DELETED;
1651 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
1652 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1654 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&subject))
1656 ehRet = OC_EH_RESOURCE_DELETED;
1662 //Send response to request originator
1663 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1664 OC_EH_OK : OC_EH_ERROR;
1670 #endif //MULTIPLE_OWNER
1672 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1673 OCEntityHandlerRequest * ehRequest,
1674 void* callbackParam)
1676 (void)callbackParam;
1677 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1679 if(NULL == ehRequest)
1684 if (flag & OC_REQUEST_FLAG)
1686 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1688 switch (ehRequest->method)
1691 ehRet = HandleDoxmGetRequest(ehRequest);
1695 ehRet = HandleDoxmPostRequest(ehRequest);
1698 #ifdef MULTIPLE_OWNER
1699 case OC_REST_DELETE:
1700 ehRet = HandleDoxmDeleteRequest(ehRequest);
1702 #endif //MULTIPLE_OWNER
1705 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1706 OC_EH_OK : OC_EH_ERROR;
1714 OCStackResult CreateDoxmResource()
1716 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1717 OIC_RSRC_TYPE_SEC_DOXM,
1718 OC_RSRVD_INTERFACE_DEFAULT,
1725 if (OC_STACK_OK != ret)
1727 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1728 DeInitDoxmResource();
1734 * Checks if DeviceID is generated during provisioning for the new device.
1735 * If DeviceID is NULL then generates the new DeviceID.
1736 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1738 static OCStackResult CheckDeviceID()
1740 OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
1742 OCStackResult ret = OC_STACK_ERROR;
1743 bool validId = false;
1747 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
1748 return OC_STACK_INVALID_PARAM;
1751 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1753 if (gDoxm->deviceID.id[i] != 0)
1762 char* strUuid = NULL;
1763 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1764 //If seed value is exist, generate UUID using seed with SHA256
1765 if (0 != gUuidSeedSize)
1767 uint8_t hashVal[MBEDTLS_MD_MAX_SIZE] = {0};
1768 mbedtls_md_context_t sha_ctx;
1771 OIC_LOG(DEBUG, TAG, "UUID will be generated using seed w/ SHA256");
1772 OIC_LOG(DEBUG, TAG, "Seed value : ");
1773 OIC_LOG_BUFFER(DEBUG, TAG, gUuidSeed, gUuidSeedSize);
1775 mbedtls_md_init( &sha_ctx );
1776 mbedret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
1779 mbedtls_md_starts( &sha_ctx );
1780 mbedtls_md_update( &sha_ctx, gUuidSeed, gUuidSeedSize);
1781 mbedtls_md_finish(&sha_ctx, (unsigned char*)hashVal);
1782 memcpy(gDoxm->deviceID.id, hashVal, sizeof(gDoxm->deviceID.id));
1787 OIC_LOG_V(ERROR, TAG, "mbedtls_md_setup() returned -0x%04x\n", -mbedret);
1788 ret = OC_STACK_ERROR;
1790 mbedtls_md_free( &sha_ctx );
1794 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
1796 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1797 return OC_STACK_ERROR;
1802 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
1804 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1810 if (OC_STACK_OK == ConvertUuidToStr(&gDoxm->deviceID, &strUuid))
1812 OIC_LOG_V(DEBUG, TAG, "Generated device UUID is [%s]", strUuid);
1817 OIC_LOG(WARNING, TAG, "Failed to convert UUID to string");
1821 if (!UpdatePersistentStorage(gDoxm))
1823 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1824 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1832 OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
1838 * Get the default value.
1840 * @return the default value of doxm, @ref OicSecDoxm_t.
1842 static OicSecDoxm_t* GetDoxmDefault()
1844 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1845 return &gDefaultDoxm;
1848 const OicSecDoxm_t* GetDoxmResourceData()
1853 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1855 * Internal API to prepare MOT
1857 static void PrepareMOT(const OicSecDoxm_t* doxm)
1859 OIC_LOG(INFO, TAG, "IN PrepareMOT");
1860 VERIFY_NON_NULL(TAG, doxm, ERROR);
1862 if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1864 CAResult_t caRes = CA_STATUS_FAILED;
1866 OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1868 if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1870 caRes = CAEnableAnonECDHCipherSuite(false);
1871 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1872 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1874 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP);
1875 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1877 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_TCP);
1878 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1880 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1882 //Set the device id to derive temporal PSK
1883 SetUuidForPinBasedOxm(&doxm->deviceID);
1887 OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1891 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1894 OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1897 OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1899 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1901 OCStackResult InitDoxmResource()
1903 OCStackResult ret = OC_STACK_ERROR;
1905 gConfirmState = CONFIRM_STATE_READY;
1908 //Read DOXM resource from PS
1909 uint8_t *data = NULL;
1911 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1912 // If database read failed
1913 if (OC_STACK_OK != ret)
1915 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1919 // Read DOXM resource from PS
1920 ret = CBORPayloadToDoxm(data, size, &gDoxm);
1923 * If SVR database in persistent storage got corrupted or
1924 * is not available for some reason, a default doxm is created
1925 * which allows user to initiate doxm provisioning again.
1927 if ((OC_STACK_OK != ret) || !data || !gDoxm)
1929 gDoxm = GetDoxmDefault();
1932 //In case of the server is shut down unintentionally, we should initialize the owner
1933 if(gDoxm && (false == gDoxm->owned))
1935 OicUuid_t emptyUuid = {.id={0}};
1936 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1937 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1938 InvokeOtmEventHandler(NULL, 0, NULL, OIC_OTM_READY);
1942 ret = CheckDeviceID();
1943 if (ret == OC_STACK_OK)
1945 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1946 //Instantiate 'oic.sec.doxm'
1947 ret = CreateDoxmResource();
1951 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1955 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1956 //if MOT is enabled, MOT should be prepared.
1957 if(gDoxm && gDoxm->owned)
1961 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1966 OCStackResult DeInitDoxmResource()
1968 OCStackResult ret = OCDeleteResource(gDoxmHandle);
1969 if (gDoxm != &gDefaultDoxm)
1971 DeleteDoxmBinData(gDoxm);
1975 if (OC_STACK_OK == ret)
1981 return OC_STACK_ERROR;
1985 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1987 if (deviceID && gDoxm)
1989 *deviceID = gDoxm->deviceID;
1992 return OC_STACK_ERROR;
1995 OCStackResult GetDoxmIsOwned(bool *isOwned)
1997 if (isOwned && gDoxm)
1999 *isOwned = gDoxm->owned;
2002 return OC_STACK_ERROR;
2005 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2006 OCStackResult SetDoxmDeviceIDSeed(const uint8_t* seed, size_t seedSize)
2008 OIC_LOG_V(INFO, TAG, "In %s", __func__);
2012 return OC_STACK_INVALID_PARAM;
2014 if (MAX_UUID_SEED_SIZE < seedSize)
2016 OIC_LOG_V(ERROR, TAG, "Seed size is too long (MAX size is %d bytes)", MAX_UUID_SEED_SIZE);
2017 return OC_STACK_INVALID_PARAM;
2019 if (MIN_UUID_SEED_SIZE > seedSize)
2021 OIC_LOG_V(ERROR, TAG, "Seed size is too small (MIN size is %d bytes)", MIN_UUID_SEED_SIZE);
2022 return OC_STACK_INVALID_PARAM;
2025 memset(gUuidSeed, 0x00, sizeof(gUuidSeed));
2026 memcpy(gUuidSeed, seed, seedSize);
2027 gUuidSeedSize = seedSize;
2029 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2036 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
2038 bool isOwnerUpdated = false;
2039 bool isRownerUpdated = false;
2040 if (NULL == deviceID)
2042 return OC_STACK_INVALID_PARAM;
2046 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
2047 return OC_STACK_NO_RESOURCE;
2050 #ifdef __WITH_DTLS__
2051 //for normal device.
2052 if (true == gDoxm->owned &&
2053 memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
2055 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
2056 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
2057 return OC_STACK_ERROR;
2059 #endif //__WITH_DTLS
2061 //Save the previous UUID
2063 memcpy(prevUuid.id, gDoxm->deviceID.id, sizeof(prevUuid.id));
2065 //Change the device UUID
2066 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
2068 //Change the owner ID if necessary
2069 if (memcmp(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2071 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
2072 isOwnerUpdated = true;
2074 //Change the resource owner ID if necessary
2075 if (memcmp(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2077 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
2078 isRownerUpdated = true;
2080 // TODO: T.B.D Change resource owner for pstat, acl and cred
2083 if (!UpdatePersistentStorage(gDoxm))
2085 //revert UUID in case of PSI error
2086 memcpy(gDoxm->deviceID.id, prevUuid.id, sizeof(prevUuid.id));
2089 memcpy(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id));
2091 if (isRownerUpdated)
2093 memcpy(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id));
2095 // TODO: T.B.D Revert resource owner for pstat, acl and cred
2097 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
2098 return OC_STACK_ERROR;
2103 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
2105 OCStackResult retVal = OC_STACK_ERROR;
2108 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
2112 *devownerid = gDoxm->owner;
2113 retVal = OC_STACK_OK;
2119 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
2121 OCStackResult retVal = OC_STACK_ERROR;
2126 *rowneruuid = gDoxm->rownerID;
2127 retVal = OC_STACK_OK;
2133 #ifdef MULTIPLE_OWNER
2135 * Compare the UUID to SubOwner.
2137 * @param[in] uuid device UUID
2139 * @return true if context->subjectId exist subowner list, else false.
2141 bool IsSubOwner(const OicUuid_t* uuid)
2143 bool retVal = false;
2150 if (gDoxm && gDoxm->subOwners)
2152 if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
2157 OicSecSubOwner_t* subOwner = NULL;
2158 LL_FOREACH(gDoxm->subOwners, subOwner)
2160 if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
2168 #endif //MULTIPLE_OWNER
2170 OCStackResult SetMOTStatus(bool enable)
2172 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2173 #ifdef MULTIPLE_OWNER
2174 OCStackResult ret = OC_STACK_NO_MEMORY;
2175 uint8_t *cborPayload = NULL;
2177 bool isDeallocateRequired = false;
2179 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
2181 if (NULL == gDoxm->mom && !enable)
2183 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2187 if (NULL == gDoxm->mom)
2189 gDoxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
2190 VERIFY_NON_NULL(TAG, gDoxm->mom, ERROR);
2191 isDeallocateRequired = true;
2194 gDoxm->mom->mode = (enable ? OIC_MULTIPLE_OWNER_ENABLE : OIC_MULTIPLE_OWNER_DISABLE);
2195 gDoxm->oxmSel = OIC_PRECONFIG_PIN;
2197 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2198 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2200 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2201 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2203 isDeallocateRequired = false;
2206 if (isDeallocateRequired)
2208 OICFree(gDoxm->mom);
2212 OICFree(cborPayload);
2214 OIC_LOG_V(DEBUG, TAG, "Out %s : %d", __func__, ret);
2218 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2219 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2220 return OC_STACK_ERROR;
2221 #endif //MULTIPLE_OWNER
2224 OCStackResult RemoveSubOwner(const OicUuid_t* subOwner)
2226 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2227 #ifdef MULTIPLE_OWNER
2228 OCStackResult ret = OC_STACK_ERROR;
2229 bool isDeleted = false;
2231 if (NULL == subOwner)
2233 OIC_LOG(ERROR, TAG, "Invalid sub owner UUID.");
2234 return OC_STACK_INVALID_PARAM;
2238 OIC_LOG(ERROR, TAG, "Doxm resource is NULL");
2239 return OC_STACK_NO_RESOURCE;
2241 if ( NULL == gDoxm->subOwners)
2243 OIC_LOG(WARNING, TAG, "Sub Owner list is empty.");
2244 return OC_STACK_ERROR;
2247 OicSecSubOwner_t* curSubOwner = NULL;
2248 OicSecSubOwner_t* tempSubOwner = NULL;
2249 LL_FOREACH_SAFE(gDoxm->subOwners, curSubOwner, tempSubOwner)
2251 if (memcmp(curSubOwner->uuid.id, subOwner->id, sizeof(subOwner->id)) == 0 ||
2252 memcmp(WILDCARD_SUBJECT_ID.id, subOwner->id, sizeof(OicUuid_t)) == 0)
2254 char* strUuid = NULL;
2255 ret = ConvertUuidToStr(&curSubOwner->uuid, &strUuid);
2256 if (OC_STACK_OK != ret)
2258 OIC_LOG_V(ERROR, TAG, "ConvertUuidToStr error : %d", ret);
2262 OIC_LOG_V(INFO, TAG, "[%s] will be removed from sub owner list.", strUuid);
2263 LL_DELETE(gDoxm->subOwners, curSubOwner);
2265 //Remove the cred for sub owner
2266 ret = RemoveCredential(&curSubOwner->uuid);
2267 if (OC_STACK_RESOURCE_DELETED != ret)
2269 OIC_LOG_V(WARNING, TAG, "RemoveCredential error for [%s] : %d", strUuid, ret);
2273 // TODO: Remove the ACL for sub owner (Currently ACL is not required for sub-owner)
2283 //Update persistent storage
2284 if (UpdatePersistentStorage(gDoxm))
2286 ret = OC_STACK_RESOURCE_DELETED;
2290 OIC_LOG(ERROR, TAG, "UpdatePersistentStorage error");
2291 ret = OC_STACK_ERROR;
2295 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2298 OC_UNUSED(subOwner);
2299 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2300 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2301 return OC_STACK_ERROR;
2302 #endif //MULTIPLE_OWNER
2306 OCStackResult SetNumberOfSubOwner(size_t numOfSubOwner)
2308 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2309 #ifdef MULTIPLE_OWNER
2310 if (MAX_SUBOWNER_SIZE < numOfSubOwner || MIN_SUBOWNER_SIZE > numOfSubOwner)
2312 OIC_LOG_V(ERROR, TAG, "Invalid number of sub owner : %d", numOfSubOwner);
2313 return OC_STACK_INVALID_PARAM;
2315 gMaxSubOwnerSize = numOfSubOwner;
2316 OIC_LOG_V(DEBUG, TAG, "Number of SubOwner = %d", gMaxSubOwnerSize);
2317 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2320 OC_UNUSED(numOfSubOwner);
2321 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2322 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2323 return OC_STACK_ERROR;
2324 #endif //MULTIPLE_OWNER
2328 * Function to restore doxm resurce to initial status.
2329 * This function will use in case of error while ownership transfer
2331 void RestoreDoxmToInitState()
2334 gConfirmState = CONFIRM_STATE_READY;
2339 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
2341 OicUuid_t emptyUuid = {.id={0}};
2342 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
2343 gDoxm->owned = false;
2344 gDoxm->oxmSel = OIC_JUST_WORKS;
2346 if(!UpdatePersistentStorage(gDoxm))
2348 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
2353 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
2355 OCStackResult ret = OC_STACK_ERROR;
2356 uint8_t *cborPayload = NULL;
2361 ret = OC_STACK_NO_RESOURCE;
2365 if( newROwner && (false == gDoxm->owned) )
2367 gDoxm->owned = true;
2368 memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
2369 memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
2371 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2372 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2374 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2375 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2377 OICFree(cborPayload);
2383 OICFree(cborPayload);