1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #include "iotivity_config.h"
33 #include "oic_malloc.h"
34 #include "payload_logging.h"
37 #include "ocpayload.h"
38 #include "cainterface.h"
39 #include "ocserverrequest.h"
40 #include "resourcemanager.h"
41 #include "doxmresource.h"
42 #include "pstatresource.h"
43 #include "aclresource.h"
44 #include "amaclresource.h"
45 #include "pconfresource.h"
46 #include "dpairingresource.h"
47 #include "psinterface.h"
48 #include "srmresourcestrings.h"
49 #include "securevirtualresourcetypes.h"
50 #include "credresource.h"
51 #include "srmutility.h"
52 #include "pinoxmcommon.h"
54 #define TAG "SRM-DOXM"
56 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
57 * The value of payload size is increased until reaching belox max cbor size. */
58 static const uint16_t CBOR_SIZE = 512;
60 /** Max cbor size payload. */
61 static const uint16_t CBOR_MAX_SIZE = 4400;
63 static OicSecDoxm_t *gDoxm = NULL;
64 static OCResourceHandle gDoxmHandle = NULL;
66 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
67 static OicSecDoxm_t gDefaultDoxm =
69 NULL, /* OicUrn_t *oxmType */
70 0, /* size_t oxmTypeLen */
71 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
72 1, /* size_t oxmLen */
73 OIC_JUST_WORKS, /* uint16_t oxmSel */
74 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
75 false, /* bool owned */
76 {.id = {0}}, /* OicUuid_t deviceID */
78 {.id = {0}}, /* OicUuid_t owner */
79 {.id = {0}}, /* OicUuid_t rownerID */
83 * This method is internal method.
84 * the param roParsed is optionally used to know whether cborPayload has
85 * at least read only property value or not.
87 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
88 OicSecDoxm_t **doxm, bool *roParsed);
90 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
95 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
97 OICFree(doxm->oxmType[i]);
99 OICFree(doxm->oxmType);
109 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
112 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
114 return OC_STACK_INVALID_PARAM;
116 size_t cborLen = *size;
124 OCStackResult ret = OC_STACK_ERROR;
128 char* strUuid = NULL;
130 int64_t cborEncoderResult = CborNoError;
132 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
133 VERIFY_NON_NULL(TAG, outPayload, ERROR);
134 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
136 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
137 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
139 //OxmType -- Not Mandatory
140 if (doxm->oxmTypeLen > 0)
143 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
144 strlen(OIC_JSON_OXM_TYPE_NAME));
145 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
146 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
147 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
149 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
151 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
152 strlen(doxm->oxmType[i]));
153 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
155 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
156 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
159 //Oxm -- Not Mandatory
160 if (doxm->oxmLen > 0 && false == rwOnly)
163 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
164 strlen(OIC_JSON_OXMS_NAME));
165 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
166 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
167 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
169 for (size_t i = 0; i < doxm->oxmLen; i++)
171 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
172 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
174 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
175 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
178 //OxmSel -- Mandatory
179 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
180 strlen(OIC_JSON_OXM_SEL_NAME));
181 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
182 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
183 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
188 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
189 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
190 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
191 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
192 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
196 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
197 strlen(OIC_JSON_OWNED_NAME));
198 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
199 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
200 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
204 //DeviceId -- Mandatory
205 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
206 strlen(OIC_JSON_DEVICE_ID_NAME));
207 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
208 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
209 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
210 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
211 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
216 //devownerid -- Mandatory
217 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
218 strlen(OIC_JSON_DEVOWNERID_NAME));
219 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
220 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
221 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
222 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
223 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
227 //ROwner -- Mandatory
228 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
229 strlen(OIC_JSON_ROWNERID_NAME));
230 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
231 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
232 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
233 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
234 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
238 //x.org.iotivity.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
239 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
240 strlen(OIC_JSON_DPC_NAME));
241 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
242 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
243 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
247 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
248 strlen(OIC_JSON_RT_NAME));
249 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
250 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
251 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
252 for (size_t i = 0; i < 1; i++)
254 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
255 strlen(OIC_RSRC_TYPE_SEC_DOXM));
256 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
258 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
259 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
263 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
264 strlen(OIC_JSON_IF_NAME));
265 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
266 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
267 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
268 for (size_t i = 0; i < 1; i++)
270 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
271 strlen(OC_RSRVD_INTERFACE_DEFAULT));
272 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
274 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
275 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
277 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
278 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
280 if (CborNoError == cborEncoderResult)
282 *size = encoder.ptr - outPayload;
283 *payload = outPayload;
287 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
289 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
290 // reallocate and try again!
292 // Since the allocated initial memory failed, double the memory.
293 cborLen += encoder.ptr - encoder.end;
294 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
295 cborEncoderResult = CborNoError;
296 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
300 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
306 ret = OC_STACK_ERROR;
312 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
313 OicSecDoxm_t **secDoxm)
315 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
318 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
319 OicSecDoxm_t **secDoxm, bool *roParsed)
321 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
323 return OC_STACK_INVALID_PARAM;
326 OCStackResult ret = OC_STACK_ERROR;
330 CborError cborFindResult = CborNoError;
331 char* strUuid = NULL;
335 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
337 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
338 VERIFY_NON_NULL(TAG, doxm, ERROR);
340 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
341 //OxmType -- not Mandatory
342 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
346 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
347 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
348 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
350 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
351 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
353 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
354 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
358 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
360 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
362 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
363 cborFindResult = cbor_value_advance(&oxmType);
364 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
368 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
369 //Oxm -- not Mandatory
370 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
373 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
374 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
375 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
377 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
378 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
380 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
381 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
384 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
388 cborFindResult = cbor_value_get_int(&oxm, &tmp);
389 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
390 doxm->oxm[i++] = (OicSecOxm_t)tmp;
391 cborFindResult = cbor_value_advance(&oxm);
392 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
402 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
403 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
404 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
405 doxm->oxmLen = gDoxm->oxmLen;
406 for (size_t i = 0; i < gDoxm->oxmLen; i++)
408 doxm->oxm[i] = gDoxm->oxm[i];
412 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
413 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
417 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
418 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
419 doxm->oxmSel = (OicSecOxm_t)oxmSel;
421 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
423 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
424 doxm->oxmSel = gDoxm->oxmSel;
427 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
428 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
432 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
433 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
434 doxm->sct = (OicSecCredType_t)sct;
441 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
443 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
444 doxm->sct = gDoxm->sct;
447 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
448 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
450 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
451 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
453 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
455 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
456 doxm->owned = gDoxm->owned;
459 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
460 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
462 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
463 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
465 else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc
467 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
468 doxm->dpc = gDoxm->dpc;
471 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
472 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
474 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
475 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
476 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
477 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
488 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
489 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
492 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
493 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
495 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
496 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
497 ret = ConvertStrToUuid(strUuid , &doxm->owner);
498 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
504 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
505 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
508 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
509 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
511 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
512 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
513 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
514 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
520 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
521 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
528 if (CborNoError != cborFindResult)
530 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
531 DeleteDoxmBinData(doxm);
534 ret = OC_STACK_ERROR;
540 * @todo document this function including why code might need to call this.
541 * The current suspicion is that it's not being called as much as it should.
543 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
549 // Convert Doxm data into CBOR for update to persistent storage
550 uint8_t *payload = NULL;
552 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
553 if (payload && (OC_STACK_OK == res)
554 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
562 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
571 static bool ValidateQuery(const char * query)
573 // Send doxm resource data if the state of doxm resource
574 // matches with the query parameters.
575 // else send doxm resource data as NULL
576 // TODO Remove this check and rely on Policy Engine
577 // and Provisioning Mode to enforce provisioning-state
578 // access rules. Eventually, the PE and PM code will
579 // not send a request to the /doxm Entity Handler at all
580 // if it should not respond.
581 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
587 bool bOwnedQry = false; // does querystring contains 'owned' query ?
588 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
589 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
590 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
591 bool bInterfaceQry = false; // does querystring contains 'if' query ?
592 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
594 OicParseQueryIter_t parseIter = {.attrPos = NULL};
596 ParseQueryIterInit((unsigned char*)query, &parseIter);
598 while (GetNextQuery(&parseIter))
600 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
603 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
608 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
615 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
618 OicUuid_t subject = {.id={0}};
620 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
621 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
623 bDeviceIDMatch = true;
627 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
629 bInterfaceQry = true;
630 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
632 bInterfaceMatch = true;
634 return (bInterfaceQry ? bInterfaceMatch: true);
638 return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
641 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
643 OCEntityHandlerResult ehRet = OC_EH_OK;
645 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
647 //Checking if Get request is a query.
648 if (ehRequest->query)
650 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
651 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
652 if (!ValidateQuery(ehRequest->query))
659 * For GET or Valid Query request return doxm resource CBOR payload.
660 * For non-valid query return NULL json payload.
661 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
662 * return valid doxm resource json.
664 uint8_t *payload = NULL;
667 if (ehRet == OC_EH_OK)
669 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
671 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
675 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
676 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
678 // Send response payload to request originator
679 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
680 OC_EH_OK : OC_EH_ERROR;
687 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
689 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
690 OCEntityHandlerResult ehRet = OC_EH_ERROR;
691 OicUuid_t emptyOwner = {.id = {0} };
692 static uint16_t previousMsgId = 0;
695 * Convert CBOR Doxm data into binary. This will also validate
696 * the Doxm data received.
698 OicSecDoxm_t *newDoxm = NULL;
700 if (ehRequest->payload)
702 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
703 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
704 bool roParsed = false;
705 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
706 if (newDoxm && OC_STACK_OK == res)
708 // Check request on RO property
709 if (true == roParsed)
711 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
712 ehRet = OC_EH_NOT_ACCEPTABLE;
717 if (true == gDoxm->owned)
719 // update writable properties
720 gDoxm->oxmSel = newDoxm->oxmSel;
721 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
722 memcpy(&(gDoxm->rownerID), &(newDoxm->rownerID), sizeof(OicUuid_t));
724 if(gDoxm->owned != newDoxm->owned)
726 gDoxm->owned = newDoxm->owned;
729 //Update new state in persistent storage
730 if (UpdatePersistentStorage(gDoxm) == true)
736 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
743 if ((false == gDoxm->owned) && (false == newDoxm->owned))
745 if (OIC_JUST_WORKS == newDoxm->oxmSel)
748 * If current state of the device is un-owned, enable
749 * anonymous ECDH cipher in tinyDTLS so that Provisioning
750 * tool can initiate JUST_WORKS ownership transfer process.
752 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
754 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
755 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
756 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
757 #endif // __WITH_DTLS__ or __WITH_TLS__
762 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
763 //Save the owner's UUID to derive owner credential
764 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
766 // Update new state in persistent storage
767 if (true == UpdatePersistentStorage(gDoxm))
773 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
778 * Disable anonymous ECDH cipher in tinyDTLS since device is now
781 CAResult_t caRes = CA_STATUS_OK;
782 caRes = CAEnableAnonECDHCipherSuite(false);
783 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
784 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
786 #endif // __WITH_DTLS__ or __WITH_TLS__
789 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
792 * If current state of the device is un-owned, enable
793 * anonymous ECDH cipher in tinyDTLS so that Provisioning
794 * tool can initiate JUST_WORKS ownership transfer process.
796 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
798 gDoxm->oxmSel = newDoxm->oxmSel;
799 //Update new state in persistent storage
800 if ((UpdatePersistentStorage(gDoxm) == true))
806 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
810 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
811 CAResult_t caRes = CA_STATUS_OK;
813 caRes = CAEnableAnonECDHCipherSuite(false);
814 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
815 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
817 caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
818 ehRequest->devAddr.adapter);
819 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
821 char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
822 //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
823 if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
825 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
827 //Set the device id to derive temporal PSK
828 SetUuidForRandomPinOxm(&gDoxm->deviceID);
831 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
832 * Credential should not be saved into SVR.
833 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
835 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
836 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
841 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
847 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
849 //Set the device id to derive temporal PSK
850 SetUuidForRandomPinOxm(&gDoxm->deviceID);
853 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
854 * Credential should not be saved into SVR.
855 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
858 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
860 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
865 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
870 #endif // __WITH_DTLS__ or __WITH_TLS__
874 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
875 //Save the owner's UUID to derive owner credential
876 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
878 //Update new state in persistent storage
879 if (UpdatePersistentStorage(gDoxm) == true)
885 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
888 #endif // __WITH_DTLS__ or __WITH_TLS__
894 * When current state of the device is un-owned and Provisioning
895 * Tool is attempting to change the state to 'Owned' with a
896 * qualified value for the field 'Owner'
898 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
899 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
901 //Change the SVR's resource owner as owner device.
902 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
903 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
908 ownerRes = SetAmaclRownerId(&gDoxm->owner);
909 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
914 ownerRes = SetCredRownerId(&gDoxm->owner);
915 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
920 ownerRes = SetPstatRownerId(&gDoxm->owner);
921 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
926 ownerRes = SetDpairingRownerId(&gDoxm->owner);
927 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
932 ownerRes = SetPconfRownerId(&gDoxm->owner);
933 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
940 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
942 // Update new state in persistent storage
943 if (UpdatePersistentStorage(gDoxm))
945 //Update default ACE of security resource to prevent anonymous user access.
946 if(OC_STACK_OK == UpdateDefaultSecProvACE())
952 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
958 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
966 if(OC_EH_OK != ehRet)
970 * If some error is occured while ownership transfer,
971 * ownership transfer related resource should be revert back to initial status.
975 if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
977 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
978 "DOXM will be reverted.");
979 RestoreDoxmToInitState();
980 RestorePstatToInitState();
985 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
990 previousMsgId = ehRequest->messageID;
993 //Send payload to request originator
994 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
995 OC_EH_OK : OC_EH_ERROR;
997 DeleteDoxmBinData(newDoxm);
1002 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1003 OCEntityHandlerRequest * ehRequest,
1004 void* callbackParam)
1006 (void)callbackParam;
1007 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1009 if(NULL == ehRequest)
1014 if (flag & OC_REQUEST_FLAG)
1016 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1018 switch (ehRequest->method)
1021 ehRet = HandleDoxmGetRequest(ehRequest);
1025 ehRet = HandleDoxmPostRequest(ehRequest);
1029 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1030 OC_EH_OK : OC_EH_ERROR;
1038 OCStackResult CreateDoxmResource()
1040 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1041 OIC_RSRC_TYPE_SEC_DOXM,
1042 OC_RSRVD_INTERFACE_DEFAULT,
1049 if (OC_STACK_OK != ret)
1051 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1052 DeInitDoxmResource();
1058 * Checks if DeviceID is generated during provisioning for the new device.
1059 * If DeviceID is NULL then generates the new DeviceID.
1060 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1062 static OCStackResult CheckDeviceID()
1064 OCStackResult ret = OC_STACK_ERROR;
1065 bool validId = false;
1066 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1068 if (gDoxm->deviceID.id[i] != 0)
1077 if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1079 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1084 if (!UpdatePersistentStorage(gDoxm))
1086 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1087 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1098 * Get the default value.
1100 * @return the default value of doxm, @ref OicSecDoxm_t.
1102 static OicSecDoxm_t* GetDoxmDefault()
1104 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1105 return &gDefaultDoxm;
1108 const OicSecDoxm_t* GetDoxmResourceData()
1113 OCStackResult InitDoxmResource()
1115 OCStackResult ret = OC_STACK_ERROR;
1117 //Read DOXM resource from PS
1118 uint8_t *data = NULL;
1120 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1121 // If database read failed
1122 if (OC_STACK_OK != ret)
1124 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1128 // Read DOXM resource from PS
1129 ret = CBORPayloadToDoxm(data, size, &gDoxm);
1132 * If SVR database in persistent storage got corrupted or
1133 * is not available for some reason, a default doxm is created
1134 * which allows user to initiate doxm provisioning again.
1136 if ((OC_STACK_OK != ret) || !data || !gDoxm)
1138 gDoxm = GetDoxmDefault();
1141 //In case of the server is shut down unintentionally, we should initialize the owner
1142 if(false == gDoxm->owned)
1144 OicUuid_t emptyUuid = {.id={0}};
1145 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1148 ret = CheckDeviceID();
1149 if (ret == OC_STACK_OK)
1151 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1152 //Instantiate 'oic.sec.doxm'
1153 ret = CreateDoxmResource();
1157 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1163 OCStackResult DeInitDoxmResource()
1165 OCStackResult ret = OCDeleteResource(gDoxmHandle);
1166 if (gDoxm != &gDefaultDoxm)
1168 DeleteDoxmBinData(gDoxm);
1172 if (OC_STACK_OK == ret)
1178 return OC_STACK_ERROR;
1182 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1184 if (deviceID && gDoxm)
1186 *deviceID = gDoxm->deviceID;
1189 return OC_STACK_ERROR;
1192 OCStackResult GetDoxmIsOwned(bool *isOwned)
1194 if (isOwned && gDoxm)
1196 *isOwned = gDoxm->owned;
1199 return OC_STACK_ERROR;
1202 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1206 if(NULL == deviceID)
1208 return OC_STACK_INVALID_PARAM;
1212 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1213 return OC_STACK_NO_RESOURCE;
1216 //Check the device's OTM state
1218 #ifdef __WITH_DTLS__
1219 //for normal device.
1220 if(true == gDoxm->owned)
1222 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1223 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1224 return OC_STACK_ERROR;
1226 #endif //__WITH_DTLS
1228 //Save the previous UUID
1230 memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1233 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1236 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1237 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1241 if(!UpdatePersistentStorage(gDoxm))
1243 //revert UUID in case of update error
1244 memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1247 memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1248 memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1251 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1252 return OC_STACK_ERROR;
1257 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1259 OCStackResult retVal = OC_STACK_ERROR;
1262 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
1266 *devownerid = gDoxm->owner;
1267 retVal = OC_STACK_OK;
1273 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1275 OCStackResult retVal = OC_STACK_ERROR;
1280 *rowneruuid = gDoxm->rownerID;
1281 retVal = OC_STACK_OK;
1288 * Function to restore doxm resurce to initial status.
1289 * This function will use in case of error while ownership transfer
1291 void RestoreDoxmToInitState()
1295 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1297 OicUuid_t emptyUuid = {.id={0}};
1298 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1299 gDoxm->owned = false;
1300 gDoxm->oxmSel = OIC_JUST_WORKS;
1302 if(!UpdatePersistentStorage(gDoxm))
1304 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");