1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
32 #include "oic_malloc.h"
33 #include "payload_logging.h"
36 #include "ocpayload.h"
37 #include "cainterface.h"
38 #include "ocserverrequest.h"
39 #include "resourcemanager.h"
40 #include "doxmresource.h"
41 #include "pstatresource.h"
42 #include "aclresource.h"
43 #include "amaclresource.h"
44 #include "pconfresource.h"
45 #include "dpairingresource.h"
46 #include "psinterface.h"
47 #include "srmresourcestrings.h"
48 #include "securevirtualresourcetypes.h"
49 #include "credresource.h"
50 #include "srmutility.h"
51 #include "pinoxmcommon.h"
53 #include "provisioningdatabasemanager.h"
55 #define TAG "SRM-DOXM"
57 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
58 * The value of payload size is increased until reaching belox max cbor size. */
59 static const uint16_t CBOR_SIZE = 512;
61 /** Max cbor size payload. */
62 static const uint16_t CBOR_MAX_SIZE = 4400;
64 /** DOXM Map size - Number of mandatory items. */
65 static const uint8_t DOXM_MAP_SIZE = 9;
67 static OicSecDoxm_t *gDoxm = NULL;
68 static OCResourceHandle gDoxmHandle = NULL;
70 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
71 static OicSecDoxm_t gDefaultDoxm =
73 NULL, /* OicUrn_t *oxmType */
74 0, /* size_t oxmTypeLen */
75 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
76 1, /* size_t oxmLen */
77 OIC_JUST_WORKS, /* uint16_t oxmSel */
78 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
79 false, /* bool owned */
80 {.id = {0}}, /* OicUuid_t deviceID */
82 {.id = {0}}, /* OicUuid_t owner */
83 {.id = {0}}, /* OicUuid_t rownerID */
87 * This method is internal method.
88 * the param roParsed is optionally used to know whether cborPayload has
89 * at least read only property value or not.
91 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
92 OicSecDoxm_t **doxm, bool *roParsed);
94 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
99 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
101 OICFree(doxm->oxmType[i]);
103 OICFree(doxm->oxmType);
113 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
116 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
118 return OC_STACK_INVALID_PARAM;
120 size_t cborLen = *size;
128 OCStackResult ret = OC_STACK_ERROR;
132 char* strUuid = NULL;
134 int64_t cborEncoderResult = CborNoError;
135 uint8_t mapSize = DOXM_MAP_SIZE;
136 if (doxm->oxmTypeLen > 0)
140 if (doxm->oxmLen > 0)
145 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
146 VERIFY_NON_NULL(TAG, outPayload, ERROR);
147 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
149 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
150 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
152 //OxmType -- Not Mandatory
153 if (doxm->oxmTypeLen > 0)
156 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
157 strlen(OIC_JSON_OXM_TYPE_NAME));
158 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
159 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
160 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
162 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
164 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
165 strlen(doxm->oxmType[i]));
166 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
168 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
169 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
172 //Oxm -- Not Mandatory
173 if (doxm->oxmLen > 0 && false == rwOnly)
176 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
177 strlen(OIC_JSON_OXMS_NAME));
178 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
179 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
180 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
182 for (size_t i = 0; i < doxm->oxmLen; i++)
184 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
185 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
187 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
188 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
191 //OxmSel -- Mandatory
192 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
193 strlen(OIC_JSON_OXM_SEL_NAME));
194 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
195 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
196 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
201 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
202 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
203 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
204 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
205 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
209 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
210 strlen(OIC_JSON_OWNED_NAME));
211 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
212 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
213 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
217 //DeviceId -- Mandatory
218 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
219 strlen(OIC_JSON_DEVICE_ID_NAME));
220 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
221 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
222 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
223 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
224 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
229 //devownerid -- Mandatory
230 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
231 strlen(OIC_JSON_DEVOWNERID_NAME));
232 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
233 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
234 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
235 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
236 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
240 //ROwner -- Mandatory
241 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
242 strlen(OIC_JSON_ROWNERID_NAME));
243 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
244 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
245 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
246 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
247 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
251 //x.org.iotivity.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
252 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
253 strlen(OIC_JSON_DPC_NAME));
254 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
255 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
256 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
260 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
261 strlen(OIC_JSON_RT_NAME));
262 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
263 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
264 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
265 for (size_t i = 0; i < 1; i++)
267 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
268 strlen(OIC_RSRC_TYPE_SEC_DOXM));
269 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
271 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
272 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
276 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
277 strlen(OIC_JSON_IF_NAME));
278 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
279 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
280 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
281 for (size_t i = 0; i < 1; i++)
283 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
284 strlen(OC_RSRVD_INTERFACE_DEFAULT));
285 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
287 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
288 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
290 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
291 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
293 if (CborNoError == cborEncoderResult)
295 *size = encoder.ptr - outPayload;
296 *payload = outPayload;
300 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
302 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
303 // reallocate and try again!
305 // Since the allocated initial memory failed, double the memory.
306 cborLen += encoder.ptr - encoder.end;
307 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
308 cborEncoderResult = CborNoError;
309 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
313 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
319 ret = OC_STACK_ERROR;
325 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
326 OicSecDoxm_t **secDoxm)
328 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
331 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
332 OicSecDoxm_t **secDoxm, bool *roParsed)
334 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
336 return OC_STACK_INVALID_PARAM;
339 OCStackResult ret = OC_STACK_ERROR;
343 CborError cborFindResult = CborNoError;
344 char* strUuid = NULL;
348 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
350 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
351 VERIFY_NON_NULL(TAG, doxm, ERROR);
353 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
354 //OxmType -- not Mandatory
355 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
359 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
360 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
361 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
363 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
364 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
366 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
367 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
371 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
373 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
375 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
376 cborFindResult = cbor_value_advance(&oxmType);
377 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
381 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
382 //Oxm -- not Mandatory
383 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
386 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
387 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
388 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
390 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
391 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
393 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
394 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
397 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
401 cborFindResult = cbor_value_get_int(&oxm, &tmp);
402 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
403 doxm->oxm[i++] = (OicSecOxm_t)tmp;
404 cborFindResult = cbor_value_advance(&oxm);
405 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
415 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
416 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
417 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
418 doxm->oxmLen = gDoxm->oxmLen;
419 for (size_t i = 0; i < gDoxm->oxmLen; i++)
421 doxm->oxm[i] = gDoxm->oxm[i];
425 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
426 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
430 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
431 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
432 doxm->oxmSel = (OicSecOxm_t)oxmSel;
434 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
436 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
437 doxm->oxmSel = gDoxm->oxmSel;
440 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
441 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
445 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
446 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
447 doxm->sct = (OicSecCredType_t)sct;
454 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
456 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
457 doxm->sct = gDoxm->sct;
460 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
461 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
463 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
464 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
466 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
468 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
469 doxm->owned = gDoxm->owned;
472 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
473 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
475 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
476 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
478 else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc
480 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
481 doxm->dpc = gDoxm->dpc;
484 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
485 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
487 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
488 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
489 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
490 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
501 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
502 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
505 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
506 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
508 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
509 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
510 ret = ConvertStrToUuid(strUuid , &doxm->owner);
511 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
517 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
518 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
521 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
522 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
524 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
525 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
526 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
527 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
533 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
534 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
541 if (CborNoError != cborFindResult)
543 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
544 DeleteDoxmBinData(doxm);
547 ret = OC_STACK_ERROR;
553 * @todo document this function including why code might need to call this.
554 * The current suspicion is that it's not being called as much as it should.
556 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
562 // Convert Doxm data into CBOR for update to persistent storage
563 uint8_t *payload = NULL;
565 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
566 if (payload && (OC_STACK_OK == res)
567 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
575 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
584 static bool ValidateQuery(const char * query)
586 // Send doxm resource data if the state of doxm resource
587 // matches with the query parameters.
588 // else send doxm resource data as NULL
589 // TODO Remove this check and rely on Policy Engine
590 // and Provisioning Mode to enforce provisioning-state
591 // access rules. Eventually, the PE and PM code will
592 // not send a request to the /doxm Entity Handler at all
593 // if it should not respond.
594 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
600 bool bOwnedQry = false; // does querystring contains 'owned' query ?
601 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
602 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
603 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
604 bool bInterfaceQry = false; // does querystring contains 'if' query ?
605 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
607 OicParseQueryIter_t parseIter = {.attrPos = NULL};
609 ParseQueryIterInit((unsigned char*)query, &parseIter);
611 while (GetNextQuery(&parseIter))
613 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
616 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
621 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
628 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
631 OicUuid_t subject = {.id={0}};
633 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
634 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
636 bDeviceIDMatch = true;
640 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
642 bInterfaceQry = true;
643 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
645 bInterfaceMatch = true;
647 return (bInterfaceQry ? bInterfaceMatch: true);
651 return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
654 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
656 OCEntityHandlerResult ehRet = OC_EH_OK;
658 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
660 //Checking if Get request is a query.
661 if (ehRequest->query)
663 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
664 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
665 if (!ValidateQuery(ehRequest->query))
672 * For GET or Valid Query request return doxm resource CBOR payload.
673 * For non-valid query return NULL json payload.
674 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
675 * return valid doxm resource json.
677 uint8_t *payload = NULL;
680 if (ehRet == OC_EH_OK)
682 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
684 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
688 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
689 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
691 // Send response payload to request originator
692 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
693 OC_EH_OK : OC_EH_ERROR;
700 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
702 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
703 OCEntityHandlerResult ehRet = OC_EH_ERROR;
704 OicUuid_t emptyOwner = {.id = {0} };
705 static uint16_t previousMsgId = 0;
708 * Convert CBOR Doxm data into binary. This will also validate
709 * the Doxm data received.
711 OicSecDoxm_t *newDoxm = NULL;
713 if (ehRequest->payload)
715 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
716 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
717 bool roParsed = false;
718 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
719 if (newDoxm && OC_STACK_OK == res)
721 // Check request on RO property
722 if (true == roParsed)
724 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
725 ehRet = OC_EH_NOT_ACCEPTABLE;
730 if (true == gDoxm->owned)
732 // update writable properties
733 gDoxm->oxmSel = newDoxm->oxmSel;
734 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
735 memcpy(&(gDoxm->rownerID), &(newDoxm->rownerID), sizeof(OicUuid_t));
737 if(gDoxm->owned != newDoxm->owned)
739 gDoxm->owned = newDoxm->owned;
742 //Update new state in persistent storage
743 if (UpdatePersistentStorage(gDoxm) == true)
749 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
756 if ((false == gDoxm->owned) && (false == newDoxm->owned))
758 if (OIC_JUST_WORKS == newDoxm->oxmSel)
761 * If current state of the device is un-owned, enable
762 * anonymous ECDH cipher in tinyDTLS so that Provisioning
763 * tool can initiate JUST_WORKS ownership transfer process.
765 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
767 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
769 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
770 #endif //__WITH_DTLS__
776 //Save the owner's UUID to derive owner credential
777 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
779 // Update new state in persistent storage
780 if (true == UpdatePersistentStorage(gDoxm))
786 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
791 * Disable anonymous ECDH cipher in tinyDTLS since device is now
794 CAResult_t caRes = CA_STATUS_OK;
795 caRes = CAEnableAnonECDHCipherSuite(false);
796 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
797 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
800 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
801 CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
802 ehRequest->devAddr.adapter);
803 #endif //__WITH_X509__
804 #endif //__WITH_DTLS__
807 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
810 * If current state of the device is un-owned, enable
811 * anonymous ECDH cipher in tinyDTLS so that Provisioning
812 * tool can initiate JUST_WORKS ownership transfer process.
814 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
816 gDoxm->oxmSel = newDoxm->oxmSel;
817 //Update new state in persistent storage
818 if ((UpdatePersistentStorage(gDoxm) == true))
824 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
829 CAResult_t caRes = CA_STATUS_OK;
831 caRes = CAEnableAnonECDHCipherSuite(false);
832 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
833 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
835 caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
836 ehRequest->devAddr.adapter);
837 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
839 char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
840 //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
841 if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
843 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
845 //Set the device id to derive temporal PSK
846 SetUuidForRandomPinOxm(&gDoxm->deviceID);
849 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
850 * Credential should not be saved into SVR.
851 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
853 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
854 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
859 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
865 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
867 //Set the device id to derive temporal PSK
868 SetUuidForRandomPinOxm(&gDoxm->deviceID);
871 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
872 * Credential should not be saved into SVR.
873 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
876 caRes = CAregisterTlsCredentialsHandler(GetDtlsPskForRandomPinOxm);
878 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
883 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
888 #endif //__WITH_DTLS__
893 //Save the owner's UUID to derive owner credential
894 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
896 //Update new state in persistent storage
897 if (UpdatePersistentStorage(gDoxm) == true)
903 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
912 * When current state of the device is un-owned and Provisioning
913 * Tool is attempting to change the state to 'Owned' with a
914 * qualified value for the field 'Owner'
916 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
917 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
919 //Change the SVR's resource owner as owner device.
920 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
921 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
926 ownerRes = SetAmaclRownerId(&gDoxm->owner);
927 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
932 ownerRes = SetCredRownerId(&gDoxm->owner);
933 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
938 ownerRes = SetPstatRownerId(&gDoxm->owner);
939 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
944 ownerRes = SetDpairingRownerId(&gDoxm->owner);
945 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
950 ownerRes = SetPconfRownerId(&gDoxm->owner);
951 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
958 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
960 // Update new state in persistent storage
961 if (UpdatePersistentStorage(gDoxm))
963 //Update default ACE of security resource to prevent anonymous user access.
964 if(OC_STACK_OK == UpdateDefaultSecProvACE())
970 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
976 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
984 if(OC_EH_OK != ehRet)
988 * If some error is occured while ownership transfer,
989 * ownership transfer related resource should be revert back to initial status.
993 if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
995 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
996 "DOXM will be reverted.");
997 RestoreDoxmToInitState();
998 RestorePstatToInitState();
1003 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1008 previousMsgId = ehRequest->messageID;
1011 //Send payload to request originator
1012 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1013 OC_EH_OK : OC_EH_ERROR;
1015 DeleteDoxmBinData(newDoxm);
1020 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1021 OCEntityHandlerRequest * ehRequest,
1022 void* callbackParam)
1024 (void)callbackParam;
1025 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1027 if(NULL == ehRequest)
1032 if (flag & OC_REQUEST_FLAG)
1034 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1036 switch (ehRequest->method)
1039 ehRet = HandleDoxmGetRequest(ehRequest);
1043 ehRet = HandleDoxmPostRequest(ehRequest);
1047 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1048 OC_EH_OK : OC_EH_ERROR;
1056 OCStackResult CreateDoxmResource()
1058 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1059 OIC_RSRC_TYPE_SEC_DOXM,
1060 OC_RSRVD_INTERFACE_DEFAULT,
1067 if (OC_STACK_OK != ret)
1069 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1070 DeInitDoxmResource();
1076 * Checks if DeviceID is generated during provisioning for the new device.
1077 * If DeviceID is NULL then generates the new DeviceID.
1078 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1080 static OCStackResult CheckDeviceID()
1082 OCStackResult ret = OC_STACK_ERROR;
1083 bool validId = false;
1084 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1086 if (gDoxm->deviceID.id[i] != 0)
1095 if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1097 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1102 if (!UpdatePersistentStorage(gDoxm))
1104 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1105 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1116 * Get the default value.
1118 * @return the default value of doxm, @ref OicSecDoxm_t.
1120 static OicSecDoxm_t* GetDoxmDefault()
1122 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1123 return &gDefaultDoxm;
1126 const OicSecDoxm_t* GetDoxmResourceData()
1131 OCStackResult InitDoxmResource()
1133 OCStackResult ret = OC_STACK_ERROR;
1135 //Read DOXM resource from PS
1136 uint8_t *data = NULL;
1138 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1139 // If database read failed
1140 if (OC_STACK_OK != ret)
1142 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1146 // Read DOXM resource from PS
1147 ret = CBORPayloadToDoxm(data, size, &gDoxm);
1150 * If SVR database in persistent storage got corrupted or
1151 * is not available for some reason, a default doxm is created
1152 * which allows user to initiate doxm provisioning again.
1154 if ((OC_STACK_OK != ret) || !data || !gDoxm)
1156 gDoxm = GetDoxmDefault();
1159 //In case of the server is shut down unintentionally, we should initialize the owner
1160 if(false == gDoxm->owned)
1162 OicUuid_t emptyUuid = {.id={0}};
1163 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1166 ret = CheckDeviceID();
1167 if (ret == OC_STACK_OK)
1169 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1170 //Instantiate 'oic.sec.doxm'
1171 ret = CreateDoxmResource();
1175 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1181 OCStackResult DeInitDoxmResource()
1183 OCStackResult ret = OCDeleteResource(gDoxmHandle);
1184 if (gDoxm != &gDefaultDoxm)
1186 DeleteDoxmBinData(gDoxm);
1190 if (OC_STACK_OK == ret)
1196 return OC_STACK_ERROR;
1200 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1202 if (deviceID && gDoxm)
1204 *deviceID = gDoxm->deviceID;
1207 return OC_STACK_ERROR;
1210 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1214 if(NULL == deviceID)
1216 return OC_STACK_INVALID_PARAM;
1220 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1221 return OC_STACK_NO_RESOURCE;
1224 //Check the device's OTM state
1226 #ifdef __WITH_DTLS__
1228 if(true == gDoxm->owned &&
1229 memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) == 0)
1231 OCUuidList_t* ownedDevices = NULL;
1232 size_t* ownedDevNum = 0;
1234 if(OC_STACK_OK == PDMGetOwnedDevices(&ownedDevices, &ownedDevNum))
1236 OCUuidList_t* temp1 = NULL;
1237 OCUuidList_t* temp2 = NULL;
1238 LL_FOREACH_SAFE(ownedDevices, temp1, temp2)
1240 LL_DELETE(ownedDevices, temp1);
1244 if(0 != ownedDevNum)
1246 OIC_LOG(ERROR, TAG, "This device has ownership for other device.");
1247 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1248 return OC_STACK_ERROR;
1254 //for normal device.
1255 else if(true == gDoxm->owned)
1257 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1258 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1259 return OC_STACK_ERROR;
1261 #endif //__WITH_DTLS
1263 //Save the previous UUID
1265 memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1268 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1271 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1272 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1276 if(!UpdatePersistentStorage(gDoxm))
1278 //revert UUID in case of update error
1279 memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1282 memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1283 memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1286 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1287 return OC_STACK_ERROR;
1292 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1294 OCStackResult retVal = OC_STACK_ERROR;
1297 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
1301 *devownerid = gDoxm->owner;
1302 retVal = OC_STACK_OK;
1308 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1310 OCStackResult retVal = OC_STACK_ERROR;
1315 *rowneruuid = gDoxm->rownerID;
1316 retVal = OC_STACK_OK;
1323 * Function to restore doxm resurce to initial status.
1324 * This function will use in case of error while ownership transfer
1326 void RestoreDoxmToInitState()
1330 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1332 OicUuid_t emptyUuid = {.id={0}};
1333 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1334 gDoxm->owned = false;
1335 gDoxm->oxmSel = OIC_JUST_WORKS;
1337 if(!UpdatePersistentStorage(gDoxm))
1339 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");