Merge branch 'master' into cloud-interface
[platform/upstream/iotivity.git] / resource / csdk / security / src / dpairingresource.c
1 /* *****************************************************************
2  *
3  * Copyright 2016 Samsung Electronics 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
21 #include <stdlib.h>
22 #include <string.h>
23 #include "ocstack.h"
24 #include "logger.h"
25 #include "oic_malloc.h"
26 #include "oic_string.h"
27 #include "cJSON.h"
28 #include "base64.h"
29 #include "resourcemanager.h"
30 #include "dpairingresource.h"
31 #include "psinterface.h"
32 #include "utlist.h"
33 #include "srmresourcestrings.h"
34 #include "cainterface.h"
35 #include "doxmresource.h"
36 #include "pconfresource.h"
37 #include "credresource.h"
38 #include "aclresource.h"
39 #include "srmutility.h"
40 #include "ocserverrequest.h"
41 #include "ocpayloadcbor.h"
42 #include "ocpayload.h"
43 #include "payload_logging.h"
44 #include <stdlib.h>
45 #ifdef HAVE_STRINGS_H
46 #include <strings.h>
47 #endif
48
49 #ifdef __WITH_DTLS__
50 #include "global.h"
51 #endif
52
53 #define TAG  "SRM-DPAIRING"
54
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 = 1024;
58
59 /** Max cbor size payload. */
60 static const uint16_t CBOR_MAX_SIZE = 4400;
61
62 /** DOXM Map size - Number of mandatory items. */
63 static const uint8_t DPAIR_MAP_SIZE = 3;
64
65 static OicSecDpairing_t     *gDpair = NULL;
66 static OCResourceHandle   gDpairHandle = NULL;
67 static OicSecDpairing_t      gDefaultDpair =
68 {
69     PRM_NOT_ALLOWED,       /* OicSecPrm_t spm */
70     {.id = {0}},                   /* OicUuid_t pdeviceID */
71     {.id = {0}},                   /* OicUuid_t rowner */
72 };
73
74 void DeleteDpairingBinData(OicSecDpairing_t* dpair)
75 {
76     if (dpair)
77     {
78         //Clean dpairing itself
79         OICFree(dpair);
80     }
81 }
82
83 /**
84  * Get the default value.
85  * @retval  the gDefaultDpair pointer;
86  */
87 static OicSecDpairing_t* GetDpairingDefault()
88 {
89     OIC_LOG (DEBUG, TAG, "GetDpairingDefault");
90
91     return &gDefaultDpair;
92 }
93
94 /**
95  * This method is used by SRM to retrieve Dpairing resource data..
96  */
97 void SetDpairingResourceOwner(OicUuid_t *rowner)
98 {
99     OIC_LOG (DEBUG, TAG, "SetDpairingResourceOwner");
100     if (gDpair)
101     {
102         memcpy(&gDpair->rownerID, rowner, sizeof(OicUuid_t));
103     }
104 }
105
106 #ifdef __WITH_DTLS__
107 /**
108  * Function to save PairingPSK.
109  *
110  * @param[in] endpoint   current endpoint.
111  * @param[in] peerDevID   peer device indentitiy.
112  * @param[in] isPairingServer   indicate if it generates PairingPSK for server or client.
113  *
114  * @return  OC_STACK_OK on success
115  */
116 OCStackResult SavePairingPSK(OCDevAddr *endpoint,
117             OicUuid_t *peerDevID, OicUuid_t *owner, bool isPairingServer)
118 {
119     OIC_LOG(DEBUG, TAG, "IN SavePairingPSK");
120
121     if(NULL == endpoint || NULL == peerDevID || NULL == owner)
122     {
123         OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
124         return OC_STACK_INVALID_PARAM;
125     }
126
127     OCStackResult res = OC_STACK_ERROR;
128
129     OicUuid_t ptDeviceID = {.id={0}};
130     if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
131     {
132         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
133         return res;
134     }
135
136     uint8_t pairingPSK[OWNER_PSK_LENGTH_128] = {0};
137     OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_RAW};
138
139     //Generating PairingPSK using OwnerPSK scheme
140     CAResult_t pskRet = CAGenerateOwnerPSK((const CAEndpoint_t *)endpoint,
141             (uint8_t *)OIC_RSRC_TYPE_SEC_DPAIRING,
142             strlen(OIC_RSRC_TYPE_SEC_DPAIRING),
143             (isPairingServer ? ptDeviceID.id : peerDevID->id), sizeof(OicUuid_t), // server
144             (isPairingServer ? peerDevID->id : ptDeviceID.id), sizeof(OicUuid_t), // client
145             pairingPSK, OWNER_PSK_LENGTH_128);
146
147     if (CA_STATUS_OK == pskRet)
148     {
149         OIC_LOG(INFO, TAG, "pairingPSK dump:\n");
150         OIC_LOG_BUFFER(INFO, TAG, pairingPSK, OWNER_PSK_LENGTH_128);
151         //Generating new credential for direct-pairing client
152
153         OicSecCred_t *cred = GenerateCredential(peerDevID,
154                 SYMMETRIC_PAIR_WISE_KEY, NULL,
155                 &pairingKey, owner);
156         VERIFY_NON_NULL(TAG, cred, ERROR);
157
158         res = AddCredential(cred);
159         if(res != OC_STACK_OK)
160         {
161             DeleteCredList(cred);
162             return res;
163         }
164     }
165     else
166     {
167         OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
168     }
169
170     OIC_LOG(DEBUG, TAG, "OUT SavePairingPSK");
171 exit:
172     return res;
173 }
174 #endif // __WITH_DTLS__
175
176 OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size)
177 {
178     if (NULL == dpair || NULL == payload || NULL != *payload || NULL == size)
179     {
180         return OC_STACK_INVALID_PARAM;
181     }
182
183     size_t cborLen = *size;
184     if (0 == cborLen)
185     {
186         cborLen = CBOR_SIZE;
187     }
188
189     *payload = NULL;
190     *size = 0;
191
192     OCStackResult ret = OC_STACK_ERROR;
193
194     CborEncoder encoder;
195     CborEncoder dpairMap;
196
197     int64_t cborEncoderResult = CborNoError;
198     uint8_t mapSize = DPAIR_MAP_SIZE;
199
200     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
201     VERIFY_NON_NULL(TAG, outPayload, ERROR);
202     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
203
204     cborEncoderResult = cbor_encoder_create_map(&encoder, &dpairMap, mapSize);
205     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating DPAIRING Map");
206
207     //spm -- Mandatory
208     cborEncoderResult = cbor_encode_text_string(&dpairMap, OIC_JSON_SPM_NAME,
209         strlen(OIC_JSON_SPM_NAME));
210     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SPM name tag");
211     cborEncoderResult = cbor_encode_int(&dpairMap, dpair->spm);
212     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SPM value");
213
214     //PDEVICEID -- Mandatory
215     cborEncoderResult = cbor_encode_text_string(&dpairMap, OIC_JSON_PDEVICE_ID_NAME,
216         strlen(OIC_JSON_PDEVICE_ID_NAME));
217     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PDeviceID tag");
218     {
219         char *deviceId = NULL;
220         ret = ConvertUuidToStr(&dpair->pdeviceID, &deviceId);
221         VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
222         cborEncoderResult = cbor_encode_text_string(&dpairMap, deviceId, strlen(deviceId));
223         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode PDeviceID value");
224         OICFree(deviceId);
225     }
226
227     //ROWNER -- Mandatory
228     {
229         char *rowner = NULL;
230         cborEncoderResult = cbor_encode_text_string(&dpairMap, OIC_JSON_ROWNERID_NAME,
231             strlen(OIC_JSON_ROWNERID_NAME));
232         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROWNER tag");
233         ret = ConvertUuidToStr(&dpair->rownerID, &rowner);
234         VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
235         cborEncoderResult = cbor_encode_text_string(&dpairMap, rowner, strlen(rowner));
236         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Rowner ID value");
237         OICFree(rowner);
238     }
239
240     cborEncoderResult = cbor_encoder_close_container(&encoder, &dpairMap);
241     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close dpairMap");
242
243      if (CborNoError == cborEncoderResult)
244     {
245         *size = encoder.ptr - outPayload;
246         *payload = outPayload;
247         ret = OC_STACK_OK;
248     }
249
250 exit:
251     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
252     {
253        // reallocate and try again!
254        OICFree(outPayload);
255        // Since the allocated initial memory failed, double the memory.
256        cborLen += encoder.ptr - encoder.end;
257        cborEncoderResult = CborNoError;
258        ret = DpairingToCBORPayload(dpair, payload, &cborLen);
259        *size = cborLen;
260     }
261
262     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
263     {
264        OICFree(outPayload);
265        outPayload = NULL;
266        *payload = NULL;
267        *size = 0;
268        ret = OC_STACK_ERROR;
269     }
270
271     return ret;
272 }
273
274 OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
275                                 OicSecDpairing_t **secDpair)
276 {
277     if (NULL == cborPayload || NULL == secDpair || NULL != *secDpair || 0 == size)
278     {
279         return OC_STACK_INVALID_PARAM;
280     }
281
282     OCStackResult ret = OC_STACK_ERROR;
283     *secDpair = NULL;
284
285     CborValue dpairCbor = { .parser = NULL };
286     CborParser parser = { .end = NULL };
287     CborError cborFindResult = CborNoError;
288
289     cbor_parser_init(cborPayload, size, 0, &parser, &dpairCbor);
290     CborValue dpairMap = { .parser = NULL };
291     OicSecDpairing_t *dpair = NULL;
292     cborFindResult = cbor_value_enter_container(&dpairCbor, &dpairMap);
293     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering DPairing Map");
294
295     dpair = (OicSecDpairing_t *)OICCalloc(1, sizeof(*dpair));
296     VERIFY_NON_NULL(TAG, dpair, ERROR);
297
298     while (cbor_value_is_valid(&dpairMap) && cbor_value_is_text_string(&dpairMap))
299     {
300         char *name = NULL;
301         size_t len = 0;
302         CborType type = CborInvalidType;
303         cborFindResult = cbor_value_dup_text_string(&dpairMap, &name, &len, NULL);
304         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding tag name");
305         cborFindResult = cbor_value_advance(&dpairMap);
306         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a value in DPair map");
307
308         type = cbor_value_get_type(&dpairMap);
309         if (0 == strcmp(OIC_JSON_SPM_NAME, name) && cbor_value_is_integer(&dpairMap))
310         {
311             cborFindResult = cbor_value_get_int(&dpairMap, (int *) &dpair->spm);
312             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SPM Value");
313         }
314
315         if (0 == strcmp(OIC_JSON_PDEVICE_ID_NAME, name))
316         {
317             char *id = NULL;
318             cborFindResult = cbor_value_dup_text_string(&dpairMap, &id, &len, NULL);
319             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PDeviceID value");
320             ret = ConvertStrToUuid(id, &dpair->pdeviceID);
321             VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
322             OICFree(id);
323         }
324
325         if (0 == strcmp(OIC_JSON_ROWNERID_NAME, name))
326         {
327             char *id = NULL;
328             cborFindResult = cbor_value_dup_text_string(&dpairMap, &id, &len, NULL);
329             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RownerID value");
330             ret = ConvertStrToUuid(id, &dpair->rownerID);
331             VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
332             OICFree(id);
333         }
334
335         if (CborMapType != type && cbor_value_is_valid(&dpairMap))
336         {
337             cborFindResult = cbor_value_advance(&dpairMap);
338             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Dpair Map");
339         }
340         OICFree(name);
341     }
342
343     *secDpair = dpair;
344     ret = OC_STACK_OK;
345
346 exit:
347     if (CborNoError != cborFindResult)
348     {
349         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed");
350         DeleteDpairingBinData(dpair);
351         dpair = NULL;
352         *secDpair = NULL;
353         ret = OC_STACK_ERROR;
354     }
355     return ret;
356 }
357 /**
358  * Function to handle the handshake result in Direct-Pairing.
359  * This function will be invoked after DTLS handshake
360  * @param   endPoint  [IN] The remote endpoint.
361  * @param   errorInfo [IN] Error information from the endpoint.
362  * @return  NONE
363  */
364 void DPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
365 {
366     OIC_LOG_V(INFO, TAG, "IN DPairingDTLSHandshakeCB");
367
368     if(gDpair && endpoint && info)
369     {
370         OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
371                  endpoint->addr, endpoint->port, info->result);
372
373         if(CA_STATUS_OK == info->result)
374         {
375             OIC_LOG(INFO, TAG, "DPairingDTLSHandshakeCB - Connection success.");
376         }
377         else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
378         {
379             OIC_LOG(INFO, TAG, "DPairingDTLSHandshakeCB - Authentication failed");
380
381         }
382
383 #ifdef __WITH_DTLS__
384         CARegisterDTLSHandshakeCallback(NULL);
385 #endif // __WITH_DTLS__
386
387         // delete temporary key
388         RemoveCredential(&gDpair->pdeviceID);
389     }
390
391     OIC_LOG_V(INFO, TAG, "OUT DPairingDTLSHandshakeCB");
392 }
393
394 static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerRequest * ehRequest)
395 {
396     OIC_LOG (DEBUG, TAG, "Dpairing EntityHandle  processing POST request");
397     OCEntityHandlerResult ehRet = OC_EH_ERROR;
398     OicSecDpairing_t* newDpair = NULL;
399     OCStackResult res = OC_STACK_OK;
400
401     const OicSecPconf_t *pconf = GetPconfResourceData();
402     if (true == pconf->edp)
403     {
404         uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
405         size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
406         if (payload)
407         {
408             res = CBORPayloadToDpair(payload, size, &newDpair);
409         }
410     }
411     else
412     {
413         OIC_LOG (DEBUG, TAG, "EDP == false : Direct-Pairing Disabled");
414         ehRet = OC_EH_ERROR;
415     }
416
417     if (OC_STACK_OK == res && newDpair && false == IsPairedDevice(&newDpair->pdeviceID))
418     {
419         // Check if valid Post request
420         bool prmMached = false;
421         for (size_t i=0; i<pconf->prmLen; i++)
422         {
423             if (newDpair->spm == pconf->prm[i])
424             {
425                 prmMached = true;
426                 break;
427             }
428         }
429         OIC_LOG_V(DEBUG, TAG, "Parsed spm is %s", prmMached ? "valid" :
430                 "invalid, send error response");
431
432         // Update local Dpairing with new Dpairing & prepare dtls session
433         if (prmMached && '\0' != (char)newDpair->pdeviceID.id[0])
434         {
435             if(!gDpair)
436             {
437                 gDpair = GetDpairingDefault();
438             }
439             gDpair->spm = newDpair->spm;
440             memcpy(&gDpair->pdeviceID, &newDpair->pdeviceID, sizeof(OicUuid_t));
441             memcpy(&gDpair->rownerID, &pconf->rownerID, sizeof(OicUuid_t));
442
443 #ifdef __WITH_DTLS__
444             // Add temporary psk
445             OCStackResult res;
446             OicUuid_t subjectId = {.id={0}};
447             res = AddTmpPskWithPIN(&gDpair->pdeviceID,
448                            SYMMETRIC_PAIR_WISE_KEY,
449                            (char*)pconf->pin.val, DP_PIN_LENGTH,
450                            &gDpair->rownerID, &subjectId);
451             if(res != OC_STACK_OK ||
452                     memcmp(&gDpair->pdeviceID, &subjectId, sizeof(OicUuid_t)))
453             {
454                 OIC_LOG_V(ERROR, TAG, "Failed to save the temporal PSK : %d", res);
455                 goto exit;
456             }
457
458             // Prepare to establish a secure channel with Pin-based PSK cipher suite
459             if (CA_STATUS_OK != CAEnableAnonECDHCipherSuite(false) ||
460                 CA_STATUS_OK != CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256))
461             {
462                 OIC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256");
463                 goto exit;
464             }
465
466             if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DPairingDTLSHandshakeCB))
467             {
468                 OIC_LOG(WARNING, TAG, "DirectPairingHandler : Failed to register"
469                         " DTLS handshake callback.");
470                 goto exit;
471             }
472 #endif // __WITH_DTLS__
473
474             // should be lock /oic/sec/dpairing resource if Direct-Pairing starts normally ?
475             OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource created");
476
477             ehRet = OC_EH_RESOURCE_CREATED;
478         }
479         else
480         {
481             OIC_LOG(ERROR, TAG, "Error in request check");
482         }
483     }
484
485
486 #ifdef __WITH_DTLS__
487 exit:
488 #endif // __WITH_DTLS__
489
490     // Send payload to request originator
491     if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
492     {
493         ehRet = OC_EH_ERROR;
494         OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPostRequest");
495     }
496
497     if (OC_EH_ERROR == ehRet && gDpair)
498     {
499         RemoveCredential(&gDpair->pdeviceID);
500         gDpair = NULL;
501     }
502
503     DeleteDpairingBinData(newDpair);
504     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
505     return ehRet;
506 }
507
508 static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequest * ehRequest)
509 {
510     OIC_LOG (DEBUG, TAG, "Dpairing EntityHandle  processing PUT request (Comfirmation)");
511
512     OCEntityHandlerResult ehRet = OC_EH_ERROR;
513     OicSecDpairing_t* newDpair = NULL;
514     OCStackResult res = OC_STACK_OK;
515
516     const OicSecPconf_t *pconf = GetPconfResourceData();
517     if (true == pconf->edp)
518     {
519         uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
520         size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
521         if (payload)
522         {
523             res = CBORPayloadToDpair(payload, size, &newDpair);
524         }
525
526     }
527     else
528     {
529         OIC_LOG (DEBUG, TAG, "EDP == false : Direct-Pairing Disabled");
530         ehRet = OC_EH_ERROR;
531     }
532
533
534     if ((OC_STACK_OK == res) && gDpair && newDpair)
535     {
536         OIC_LOG(DEBUG, TAG, "Received direct-pairing finalization request");
537
538         // Check if valid Put request
539         VERIFY_SUCCESS(TAG, PRM_NOT_ALLOWED == newDpair->spm, ERROR);
540
541         const OicSecPconf_t *pconf = GetPconfResourceData();
542         VERIFY_NON_NULL(TAG, pconf, ERROR);
543
544 #ifdef __WITH_DTLS__
545         OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle;
546         VERIFY_SUCCESS(TAG, (request->devAddr.flags | OC_FLAG_SECURE), ERROR);
547
548         //Generate new credential
549         OIC_LOG_V(INFO, TAG, "SavePairingPSK for %s(%d)", request->devAddr.addr,
550                 request->devAddr.port);
551         OCStackResult res = SavePairingPSK(&request->devAddr, &newDpair->pdeviceID,
552                 (OicUuid_t *)&pconf->rownerID, true);
553         VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
554 #endif //__WITH_DTLS__
555
556         //Generate new acl
557         OicSecPdAcl_t *pdAcl;
558         LL_FOREACH(pconf->pdacls, pdAcl)
559         {
560             OicSecAcl_t* acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
561             VERIFY_NON_NULL(TAG, acl, ERROR);
562
563             OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
564             VERIFY_NON_NULL(TAG, ace, ERROR);
565
566             LL_APPEND(acl->aces, ace);
567
568             memcpy(&ace->subjectuuid, &gDpair->pdeviceID, sizeof(OicUuid_t));
569
570             for(size_t i = 0; i < pdAcl->resourcesLen; i++)
571             {
572                 OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
573                 VERIFY_NON_NULL(TAG, rsrc, ERROR);
574                 LL_APPEND(ace->resources, rsrc);
575
576                 //href
577                 rsrc->href = OICStrdup(pdAcl->resources[i]);
578
579                 // TODO: Append 'if' and 'rt' as workaround
580                 // if
581                 rsrc->interfaceLen = 1;
582                 rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char));
583                 VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR);
584                 rsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
585                 VERIFY_NON_NULL(TAG, (rsrc->interfaces[0]), ERROR);
586
587                 //rt
588                 rsrc->typeLen = 1;
589                 rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char));
590                 VERIFY_NON_NULL(TAG, (rsrc->types), ERROR);
591                 rsrc->types[0] = OICStrdup("oic.core");
592                 VERIFY_NON_NULL(TAG, (rsrc->types[0]), ERROR);
593             }
594
595             ace->permission = pdAcl->permission;
596
597             //Copy the validity
598             if(pdAcl->periods || pdAcl->recurrences)
599             {
600                 OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
601                 VERIFY_NON_NULL(TAG, validity, ERROR);
602
603                 if(pdAcl->periods && pdAcl->periods[0])
604                 {
605                     size_t periodLen = strlen(pdAcl->periods[0]) + 1;
606                     validity->period = (char*)OICMalloc(periodLen * sizeof(char));
607                     VERIFY_NON_NULL(TAG, (validity->period), ERROR);
608                     OICStrcpy(validity->period, periodLen, pdAcl->periods[0]);
609                 }
610
611                 if(pdAcl->recurrences && 0 < pdAcl->prdRecrLen)
612                 {
613                     validity->recurrenceLen = pdAcl->prdRecrLen;
614                     validity->recurrences = (char**)OICMalloc(sizeof(char*) * pdAcl->prdRecrLen);
615                     VERIFY_NON_NULL(TAG, (validity->recurrences), ERROR);
616
617                     for(size_t i = 0; i < pdAcl->prdRecrLen; i++)
618                     {
619                         size_t recurrenceLen = strlen(pdAcl->recurrences[i]) + 1;
620                         validity->recurrences[i] = (char*)OICMalloc(recurrenceLen  * sizeof(char));
621                         VERIFY_NON_NULL(TAG, (validity->recurrences[i]), ERROR);
622
623                         OICStrcpy(validity->recurrences[i], recurrenceLen, pdAcl->recurrences[i]);
624                     }
625                 }
626
627                 LL_APPEND(ace->validities, validity);
628             }
629
630             size_t size = 0;
631             uint8_t *payload = NULL;
632             if (OC_STACK_OK == AclToCBORPayload(acl, &payload, &size))
633             {
634                 InstallNewACL(payload, size);
635                 OICFree(payload);
636             }
637             DeleteACLList(acl);
638         }
639
640         //update pconf device list
641         AddPairedDevice(&newDpair->pdeviceID);
642
643         //Initialize dpairing resource
644         gDpair = NULL;
645
646         OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource updated,"
647                 "direct-pairing finalization success");
648         ehRet = OC_EH_OK;
649     }
650
651 exit:
652
653     //Send payload to request originator
654     if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
655     {
656         ehRet = OC_EH_ERROR;
657         OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPutRequest");
658     }
659
660     DeleteDpairingBinData(newDpair);
661     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
662     return ehRet;
663 }
664 /*
665  * This internal method is the entity handler for Dpairing resources and
666  * will handle REST request (GET/POST) for them.
667  */
668 OCEntityHandlerResult DpairingEntityHandler (OCEntityHandlerFlag flag,
669                                         OCEntityHandlerRequest * ehRequest,
670                                         void* callbackParameter)
671 {
672     OIC_LOG(DEBUG, TAG, "Received request DpairingEntityHandler");
673     (void)callbackParameter;
674     OCEntityHandlerResult ehRet = OC_EH_ERROR;
675
676     if (!ehRequest)
677     {
678         return ehRet;
679     }
680
681     if (flag & OC_REQUEST_FLAG)
682     {
683         OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
684         switch (ehRequest->method)
685         {
686             case OC_REST_GET:
687                 break;
688
689             case OC_REST_POST:
690                 ehRet = HandleDpairingPostRequest(ehRequest);
691                 break;
692
693             case OC_REST_PUT:
694                 ehRet = HandleDpairingPutRequest(ehRequest);
695                 break;
696
697             case OC_REST_DELETE:
698                 break;
699
700             default:
701                 ehRet = OC_EH_ERROR;
702                 SendSRMResponse(ehRequest, ehRet, NULL, 0);
703         }
704     }
705
706     return ehRet;
707 }
708
709 /*
710  * This internal method is used to create '/oic/sec/dpairing' resource.
711  */
712 OCStackResult CreateDpairingResource()
713 {
714     OCStackResult ret;
715
716     ret = OCCreateResource(&gDpairHandle,
717                            OIC_RSRC_TYPE_SEC_DPAIRING,
718                            OC_RSRVD_INTERFACE_DEFAULT,
719                            OIC_RSRC_DPAIRING_URI,
720                            DpairingEntityHandler,
721                            NULL,
722                            OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
723
724     if (OC_STACK_OK != ret)
725     {
726         OIC_LOG (ERROR, TAG, "Unable to instantiate Dpairing resource");
727         DeInitDpairingResource();
728     }
729     return ret;
730 }
731
732 /**
733  * Initialize Dpairing resource by loading data from persistent storage.
734  *
735  * @retval  OC_STACK_OK for Success, otherwise some error value
736  */
737 OCStackResult InitDpairingResource()
738 {
739     OCStackResult ret = OC_STACK_ERROR;
740
741     // Instantiate 'oic.sec.dpairing'
742     ret = CreateDpairingResource();
743     if (OC_STACK_OK != ret)
744     {
745         DeInitDpairingResource();
746     }
747     return ret;
748 }
749
750 /**
751  * Perform cleanup for Dpairing resources.
752  *
753  * @return
754  * OC_STACK_OK    - no error
755  * OC_STACK_ERROR - stack process error
756  *
757  */
758 OCStackResult DeInitDpairingResource()
759 {
760     OCStackResult ret = OCDeleteResource(gDpairHandle);
761     gDpair = NULL;
762
763     if(OC_STACK_OK == ret)
764     {
765         return OC_STACK_OK;
766     }
767     else
768     {
769         return OC_STACK_ERROR;
770     }
771 }
772
773 OCStackResult SetDpairingRownerId(const OicUuid_t* newROwner)
774 {
775     OCStackResult ret = OC_STACK_ERROR;
776     uint8_t *cborPayload = NULL;
777     size_t size = 0;
778     OicUuid_t prevId = {.id={0}};
779
780     if(NULL == newROwner)
781     {
782         ret = OC_STACK_INVALID_PARAM;
783     }
784     if(NULL == gDpair)
785     {
786         ret = OC_STACK_NO_RESOURCE;
787     }
788
789     if(newROwner && gDpair)
790     {
791         memcpy(prevId.id, gDpair->rownerID.id, sizeof(prevId.id));
792         memcpy(gDpair->rownerID.id, newROwner->id, sizeof(newROwner->id));
793
794         ret = DpairingToCBORPayload(gDpair, &cborPayload, &size);
795         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
796
797         ret = UpdateSecureResourceInPS(OIC_JSON_DPAIRING_NAME, cborPayload, size);
798         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
799
800         OICFree(cborPayload);
801     }
802
803     return ret;
804
805 exit:
806     OICFree(cborPayload);
807     memcpy(gDpair->rownerID.id, prevId.id, sizeof(prevId.id));
808     return ret;
809 }
810
811 OCStackResult GetDpairingRownerId(OicUuid_t *rowneruuid)
812 {
813     OCStackResult retVal = OC_STACK_ERROR;
814     if (gDpair)
815     {
816         *rowneruuid = gDpair->rownerID;
817         retVal = OC_STACK_OK;
818     }
819     return retVal;
820 }