Fix Doxm Handler for Manufacturer Cert OTM
[iotivity.git] / resource / csdk / security / src / doxmresource.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #include "iotivity_config.h"
21 #include <stdlib.h>
22 #include <string.h>
23
24 #ifdef HAVE_STRINGS_H
25 #include <strings.h>
26 #endif
27
28 #ifdef __WITH_DTLS__
29 #include "global.h"
30 #endif
31
32 #include "ocstack.h"
33 #include "oic_malloc.h"
34 #include "payload_logging.h"
35 #include "utlist.h"
36 #include "ocrandom.h"
37 #include "ocpayload.h"
38 #include "ocpayloadcbor.h"
39 #include "cainterface.h"
40 #include "ocserverrequest.h"
41 #include "resourcemanager.h"
42 #include "doxmresource.h"
43 #include "pstatresource.h"
44 #include "aclresource.h"
45 #include "amaclresource.h"
46 #include "pconfresource.h"
47 #include "dpairingresource.h"
48 #include "psinterface.h"
49 #include "srmresourcestrings.h"
50 #include "securevirtualresourcetypes.h"
51 #include "credresource.h"
52 #include "srmutility.h"
53 #include "pinoxmcommon.h"
54 #include "oxmverifycommon.h"
55
56 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
57 #include "pkix_interface.h"
58 #endif
59
60 #define TAG  "OIC_SRM_DOXM"
61 #define CHAR_ZERO ('0')
62
63 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
64  * The value of payload size is increased until reaching belox max cbor size. */
65 static const uint16_t CBOR_SIZE = 512;
66
67 /** Max cbor size payload. */
68 static const uint16_t CBOR_MAX_SIZE = 4400;
69
70 static OicSecDoxm_t        *gDoxm = NULL;
71 static OCResourceHandle    gDoxmHandle = NULL;
72
73 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
74 static OicSecDoxm_t gDefaultDoxm =
75 {
76     NULL,                   /* OicUrn_t *oxmType */
77     0,                      /* size_t oxmTypeLen */
78     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
79     1,                      /* size_t oxmLen */
80     OIC_JUST_WORKS,         /* uint16_t oxmSel */
81     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
82     false,                  /* bool owned */
83     {.id = {0}},            /* OicUuid_t deviceID */
84     false,                  /* bool dpc */
85     {.id = {0}},            /* OicUuid_t owner */
86 #ifdef MULTIPLE_OWNER
87     NULL,                   /* OicSecSubOwner_t sub-owner list */
88     NULL,                   /* OicSecMomType_t multiple owner mode */
89 #endif //MULTIPLE_OWNER
90     {.id = {0}},            /* OicUuid_t rownerID */
91 };
92
93 /**
94  * This method is internal method.
95  * the param roParsed is optionally used to know whether cborPayload has
96  * at least read only property value or not.
97  */
98 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
99                                 OicSecDoxm_t **doxm, bool *roParsed);
100
101 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
102 {
103     if (doxm)
104     {
105         //Clean oxmType
106         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
107         {
108             OICFree(doxm->oxmType[i]);
109         }
110         OICFree(doxm->oxmType);
111
112         //clean oxm
113         OICFree(doxm->oxm);
114
115 #ifdef MULTIPLE_OWNER
116         //clean mom
117         OICFree(doxm->mom);
118
119         //clean sub-owner list
120         if(NULL != doxm->subOwners)
121         {
122             OicSecSubOwner_t* subowner = NULL;
123             OicSecSubOwner_t* temp = NULL;
124             LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
125             {
126                 LL_DELETE(doxm->subOwners, subowner);
127                 OICFree(subowner);
128             }
129         }
130 #endif //MULTIPLE_OWNER
131
132         //Clean doxm itself
133         OICFree(doxm);
134     }
135 }
136
137 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
138                                 bool rwOnly)
139 {
140     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
141     {
142         return OC_STACK_INVALID_PARAM;
143     }
144     size_t cborLen = *size;
145     if (0 == cborLen)
146     {
147         cborLen = CBOR_SIZE;
148     }
149     *payload = NULL;
150     *size = 0;
151
152     OCStackResult ret = OC_STACK_ERROR;
153
154     CborEncoder encoder;
155     CborEncoder doxmMap;
156     char* strUuid = NULL;
157
158     int64_t cborEncoderResult = CborNoError;
159
160     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
161     VERIFY_NON_NULL(TAG, outPayload, ERROR);
162     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
163
164     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
165     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
166
167     //OxmType -- Not Mandatory
168     if (doxm->oxmTypeLen > 0)
169     {
170         CborEncoder oxmType;
171         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
172             strlen(OIC_JSON_OXM_TYPE_NAME));
173         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
174         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
175         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
176
177         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
178         {
179             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
180                 strlen(doxm->oxmType[i]));
181             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
182         }
183         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
184         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
185     }
186
187     //Oxm -- Not Mandatory
188     if (doxm->oxmLen > 0 && false == rwOnly)
189     {
190         CborEncoder oxm;
191         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
192             strlen(OIC_JSON_OXMS_NAME));
193         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
194         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
195         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
196
197         for (size_t i = 0; i < doxm->oxmLen; i++)
198         {
199             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
200             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
201         }
202         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
203         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
204     }
205
206     //OxmSel -- Mandatory
207     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
208         strlen(OIC_JSON_OXM_SEL_NAME));
209     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
210     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
211     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
212
213     //sct -- Mandatory
214     if (false == rwOnly)
215     {
216         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
217             strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
218         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
219         cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
220         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
221     }
222
223     //Owned -- Mandatory
224     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
225         strlen(OIC_JSON_OWNED_NAME));
226     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
227     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
228     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
229
230     if (false == rwOnly)
231     {
232         //DeviceId -- Mandatory
233         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
234             strlen(OIC_JSON_DEVICE_ID_NAME));
235         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
236         ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
237         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
238         cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
239         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
240         OICFree(strUuid);
241         strUuid = NULL;
242     }
243
244 #ifdef MULTIPLE_OWNER
245     //Device SubOwnerID -- Not Mandatory
246     if(doxm->subOwners)
247     {
248         size_t subOwnerLen = 0;
249         OicSecSubOwner_t* subOwner = NULL;
250         LL_FOREACH(doxm->subOwners, subOwner)
251         {
252             subOwnerLen++;
253         }
254
255         CborEncoder subOwners;
256         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
257             strlen(OIC_JSON_SUBOWNERID_NAME));
258         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
259         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
260         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
261
262         subOwner = NULL;
263         LL_FOREACH(doxm->subOwners, subOwner)
264         {
265             char* strUuid = NULL;
266             ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
267             VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
268             cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
269             OICFree(strUuid);
270             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
271         }
272         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
273         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
274     }
275
276     //Multiple Owner Mode -- Not Mandatory
277     if(doxm->mom)
278     {
279         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
280             strlen(OIC_JSON_MOM_NAME));
281         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
282         cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
283         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
284     }
285 #endif //MULTIPLE_OWNER
286
287     //devownerid -- Mandatory
288     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
289         strlen(OIC_JSON_DEVOWNERID_NAME));
290     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
291     ret = ConvertUuidToStr(&doxm->owner, &strUuid);
292     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
293     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
294     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
295     OICFree(strUuid);
296     strUuid = NULL;
297
298     //ROwner -- Mandatory
299     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
300         strlen(OIC_JSON_ROWNERID_NAME));
301     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
302     ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
303     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
304     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
305     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
306     OICFree(strUuid);
307     strUuid = NULL;
308
309     //RT -- Mandatory
310     CborEncoder rtArray;
311     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
312             strlen(OIC_JSON_RT_NAME));
313     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
314     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
315     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
316     for (size_t i = 0; i < 1; i++)
317     {
318         cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
319                 strlen(OIC_RSRC_TYPE_SEC_DOXM));
320         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
321     }
322     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
323     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
324
325     //IF-- Mandatory
326      CborEncoder ifArray;
327      cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
328              strlen(OIC_JSON_IF_NAME));
329      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
330      cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
331      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
332     for (size_t i = 0; i < 1; i++)
333     {
334         cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
335                 strlen(OC_RSRVD_INTERFACE_DEFAULT));
336         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
337     }
338     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
339     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
340
341     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
342     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
343
344     if (CborNoError == cborEncoderResult)
345     {
346         *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
347         *payload = outPayload;
348         ret = OC_STACK_OK;
349     }
350 exit:
351     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
352     {
353         OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
354         // reallocate and try again!
355         OICFree(outPayload);
356         // Since the allocated initial memory failed, double the memory.
357         cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
358         OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
359         cborEncoderResult = CborNoError;
360         ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
361         *size = cborLen;
362     }
363
364     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
365     {
366        OICFree(outPayload);
367        outPayload = NULL;
368        *payload = NULL;
369        *size = 0;
370        ret = OC_STACK_ERROR;
371     }
372
373     return ret;
374 }
375
376 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
377                                 OicSecDoxm_t **secDoxm)
378 {
379     return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
380 }
381
382 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
383                                 OicSecDoxm_t **secDoxm, bool *roParsed)
384 {
385     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
386     {
387         return OC_STACK_INVALID_PARAM;
388     }
389
390     OCStackResult ret = OC_STACK_ERROR;
391     *secDoxm = NULL;
392
393     CborParser parser;
394     CborError cborFindResult = CborNoError;
395     char* strUuid = NULL;
396     size_t len = 0;
397     CborValue doxmCbor;
398
399     cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
400     CborValue doxmMap;
401     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
402     VERIFY_NON_NULL(TAG, doxm, ERROR);
403
404     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
405     //OxmType -- not Mandatory
406     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
407     {
408         CborValue oxmType;
409
410         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
411         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
412         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
413
414         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
415         VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
416
417         cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
418         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
419
420         int i = 0;
421         size_t len = 0;
422         while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
423         {
424             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
425                                                         &len, NULL);
426             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
427             cborFindResult = cbor_value_advance(&oxmType);
428             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
429         }
430     }
431
432     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
433     //Oxm -- not Mandatory
434     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
435     {
436         CborValue oxm;
437         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
438         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
439         VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
440
441         doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
442         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
443
444         cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
445         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
446
447         int i = 0;
448         while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
449         {
450             int tmp;
451
452             cborFindResult = cbor_value_get_int(&oxm, &tmp);
453             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
454             doxm->oxm[i++] = (OicSecOxm_t)tmp;
455             cborFindResult = cbor_value_advance(&oxm);
456             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
457         }
458
459         if (roParsed)
460         {
461             *roParsed = true;
462         }
463     }
464     else
465     {
466         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
467         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
468         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
469         doxm->oxmLen = gDoxm->oxmLen;
470         for (size_t i = 0; i < gDoxm->oxmLen; i++)
471         {
472             doxm->oxm[i] = gDoxm->oxm[i];
473         }
474     }
475
476     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
477     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
478     {
479         int oxmSel;
480
481         cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
482         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
483         doxm->oxmSel = (OicSecOxm_t)oxmSel;
484     }
485     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
486     {
487         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
488         doxm->oxmSel = gDoxm->oxmSel;
489     }
490
491     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
492     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
493     {
494         int sct;
495
496         cborFindResult = cbor_value_get_int(&doxmMap, &sct);
497         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
498         doxm->sct = (OicSecCredType_t)sct;
499
500         if (roParsed)
501         {
502             *roParsed = true;
503         }
504     }
505     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
506     {
507         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
508         doxm->sct = gDoxm->sct;
509     }
510
511     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
512     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
513     {
514         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
515         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
516     }
517     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
518     {
519         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
520         doxm->owned = gDoxm->owned;
521     }
522
523     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
524     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
525     {
526         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
527         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
528         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
529         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
530         OICFree(strUuid);
531         strUuid  = NULL;
532     }
533     else
534     {
535         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
536         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
537     }
538
539     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
540     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
541     {
542         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
543         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
544         ret = ConvertStrToUuid(strUuid , &doxm->owner);
545         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
546         OICFree(strUuid);
547         strUuid  = NULL;
548     }
549     else
550     {
551         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
552         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
553     }
554
555 #ifdef MULTIPLE_OWNER
556     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
557     if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
558     {
559         int mode = 0;
560         cborFindResult = cbor_value_get_int(&doxmMap, &mode);
561         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
562         if(NULL == doxm->mom)
563         {
564             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
565             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
566         }
567         doxm->mom->mode = (OicSecMomType_t)mode;
568     }
569     else if(NULL != gDoxm && NULL != gDoxm->mom)
570     {
571         // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
572         if(NULL == doxm->mom)
573         {
574             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
575             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
576         }
577         doxm->mom->mode = gDoxm->mom->mode;
578     }
579
580     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
581     if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
582     {
583         size_t subOwnerLen = 0;
584         CborValue subOwnerCbor;
585         cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
586         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
587         VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
588
589         cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
590         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
591
592         while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
593         {
594             OCStackResult convertRes = OC_STACK_ERROR;
595             OicSecSubOwner_t* subOwner = NULL;
596             char* strUuid = NULL;
597             size_t uuidLen = 0;
598
599             cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
600             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
601
602             subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
603             VERIFY_NON_NULL(TAG, subOwner, ERROR);
604
605             convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
606             VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
607             subOwner->status = MOT_STATUS_DONE;
608             LL_APPEND(doxm->subOwners, subOwner);
609
610             cborFindResult = cbor_value_advance(&subOwnerCbor);
611             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
612         }
613     }
614     else if(NULL != gDoxm && NULL != gDoxm->subOwners)
615     {
616         // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
617         OicSecSubOwner_t* subOwnerItor = NULL;
618         LL_FOREACH(gDoxm->subOwners, subOwnerItor)
619         {
620             OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
621             VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
622
623             memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
624             subOwnerId->status = MOT_STATUS_DONE;
625
626             LL_APPEND(doxm->subOwners, subOwnerId);
627         }
628     }
629 #endif //MULTIPLE_OWNER
630
631     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
632     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
633     {
634         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
635         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
636         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
637         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
638         OICFree(strUuid);
639         strUuid  = NULL;
640     }
641     else
642     {
643         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
644         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
645     }
646
647     *secDoxm = doxm;
648     ret = OC_STACK_OK;
649
650 exit:
651     if (CborNoError != cborFindResult)
652     {
653         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
654         DeleteDoxmBinData(doxm);
655         doxm = NULL;
656         *secDoxm = NULL;
657         ret = OC_STACK_ERROR;
658     }
659     return ret;
660 }
661
662 /**
663  * @todo document this function including why code might need to call this.
664  * The current suspicion is that it's not being called as much as it should.
665  */
666 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
667 {
668     bool bRet = false;
669
670     if (NULL != doxm)
671     {
672         // Convert Doxm data into CBOR for update to persistent storage
673         uint8_t *payload = NULL;
674         size_t size = 0;
675         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
676         if (payload && (OC_STACK_OK == res)
677             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
678         {
679                 bRet = true;
680         }
681         OICFree(payload);
682     }
683     else
684     {
685         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
686         {
687                 bRet = true;
688         }
689     }
690
691     return bRet;
692 }
693
694 static bool ValidateQuery(const char * query)
695 {
696     // Send doxm resource data if the state of doxm resource
697     // matches with the query parameters.
698     // else send doxm resource data as NULL
699     // TODO Remove this check and rely on Policy Engine
700     // and Provisioning Mode to enforce provisioning-state
701     // access rules. Eventually, the PE and PM code will
702     // not send a request to the /doxm Entity Handler at all
703     // if it should not respond.
704     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
705     if(NULL == gDoxm)
706     {
707         return false;
708     }
709
710     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
711     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
712     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
713     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
714     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
715     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
716 #ifdef MULTIPLE_OWNER
717     bool bMotQry = false;         // does querystring contains 'mom' and 'owned' query ?
718     bool bMotMatch = false;       // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
719 #endif //MULTIPLE_OWNER
720
721     OicParseQueryIter_t parseIter = {.attrPos = NULL};
722
723     ParseQueryIterInit((unsigned char*)query, &parseIter);
724
725     while (GetNextQuery(&parseIter))
726     {
727         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
728         {
729             bOwnedQry = true;
730             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
731                     (gDoxm->owned))
732             {
733                 bOwnedMatch = true;
734             }
735             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
736                     && (!gDoxm->owned))
737             {
738                 bOwnedMatch = true;
739             }
740         }
741
742 #ifdef MULTIPLE_OWNER
743         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
744         {
745             bMotQry = true;
746             OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
747             if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
748             {
749                 if(GetNextQuery(&parseIter))
750                 {
751                     if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
752                     {
753                         if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
754                                 (gDoxm->owned))
755                         {
756                             bMotMatch = true;
757                         }
758                     }
759                 }
760             }
761             return bMotMatch;
762         }
763 #endif //MULTIPLE_OWNER
764
765         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
766         {
767             bDeviceIDQry = true;
768             OicUuid_t subject = {.id={0}};
769
770             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
771             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
772             {
773                 bDeviceIDMatch = true;
774             }
775         }
776
777         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
778         {
779             bInterfaceQry = true;
780             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
781             {
782                 bInterfaceMatch = true;
783             }
784             return (bInterfaceQry ? bInterfaceMatch: true);
785         }
786     }
787
788 #ifdef MULTIPLE_OWNER
789     return ((bOwnedQry ? bOwnedMatch : true) &&
790             (bDeviceIDQry ? bDeviceIDMatch : true) &&
791             (bMotQry ? bMotMatch : true));
792 #else
793     return ((bOwnedQry ? bOwnedMatch : true) &&
794             (bDeviceIDQry ? bDeviceIDMatch : true));
795 #endif //MULTIPLE_OWNER
796 }
797
798 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
799 {
800     OCEntityHandlerResult ehRet = OC_EH_OK;
801
802     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
803
804     //Checking if Get request is a query.
805     if (ehRequest->query)
806     {
807         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
808         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
809         if (!ValidateQuery(ehRequest->query))
810         {
811             ehRet = OC_EH_ERROR;
812         }
813     }
814
815     /*
816      * For GET or Valid Query request return doxm resource CBOR payload.
817      * For non-valid query return NULL json payload.
818      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
819      * return valid doxm resource json.
820      */
821     uint8_t *payload = NULL;
822     size_t size = 0;
823
824     if (ehRet == OC_EH_OK)
825     {
826         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
827         {
828             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
829         }
830     }
831
832     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
833     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
834
835     // Send response payload to request originator
836     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
837                    OC_EH_OK : OC_EH_ERROR;
838
839     OICFree(payload);
840
841     return ehRet;
842 }
843
844 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
845 {
846     if(src && dst)
847    {
848         // update oxmsel
849         dst->oxmSel = src->oxmSel;
850
851         //update owner
852         memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
853
854         //update rowner
855         memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
856
857         //update deviceuuid
858         memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
859
860         //Update owned status
861         if(dst->owned != src->owned)
862         {
863             dst->owned = src->owned;
864         }
865
866 #ifdef MULTIPLE_OWNER
867         if(src->mom)
868         {
869             OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
870             if(NULL == dst->mom)
871             {
872                 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
873                 if(NULL != dst->mom)
874                 {
875                     dst->mom->mode = src->mom->mode;
876                 }
877             }
878         }
879 #endif //MULTIPLE_OWNER
880     }
881 }
882
883 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
884 #ifdef MULTIPLE_OWNER
885 /**
886  * Callback function to handle MOT DTLS handshake result.
887  * @param[out]   object           remote device information.
888  * @param[out]   errorInfo        CA Error information.
889  */
890 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *object,
891                                 const CAErrorInfo_t *errorInfo)
892 {
893     OIC_LOG(DEBUG, TAG, "IN MultipleOwnerDTLSHandshakeCB");
894
895     if(CA_STATUS_OK == errorInfo->result)
896     {
897         const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(object);
898         if(authenticatedSubOwnerInfo)
899         {
900             if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
901                             authenticatedSubOwnerInfo->identity.id_length))
902             {
903                 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
904                 return;
905             }
906
907             OicSecSubOwner_t* subOwnerInst = NULL;
908             LL_FOREACH(gDoxm->subOwners, subOwnerInst)
909             {
910                 if(0 == memcmp(subOwnerInst->uuid.id,
911                                authenticatedSubOwnerInfo->identity.id,
912                                authenticatedSubOwnerInfo->identity.id_length))
913                 {
914                     break;
915                 }
916             }
917
918             if(NULL == subOwnerInst)
919             {
920                 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
921                 if(subOwnerInst)
922                 {
923                     char* strUuid = NULL;
924                     memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
925                            authenticatedSubOwnerInfo->identity.id_length);
926                     if(OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
927                     {
928                         OIC_LOG(ERROR, TAG, "Failed to allocate memory.");
929                         return;
930                     }
931                     OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
932                     OICFree(strUuid);
933                     LL_APPEND(gDoxm->subOwners, subOwnerInst);
934                     if(!UpdatePersistentStorage(gDoxm))
935                     {
936                         OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
937                     }
938                 }
939             }
940         }
941     }
942
943     if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
944     {
945         OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
946     }
947
948     OIC_LOG(DEBUG, TAG, "OUT MultipleOwnerDTLSHandshakeCB");
949 }
950 #endif //MULTIPLE_OWNER
951 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
952
953 /**
954  * Function to validate oxmsel with oxms.
955  *
956  * @param[in] supportedMethods   Array of supported methods
957  * @param[in] numberOfMethods   number of supported methods
958  * @param[out]  selectedMethod         Selected methods
959  * @return  TRUE on success
960  */
961 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
962         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
963 {
964     bool isValidOxmsel = false;
965
966     OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
967     if (numberOfMethods == 0 || !supportedMethods)
968     {
969         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
970         return isValidOxmsel;
971     }
972
973     for (size_t i = 0; i < numberOfMethods; i++)
974     {
975             if (*selectedMethod  == supportedMethods[i])
976             {
977                 isValidOxmsel = true;
978                 break;
979             }
980     }
981     if (!isValidOxmsel)
982     {
983         OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
984         return isValidOxmsel;
985     }
986
987     OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
988
989     return isValidOxmsel;
990 }
991
992 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
993 {
994     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
995     OCEntityHandlerResult ehRet = OC_EH_ERROR;
996     OicUuid_t emptyOwner = {.id = {0} };
997     static uint16_t previousMsgId = 0;
998
999     /*
1000      * Convert CBOR Doxm data into binary. This will also validate
1001      * the Doxm data received.
1002      */
1003     OicSecDoxm_t *newDoxm = NULL;
1004
1005     if (ehRequest->payload)
1006     {
1007         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1008         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1009         bool roParsed = false;
1010         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1011         if (newDoxm && OC_STACK_OK == res)
1012         {
1013             // Check request on RO property
1014             if (true == roParsed)
1015             {
1016                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1017                 ehRet = OC_EH_NOT_ACCEPTABLE;
1018                 goto exit;
1019             }
1020
1021             // in owned state
1022             if (true == gDoxm->owned)
1023             {
1024                 //Update gDoxm based on newDoxm
1025                 updateWriteableProperty(newDoxm, gDoxm);
1026
1027 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1028 #ifdef MULTIPLE_OWNER
1029                 //handle mom
1030                 if(gDoxm->mom)
1031                 {
1032                     if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1033                     {
1034                         CAResult_t caRes = CA_STATUS_FAILED;
1035                         if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1036                         {
1037                             caRes = CAEnableAnonECDHCipherSuite(false);
1038                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1039                             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1040
1041                             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, ehRequest->devAddr.adapter);
1042                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1043                             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1044
1045                             //Set the device id to derive temporal PSK
1046                             SetUuidForPinBasedOxm(&gDoxm->deviceID);
1047                         }
1048                         else
1049                         {
1050                             OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1051                         }
1052
1053                         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1054                     }
1055                     else
1056                     {
1057                         //if MOM is disabled, revert the DTLS handshake callback
1058                         if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1059                         {
1060                             OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1061                         }
1062                     }
1063                 }
1064
1065                 if(newDoxm->subOwners)
1066                 {
1067                     OicSecSubOwner_t* subowner = NULL;
1068                     OicSecSubOwner_t* temp = NULL;
1069
1070                     OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1071
1072                     if(gDoxm->subOwners)
1073                     {
1074                         LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1075                         {
1076                             LL_DELETE(gDoxm->subOwners, subowner);
1077                             OICFree(subowner);
1078                         }
1079                     }
1080
1081                     subowner = NULL;
1082                     temp = NULL;
1083                     LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1084                     {
1085                         LL_DELETE(newDoxm->subOwners, subowner);
1086                         LL_APPEND(gDoxm->subOwners, subowner);
1087                     }
1088                 }
1089 #endif //MULTIPLE_OWNER
1090 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1091
1092                 //Update new state in persistent storage
1093                 if (UpdatePersistentStorage(gDoxm) == true)
1094                 {
1095                     ehRet = OC_EH_OK;
1096                 }
1097                 else
1098                 {
1099                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1100                     ehRet = OC_EH_ERROR;
1101                 }
1102                 goto exit;
1103             }
1104
1105             // in unowned state
1106             if ((false == gDoxm->owned) && (false == newDoxm->owned))
1107             {
1108                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1109                 {
1110                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1111                     ehRet = OC_EH_NOT_ACCEPTABLE;
1112                     goto exit;
1113                 }
1114
1115                 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1116                 {
1117                     /*
1118                      * If current state of the device is un-owned, enable
1119                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1120                      * tool can initiate JUST_WORKS ownership transfer process.
1121                      */
1122                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1123                     {
1124                         gDoxm->oxmSel = newDoxm->oxmSel;
1125                         //Update new state in persistent storage
1126                         if ((UpdatePersistentStorage(gDoxm) == true))
1127                         {
1128                             ehRet = OC_EH_OK;
1129                         }
1130                         else
1131                         {
1132                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1133                             ehRet = OC_EH_ERROR;
1134                         }
1135                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
1136 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1137                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1138 #endif // __WITH_DTLS__ or __WITH_TLS__
1139                         goto exit;
1140                     }
1141                     else
1142                     {
1143 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1144                         //Save the owner's UUID to derive owner credential
1145                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1146
1147                         // Update new state in persistent storage
1148                         if (true == UpdatePersistentStorage(gDoxm))
1149                         {
1150                             ehRet = OC_EH_OK;
1151                         }
1152                         else
1153                         {
1154                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1155                             ehRet = OC_EH_ERROR;
1156                         }
1157
1158                         /*
1159                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
1160                          * in owned state.
1161                          */
1162                         CAResult_t caRes = CA_STATUS_OK;
1163                         caRes = CAEnableAnonECDHCipherSuite(false);
1164                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1165                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1166
1167                         //In case of Mutual Verified Just-Works, verify mutualVerifNum
1168                         if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1169                                         previousMsgId != ehRequest->messageID)
1170                         {
1171                             uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1172                             uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1173                             OicUuid_t deviceID = {.id = {0}};
1174
1175                             //Generate mutualVerifNum
1176                             OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1177
1178                             char label[LABEL_LEN] = {0};
1179                             snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1180                             if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1181                             {
1182                                 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1183                                 ehRet = OC_EH_ERROR;
1184                                 goto exit;
1185
1186                             }
1187
1188                             CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1189                                     (uint8_t *)label,
1190                                     strlen(label),
1191                                     gDoxm->owner.id, sizeof(gDoxm->owner.id),
1192                                     gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1193                                     preMutualVerifNum, OWNER_PSK_LENGTH_128);
1194                             if (CA_STATUS_OK != pskRet)
1195                             {
1196                                 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1197                                 ehRet = OC_EH_ERROR;
1198                                 goto exit;
1199
1200                             }
1201
1202                             memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1203                                     sizeof(mutualVerifNum));
1204
1205                             //Wait for user confirmation
1206                             if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1207                             {
1208                                 ehRet = OC_EH_NOT_ACCEPTABLE;
1209                             }
1210                             else
1211                             {
1212                                 ehRet = OC_EH_OK;
1213                             }
1214                         }
1215
1216 #endif // __WITH_DTLS__ or __WITH_TLS__
1217                     }
1218                 }
1219                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1220                 {
1221                     /*
1222                      * If current state of the device is un-owned, enable
1223                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1224                      * tool can initiate JUST_WORKS ownership transfer process.
1225                      */
1226                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1227                     {
1228                         gDoxm->oxmSel = newDoxm->oxmSel;
1229                         //Update new state in persistent storage
1230                         if ((UpdatePersistentStorage(gDoxm) == true))
1231                         {
1232                             ehRet = OC_EH_OK;
1233                         }
1234                         else
1235                         {
1236                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1237                             ehRet = OC_EH_ERROR;
1238                         }
1239
1240 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1241                         CAResult_t caRes = CA_STATUS_OK;
1242
1243                         caRes = CAEnableAnonECDHCipherSuite(false);
1244                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1245                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1246
1247                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
1248                                                     ehRequest->devAddr.adapter);
1249                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1250
1251                         char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1252                          //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
1253                         if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
1254                         {
1255                             if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1256                             {
1257                                 //Set the device id to derive temporal PSK
1258                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1259
1260                                 /**
1261                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1262                                  * Credential should not be saved into SVR.
1263                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1264                                  */
1265                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1266                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1267                                 ehRet = OC_EH_OK;
1268                             }
1269                             else
1270                             {
1271                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1272                                 ehRet = OC_EH_ERROR;
1273                             }
1274                         }
1275                         else if(OC_ADAPTER_TCP == ehRequest->devAddr.adapter)
1276                         {
1277                             if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1278                             {
1279                                 //Set the device id to derive temporal PSK
1280                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1281
1282                                 /**
1283                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1284                                  * Credential should not be saved into SVR.
1285                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1286                                  */
1287                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1288                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1289                                 ehRet = OC_EH_OK;
1290                             }
1291                             else
1292                             {
1293                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1294                                 ehRet = OC_EH_ERROR;
1295                             }
1296
1297                         }
1298 #endif // __WITH_DTLS__ or __WITH_TLS__
1299                     }
1300 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1301                     else
1302                     {
1303                         //Save the owner's UUID to derive owner credential
1304                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1305
1306                         //Update new state in persistent storage
1307                         if (UpdatePersistentStorage(gDoxm) == true)
1308                         {
1309                             ehRet = OC_EH_OK;
1310                         }
1311                         else
1312                         {
1313                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1314                             ehRet = OC_EH_ERROR;
1315                         }
1316                     }
1317 #endif // __WITH_DTLS__ or __WITH_TLS__
1318                 }
1319 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1320                 else if (OIC_MANUFACTURER_CERTIFICATE ==  newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1321                 {
1322                     //Save the owner's UUID to derive owner credential
1323                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1324                     gDoxm->oxmSel = newDoxm->oxmSel;
1325                     //Update new state in persistent storage
1326                     if (UpdatePersistentStorage(gDoxm))
1327                     {
1328                         ehRet = OC_EH_OK;
1329                     }
1330                     else
1331                     {
1332                         OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1333                         ehRet = OC_EH_ERROR;
1334                     }
1335                     CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1336                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1337                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1338
1339                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1340                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1341
1342                     //In case of Confirm Manufacturer Cert, get user confirmation
1343                     if (OIC_CON_MFG_CERT == newDoxm->oxmSel && false == newDoxm->owned &&
1344                                     previousMsgId != ehRequest->messageID &&
1345                                     memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1346                     {
1347                         if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1348                         {
1349                             ehRet = OC_EH_NOT_ACCEPTABLE;
1350                         }
1351                         else
1352                         {
1353                             ehRet = OC_EH_OK;
1354                         }
1355                     }
1356
1357
1358                 }
1359 #endif // __WITH_DTLS__ or __WITH_TLS__
1360             }
1361
1362             /*
1363              * When current state of the device is un-owned and Provisioning
1364              * Tool is attempting to change the state to 'Owned' with a
1365              * qualified value for the field 'Owner'
1366              */
1367             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1368                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1369             {
1370                 //Change the SVR's resource owner as owner device.
1371                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1372                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1373                 {
1374                     ehRet = OC_EH_ERROR;
1375                     goto exit;
1376                 }
1377                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1378                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1379                 {
1380                     ehRet = OC_EH_ERROR;
1381                     goto exit;
1382                 }
1383                 ownerRes = SetCredRownerId(&gDoxm->owner);
1384                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1385                 {
1386                     ehRet = OC_EH_ERROR;
1387                     goto exit;
1388                 }
1389                 ownerRes = SetPstatRownerId(&gDoxm->owner);
1390                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1391                 {
1392                     ehRet = OC_EH_ERROR;
1393                     goto exit;
1394                 }
1395                 ownerRes = SetDpairingRownerId(&gDoxm->owner);
1396                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1397                 {
1398                     ehRet = OC_EH_ERROR;
1399                     goto exit;
1400                 }
1401                 ownerRes = SetPconfRownerId(&gDoxm->owner);
1402                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1403                 {
1404                     ehRet = OC_EH_ERROR;
1405                     goto exit;
1406                 }
1407
1408                 gDoxm->owned = true;
1409                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1410
1411                 // Update new state in persistent storage
1412                 if (UpdatePersistentStorage(gDoxm))
1413                 {
1414                     //Update default ACE of security resource to prevent anonymous user access.
1415                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
1416                     {
1417                         ehRet = OC_EH_OK;
1418                     }
1419                     else
1420                     {
1421                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1422                         ehRet = OC_EH_ERROR;
1423                     }
1424                 }
1425                 else
1426                 {
1427                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1428                     ehRet = OC_EH_ERROR;
1429                 }
1430 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1431                 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel)
1432                 {
1433                     CAregisterPkixInfoHandler(GetPkixInfo);
1434                     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1435                 }
1436 #endif // __WITH_DTLS__ or __WITH_TLS__
1437             }
1438         }
1439     }
1440
1441 exit:
1442     if(OC_EH_OK != ehRet)
1443     {
1444
1445         /*
1446          * If some error is occured while ownership transfer,
1447          * ownership transfer related resource should be revert back to initial status.
1448         */
1449         if(gDoxm)
1450         {
1451             if(!gDoxm->owned)
1452             {
1453                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1454
1455                 if((OC_ADAPTER_IP == ehRequest->devAddr.adapter && previousMsgId != ehRequest->messageID)
1456                    || OC_ADAPTER_TCP == ehRequest->devAddr.adapter)
1457                 {
1458                     RestoreDoxmToInitState();
1459                     RestorePstatToInitState();
1460                     OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1461                 }
1462             }
1463         }
1464         else
1465         {
1466             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1467         }
1468     }
1469     else
1470     {
1471         previousMsgId = ehRequest->messageID++;
1472     }
1473
1474     //Send payload to request originator
1475     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1476                    OC_EH_OK : OC_EH_ERROR;
1477
1478     DeleteDoxmBinData(newDoxm);
1479
1480     return ehRet;
1481 }
1482
1483 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1484                                         OCEntityHandlerRequest * ehRequest,
1485                                         void* callbackParam)
1486 {
1487     (void)callbackParam;
1488     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1489
1490     if(NULL == ehRequest)
1491     {
1492         return ehRet;
1493     }
1494
1495     if (flag & OC_REQUEST_FLAG)
1496     {
1497         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1498
1499         switch (ehRequest->method)
1500         {
1501             case OC_REST_GET:
1502                 ehRet = HandleDoxmGetRequest(ehRequest);
1503                 break;
1504
1505             case OC_REST_POST:
1506                 ehRet = HandleDoxmPostRequest(ehRequest);
1507                 break;
1508
1509             default:
1510                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1511                                OC_EH_OK : OC_EH_ERROR;
1512                 break;
1513         }
1514     }
1515
1516     return ehRet;
1517 }
1518
1519 OCStackResult CreateDoxmResource()
1520 {
1521     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1522                                          OIC_RSRC_TYPE_SEC_DOXM,
1523                                          OC_RSRVD_INTERFACE_DEFAULT,
1524                                          OIC_RSRC_DOXM_URI,
1525                                          DoxmEntityHandler,
1526                                          NULL,
1527                                          OC_SECURE |
1528                                          OC_DISCOVERABLE);
1529
1530     if (OC_STACK_OK != ret)
1531     {
1532         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1533         DeInitDoxmResource();
1534     }
1535     return ret;
1536 }
1537
1538 /**
1539  * Checks if DeviceID is generated during provisioning for the new device.
1540  * If DeviceID is NULL then generates the new DeviceID.
1541  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1542  */
1543 static OCStackResult CheckDeviceID()
1544 {
1545     OCStackResult ret = OC_STACK_ERROR;
1546     bool validId = false;
1547     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1548     {
1549         if (gDoxm->deviceID.id[i] != 0)
1550         {
1551             validId = true;
1552             break;
1553         }
1554     }
1555
1556     if (!validId)
1557     {
1558         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1559         {
1560             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1561             return ret;
1562         }
1563         ret = OC_STACK_OK;
1564
1565         if (!UpdatePersistentStorage(gDoxm))
1566         {
1567             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1568             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1569         }
1570     }
1571     else
1572     {
1573         ret = OC_STACK_OK;
1574     }
1575     return ret;
1576 }
1577
1578 /**
1579  * Get the default value.
1580  *
1581  * @return the default value of doxm, @ref OicSecDoxm_t.
1582  */
1583 static OicSecDoxm_t* GetDoxmDefault()
1584 {
1585     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1586     return &gDefaultDoxm;
1587 }
1588
1589 const OicSecDoxm_t* GetDoxmResourceData()
1590 {
1591     return gDoxm;
1592 }
1593
1594 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1595 /**
1596  * Internal API to prepare MOT
1597  */
1598 static void PrepareMOT(const OicSecDoxm_t* doxm)
1599 {
1600     OIC_LOG(INFO, TAG, "IN PrepareMOT");
1601     VERIFY_NON_NULL(TAG, doxm, ERROR);
1602
1603     if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1604     {
1605         CAResult_t caRes = CA_STATUS_FAILED;
1606
1607         OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1608
1609         if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1610         {
1611             caRes = CAEnableAnonECDHCipherSuite(false);
1612             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1613             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1614
1615             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP);
1616             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1617 #ifdef __WITH_TLS__
1618             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_TCP);
1619             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1620 #endif
1621             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1622
1623             //Set the device id to derive temporal PSK
1624             SetUuidForPinBasedOxm(&doxm->deviceID);
1625         }
1626         else
1627         {
1628             OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1629             return;
1630         }
1631
1632         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1633     }
1634
1635     OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1636     return;
1637 exit:
1638     OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1639 }
1640 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1641
1642 OCStackResult InitDoxmResource()
1643 {
1644     OCStackResult ret = OC_STACK_ERROR;
1645
1646     //Read DOXM resource from PS
1647     uint8_t *data = NULL;
1648     size_t size = 0;
1649     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1650     // If database read failed
1651     if (OC_STACK_OK != ret)
1652     {
1653        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1654     }
1655     if (data)
1656     {
1657        // Read DOXM resource from PS
1658        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1659     }
1660     /*
1661      * If SVR database in persistent storage got corrupted or
1662      * is not available for some reason, a default doxm is created
1663      * which allows user to initiate doxm provisioning again.
1664      */
1665      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1666     {
1667         gDoxm = GetDoxmDefault();
1668     }
1669
1670     //In case of the server is shut down unintentionally, we should initialize the owner
1671     if(false == gDoxm->owned)
1672     {
1673         OicUuid_t emptyUuid = {.id={0}};
1674         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1675     }
1676
1677     ret = CheckDeviceID();
1678     if (ret == OC_STACK_OK)
1679     {
1680         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1681         //Instantiate 'oic.sec.doxm'
1682         ret = CreateDoxmResource();
1683     }
1684     else
1685     {
1686         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1687     }
1688     OICFree(data);
1689
1690 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1691     //if MOT is enabled, MOT should be prepared.
1692     if(gDoxm && gDoxm->owned)
1693     {
1694         PrepareMOT(gDoxm);
1695     }
1696 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1697
1698     return ret;
1699 }
1700
1701 OCStackResult DeInitDoxmResource()
1702 {
1703     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1704     if (gDoxm  != &gDefaultDoxm)
1705     {
1706         DeleteDoxmBinData(gDoxm);
1707     }
1708     gDoxm = NULL;
1709
1710     if (OC_STACK_OK == ret)
1711     {
1712         return OC_STACK_OK;
1713     }
1714     else
1715     {
1716         return OC_STACK_ERROR;
1717     }
1718 }
1719
1720 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1721 {
1722     if (deviceID && gDoxm)
1723     {
1724        *deviceID = gDoxm->deviceID;
1725         return OC_STACK_OK;
1726     }
1727     return OC_STACK_ERROR;
1728 }
1729
1730 OCStackResult GetDoxmIsOwned(bool *isOwned)
1731 {
1732     if (isOwned && gDoxm)
1733     {
1734        *isOwned = gDoxm->owned;
1735         return OC_STACK_OK;
1736     }
1737     return OC_STACK_ERROR;
1738 }
1739
1740 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1741 {
1742     bool isPT = false;
1743
1744     if(NULL == deviceID)
1745     {
1746         return OC_STACK_INVALID_PARAM;
1747     }
1748     if(NULL == gDoxm)
1749     {
1750         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1751         return OC_STACK_NO_RESOURCE;
1752     }
1753
1754     //Check the device's OTM state
1755
1756 #ifdef __WITH_DTLS__
1757     //for normal device.
1758     if(true == gDoxm->owned &&
1759        memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
1760     {
1761         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1762         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1763         return OC_STACK_ERROR;
1764     }
1765 #endif //__WITH_DTLS
1766
1767     //Save the previous UUID
1768     OicUuid_t tempUuid;
1769     memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1770
1771     //Change the UUID
1772     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1773     if(isPT)
1774     {
1775         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1776         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1777     }
1778
1779     //Update PS
1780     if(!UpdatePersistentStorage(gDoxm))
1781     {
1782         //revert UUID in case of update error
1783         memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1784         if(isPT)
1785         {
1786             memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1787             memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1788         }
1789
1790         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1791         return OC_STACK_ERROR;
1792     }
1793     return OC_STACK_OK;
1794 }
1795
1796 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1797 {
1798     OCStackResult retVal = OC_STACK_ERROR;
1799     if (gDoxm)
1800     {
1801         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1802             gDoxm->owned);
1803         if (gDoxm->owned)
1804         {
1805             *devownerid = gDoxm->owner;
1806             retVal = OC_STACK_OK;
1807         }
1808     }
1809     return retVal;
1810 }
1811
1812 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1813 {
1814     OCStackResult retVal = OC_STACK_ERROR;
1815     if (gDoxm)
1816     {
1817         if( gDoxm->owned )
1818         {
1819             *rowneruuid = gDoxm->rownerID;
1820                     retVal = OC_STACK_OK;
1821         }
1822     }
1823     return retVal;
1824 }
1825
1826 #ifdef MULTIPLE_OWNER
1827 /**
1828  * Compare the UUID to SubOwner.
1829  *
1830  * @param[in] uuid device UUID
1831  *
1832  * @return true if context->subjectId exist subowner list, else false.
1833  */
1834 bool IsSubOwner(const OicUuid_t* uuid)
1835 {
1836     bool retVal = false;
1837
1838     if (NULL == uuid)
1839     {
1840         return retVal;
1841     }
1842
1843     if (gDoxm && gDoxm->subOwners)
1844     {
1845         if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
1846         {
1847             return false;
1848         }
1849
1850         OicSecSubOwner_t* subOwner = NULL;
1851         LL_FOREACH(gDoxm->subOwners, subOwner)
1852         {
1853             if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
1854             {
1855                 return true;
1856             }
1857         }
1858     }
1859     return retVal;
1860 }
1861 #endif //MULTIPLE_OWNER
1862
1863 /**
1864  * Function to restore doxm resurce to initial status.
1865  * This function will use in case of error while ownership transfer
1866  */
1867 void RestoreDoxmToInitState()
1868 {
1869     if(gDoxm)
1870     {
1871         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1872
1873         OicUuid_t emptyUuid = {.id={0}};
1874         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1875         gDoxm->owned = false;
1876         gDoxm->oxmSel = OIC_JUST_WORKS;
1877
1878         if(!UpdatePersistentStorage(gDoxm))
1879         {
1880             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1881         }
1882     }
1883 }