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 #define TAG "SRM-DOXM"
55 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
56 * The value of payload size is increased until reaching belox max cbor size. */
57 static const uint16_t CBOR_SIZE = 512;
59 /** Max cbor size payload. */
60 static const uint16_t CBOR_MAX_SIZE = 4400;
62 /** DOXM Map size - Number of mandatory items. */
63 static const uint8_t DOXM_MAP_SIZE = 9;
65 static OicSecDoxm_t *gDoxm = NULL;
66 static OCResourceHandle gDoxmHandle = NULL;
68 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
69 static OicSecDoxm_t gDefaultDoxm =
71 NULL, /* OicUrn_t *oxmType */
72 0, /* size_t oxmTypeLen */
73 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
74 1, /* size_t oxmLen */
75 OIC_JUST_WORKS, /* uint16_t oxmSel */
76 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
77 false, /* bool owned */
78 {.id = {0}}, /* OicUuid_t deviceID */
80 {.id = {0}}, /* OicUuid_t owner */
81 {.id = {0}}, /* OicUuid_t rownerID */
85 * This method is internal method.
86 * the param roParsed is optionally used to know whether cborPayload has
87 * at least read only property value or not.
89 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
90 OicSecDoxm_t **doxm, bool *roParsed);
92 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
97 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
99 OICFree(doxm->oxmType[i]);
101 OICFree(doxm->oxmType);
111 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
114 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
116 return OC_STACK_INVALID_PARAM;
118 size_t cborLen = *size;
126 OCStackResult ret = OC_STACK_ERROR;
130 char* strUuid = NULL;
132 int64_t cborEncoderResult = CborNoError;
133 uint8_t mapSize = DOXM_MAP_SIZE;
134 if (doxm->oxmTypeLen > 0)
138 if (doxm->oxmLen > 0)
143 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
144 VERIFY_NON_NULL(TAG, outPayload, ERROR);
145 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
147 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
148 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
150 //OxmType -- Not Mandatory
151 if (doxm->oxmTypeLen > 0)
154 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
155 strlen(OIC_JSON_OXM_TYPE_NAME));
156 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
157 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
158 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
160 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
162 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
163 strlen(doxm->oxmType[i]));
164 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
166 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
167 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
170 //Oxm -- Not Mandatory
171 if (doxm->oxmLen > 0 && false == rwOnly)
174 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
175 strlen(OIC_JSON_OXMS_NAME));
176 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
177 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
178 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
180 for (size_t i = 0; i < doxm->oxmLen; i++)
182 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
183 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
185 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
186 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
189 //OxmSel -- Mandatory
190 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
191 strlen(OIC_JSON_OXM_SEL_NAME));
192 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
193 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
194 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
199 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
200 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
201 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
202 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
203 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
207 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
208 strlen(OIC_JSON_OWNED_NAME));
209 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
210 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
211 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
215 //DeviceId -- Mandatory
216 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
217 strlen(OIC_JSON_DEVICE_ID_NAME));
218 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
219 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
220 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
221 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
222 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
227 //devownerid -- Mandatory
228 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
229 strlen(OIC_JSON_DEVOWNERID_NAME));
230 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
231 ret = ConvertUuidToStr(&doxm->owner, &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 Owner Id Value.");
238 //ROwner -- Mandatory
239 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
240 strlen(OIC_JSON_ROWNERID_NAME));
241 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
242 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
243 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
244 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
245 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
249 //x.org.iotivity.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
250 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
251 strlen(OIC_JSON_DPC_NAME));
252 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
253 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
254 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
258 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
259 strlen(OIC_JSON_RT_NAME));
260 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
261 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
262 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
263 for (size_t i = 0; i < 1; i++)
265 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
266 strlen(OIC_RSRC_TYPE_SEC_DOXM));
267 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
269 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
270 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
274 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
275 strlen(OIC_JSON_IF_NAME));
276 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
277 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
278 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
279 for (size_t i = 0; i < 1; i++)
281 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
282 strlen(OC_RSRVD_INTERFACE_DEFAULT));
283 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
285 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
286 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
288 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
289 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
291 if (CborNoError == cborEncoderResult)
293 *size = encoder.ptr - outPayload;
294 *payload = outPayload;
298 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
300 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
301 // reallocate and try again!
303 // Since the allocated initial memory failed, double the memory.
304 cborLen += encoder.ptr - encoder.end;
305 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
306 cborEncoderResult = CborNoError;
307 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
311 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
317 ret = OC_STACK_ERROR;
323 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
324 OicSecDoxm_t **secDoxm)
326 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
329 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
330 OicSecDoxm_t **secDoxm, bool *roParsed)
332 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
334 return OC_STACK_INVALID_PARAM;
337 OCStackResult ret = OC_STACK_ERROR;
341 CborError cborFindResult = CborNoError;
342 char* strUuid = NULL;
346 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
348 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
349 VERIFY_NON_NULL(TAG, doxm, ERROR);
351 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
352 //OxmType -- not Mandatory
353 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
357 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
358 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
359 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
361 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
362 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
364 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
365 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
369 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
371 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
373 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
374 cborFindResult = cbor_value_advance(&oxmType);
375 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
379 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
380 //Oxm -- not Mandatory
381 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
384 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
385 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
386 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
388 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
389 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
391 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
392 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
395 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
399 cborFindResult = cbor_value_get_int(&oxm, &tmp);
400 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
401 doxm->oxm[i++] = (OicSecOxm_t)tmp;
402 cborFindResult = cbor_value_advance(&oxm);
403 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
413 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
414 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
415 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
416 doxm->oxmLen = gDoxm->oxmLen;
418 for (i = 0; i < gDoxm->oxmLen; i++)
420 doxm->oxm[i] = gDoxm->oxm[i];
424 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
425 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
429 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
430 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
431 doxm->oxmSel = (OicSecOxm_t)oxmSel;
433 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
435 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
436 doxm->oxmSel = gDoxm->oxmSel;
439 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
440 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
444 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
445 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
446 doxm->sct = (OicSecCredType_t)sct;
453 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
455 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
456 doxm->sct = gDoxm->sct;
459 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
460 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
462 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
463 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
465 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
467 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
468 doxm->owned = gDoxm->owned;
471 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
472 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
474 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
475 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
477 else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc
479 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
480 doxm->dpc = gDoxm->dpc;
483 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
484 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
486 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
487 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
488 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
489 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
500 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
501 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
504 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
505 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
507 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
508 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
509 ret = ConvertStrToUuid(strUuid , &doxm->owner);
510 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
516 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
517 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
520 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
521 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
523 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
524 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
525 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
526 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
532 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
533 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
540 if (CborNoError != cborFindResult)
542 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
543 DeleteDoxmBinData(doxm);
546 ret = OC_STACK_ERROR;
552 * @todo document this function including why code might need to call this.
553 * The current suspicion is that it's not being called as much as it should.
555 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
561 // Convert Doxm data into CBOR for update to persistent storage
562 uint8_t *payload = NULL;
564 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
565 if (payload && (OC_STACK_OK == res)
566 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
574 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
583 static bool ValidateQuery(const char * query)
585 // Send doxm resource data if the state of doxm resource
586 // matches with the query parameters.
587 // else send doxm resource data as NULL
588 // TODO Remove this check and rely on Policy Engine
589 // and Provisioning Mode to enforce provisioning-state
590 // access rules. Eventually, the PE and PM code will
591 // not send a request to the /doxm Entity Handler at all
592 // if it should not respond.
593 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
599 bool bOwnedQry = false; // does querystring contains 'owned' query ?
600 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
601 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
602 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
603 bool bInterfaceQry = false; // does querystring contains 'if' query ?
604 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
606 OicParseQueryIter_t parseIter = {.attrPos = NULL};
608 ParseQueryIterInit((unsigned char*)query, &parseIter);
610 while (GetNextQuery(&parseIter))
612 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
615 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
620 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
627 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
630 OicUuid_t subject = {.id={0}};
632 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
633 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
635 bDeviceIDMatch = true;
639 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
641 bInterfaceQry = true;
642 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
644 bInterfaceMatch = true;
646 return (bInterfaceQry ? bInterfaceMatch: true);
650 return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
653 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
655 OCEntityHandlerResult ehRet = OC_EH_OK;
657 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
659 //Checking if Get request is a query.
660 if (ehRequest->query)
662 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
663 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
664 if (!ValidateQuery(ehRequest->query))
671 * For GET or Valid Query request return doxm resource CBOR payload.
672 * For non-valid query return NULL json payload.
673 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
674 * return valid doxm resource json.
676 uint8_t *payload = NULL;
679 if (ehRet == OC_EH_OK)
681 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
683 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
687 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
688 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
690 // Send response payload to request originator
691 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
692 OC_EH_OK : OC_EH_ERROR;
699 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
701 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
702 OCEntityHandlerResult ehRet = OC_EH_ERROR;
703 OicUuid_t emptyOwner = {.id = {0} };
704 static uint16_t previousMsgId = 0;
707 * Convert CBOR Doxm data into binary. This will also validate
708 * the Doxm data received.
710 OicSecDoxm_t *newDoxm = NULL;
712 if (ehRequest->payload)
714 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
715 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
716 bool roParsed = false;
717 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
718 if (newDoxm && OC_STACK_OK == res)
720 // Check request on RO property
721 if (true == roParsed)
723 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
724 ehRet = OC_EH_NOT_ACCEPTABLE;
729 if (true == gDoxm->owned)
731 // update writable properties
732 gDoxm->oxmSel = newDoxm->oxmSel;
733 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
734 memcpy(&(gDoxm->rownerID), &(newDoxm->rownerID), sizeof(OicUuid_t));
736 if(gDoxm->owned != newDoxm->owned)
738 gDoxm->owned = newDoxm->owned;
741 //Update new state in persistent storage
742 if (UpdatePersistentStorage(gDoxm) == true)
748 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
755 if ((false == gDoxm->owned) && (false == newDoxm->owned))
757 if (OIC_JUST_WORKS == newDoxm->oxmSel)
760 * If current state of the device is un-owned, enable
761 * anonymous ECDH cipher in tinyDTLS so that Provisioning
762 * tool can initiate JUST_WORKS ownership transfer process.
764 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
766 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
768 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
769 #endif //__WITH_DTLS__
775 //Save the owner's UUID to derive owner credential
776 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
778 // Update new state in persistent storage
779 if (true == UpdatePersistentStorage(gDoxm))
785 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
790 * Disable anonymous ECDH cipher in tinyDTLS since device is now
793 CAResult_t caRes = CA_STATUS_OK;
794 caRes = CAEnableAnonECDHCipherSuite(false);
795 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
796 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
799 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
800 CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
801 #endif //__WITH_X509__
802 #endif //__WITH_DTLS__
805 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
808 * If current state of the device is un-owned, enable
809 * anonymous ECDH cipher in tinyDTLS so that Provisioning
810 * tool can initiate JUST_WORKS ownership transfer process.
812 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
814 gDoxm->oxmSel = newDoxm->oxmSel;
815 //Update new state in persistent storage
816 if ((UpdatePersistentStorage(gDoxm) == true))
822 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
827 CAResult_t caRes = CA_STATUS_OK;
829 caRes = CAEnableAnonECDHCipherSuite(false);
830 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
831 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
833 caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
834 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
836 if(previousMsgId != ehRequest->messageID)
838 char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
839 if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
841 //Set the device id to derive temporal PSK
842 SetUuidForRandomPinOxm(&gDoxm->deviceID);
845 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
846 * Credential should not be saved into SVR.
847 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
849 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
850 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
855 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
859 #endif //__WITH_DTLS__
864 //Save the owner's UUID to derive owner credential
865 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
867 //Update new state in persistent storage
868 if (UpdatePersistentStorage(gDoxm) == true)
874 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
883 * When current state of the device is un-owned and Provisioning
884 * Tool is attempting to change the state to 'Owned' with a
885 * qualified value for the field 'Owner'
887 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
888 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
890 //Change the SVR's resource owner as owner device.
891 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
892 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
897 ownerRes = SetAmaclRownerId(&gDoxm->owner);
898 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
903 ownerRes = SetCredRownerId(&gDoxm->owner);
904 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
909 ownerRes = SetPstatRownerId(&gDoxm->owner);
910 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
915 ownerRes = SetDpairingRownerId(&gDoxm->owner);
916 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
921 ownerRes = SetPconfRownerId(&gDoxm->owner);
922 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
929 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
931 // Update new state in persistent storage
932 if (UpdatePersistentStorage(gDoxm))
934 //Update default ACE of security resource to prevent anonymous user access.
935 if(OC_STACK_OK == UpdateDefaultSecProvACE())
941 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
947 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
955 if(OC_EH_OK != ehRet)
959 * If some error is occured while ownership transfer,
960 * ownership transfer related resource should be revert back to initial status.
964 if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
966 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
967 "DOXM will be reverted.");
968 RestoreDoxmToInitState();
969 RestorePstatToInitState();
974 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
979 previousMsgId = ehRequest->messageID;
982 //Send payload to request originator
983 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
984 OC_EH_OK : OC_EH_ERROR;
986 DeleteDoxmBinData(newDoxm);
991 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
992 OCEntityHandlerRequest * ehRequest,
996 OCEntityHandlerResult ehRet = OC_EH_ERROR;
998 if(NULL == ehRequest)
1003 if (flag & OC_REQUEST_FLAG)
1005 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1007 switch (ehRequest->method)
1010 ehRet = HandleDoxmGetRequest(ehRequest);
1014 ehRet = HandleDoxmPostRequest(ehRequest);
1018 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1019 OC_EH_OK : OC_EH_ERROR;
1027 OCStackResult CreateDoxmResource()
1029 OCStackResult ret = OCCreateResource(&gDoxmHandle,
1030 OIC_RSRC_TYPE_SEC_DOXM,
1031 OC_RSRVD_INTERFACE_DEFAULT,
1038 if (OC_STACK_OK != ret)
1040 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1041 DeInitDoxmResource();
1047 * Checks if DeviceID is generated during provisioning for the new device.
1048 * If DeviceID is NULL then generates the new DeviceID.
1049 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1051 static OCStackResult CheckDeviceID()
1053 OCStackResult ret = OC_STACK_ERROR;
1054 bool validId = false;
1055 for (uint8_t i = 0; i < UUID_LENGTH; i++)
1057 if (gDoxm->deviceID.id[i] != 0)
1066 if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1068 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1073 if (!UpdatePersistentStorage(gDoxm))
1075 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1076 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1087 * Get the default value.
1089 * @return the default value of doxm, @ref OicSecDoxm_t.
1091 static OicSecDoxm_t* GetDoxmDefault()
1093 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1094 return &gDefaultDoxm;
1097 const OicSecDoxm_t* GetDoxmResourceData()
1102 OCStackResult InitDoxmResource()
1104 OCStackResult ret = OC_STACK_ERROR;
1106 //Read DOXM resource from PS
1107 uint8_t *data = NULL;
1109 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1110 // If database read failed
1111 if (OC_STACK_OK != ret)
1113 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1117 // Read DOXM resource from PS
1118 ret = CBORPayloadToDoxm(data, size, &gDoxm);
1121 * If SVR database in persistent storage got corrupted or
1122 * is not available for some reason, a default doxm is created
1123 * which allows user to initiate doxm provisioning again.
1125 if ((OC_STACK_OK != ret) || !data || !gDoxm)
1127 gDoxm = GetDoxmDefault();
1130 //In case of the server is shut down unintentionally, we should initialize the owner
1131 if(false == gDoxm->owned)
1133 OicUuid_t emptyUuid = {.id={0}};
1134 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1137 ret = CheckDeviceID();
1138 if (ret == OC_STACK_OK)
1140 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1141 //Instantiate 'oic.sec.doxm'
1142 ret = CreateDoxmResource();
1146 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1152 OCStackResult DeInitDoxmResource()
1154 OCStackResult ret = OCDeleteResource(gDoxmHandle);
1155 if (gDoxm != &gDefaultDoxm)
1157 DeleteDoxmBinData(gDoxm);
1161 if (OC_STACK_OK == ret)
1167 return OC_STACK_ERROR;
1171 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1173 if (deviceID && gDoxm)
1175 *deviceID = gDoxm->deviceID;
1178 return OC_STACK_ERROR;
1181 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1183 OCStackResult retVal = OC_STACK_ERROR;
1186 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
1190 *devownerid = gDoxm->owner;
1191 retVal = OC_STACK_OK;
1197 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1199 OCStackResult retVal = OC_STACK_ERROR;
1204 *rowneruuid = gDoxm->rownerID;
1205 retVal = OC_STACK_OK;
1212 * Function to restore doxm resurce to initial status.
1213 * This function will use in case of error while ownership transfer
1215 void RestoreDoxmToInitState()
1219 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1221 OicUuid_t emptyUuid = {.id={0}};
1222 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1223 gDoxm->owned = false;
1224 gDoxm->oxmSel = OIC_JUST_WORKS;
1226 if(!UpdatePersistentStorage(gDoxm))
1228 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");