replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / security / src / dpairingresource.c
index 900509a..8f03b9a 100644 (file)
  *
  * *****************************************************************/
 
+#include "iotivity_config.h"
 #include <stdlib.h>
 #include <string.h>
 #include "ocstack.h"
 #include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#if defined (__TIZENRT__)
+#include <apps/netutils/cJSON.h>
+#else
 #include "cJSON.h"
+#endif
 #include "base64.h"
 #include "resourcemanager.h"
 #include "dpairingresource.h"
 #include "aclresource.h"
 #include "srmutility.h"
 #include "ocserverrequest.h"
-#include "ocpayloadcbor.h"
 #include "ocpayload.h"
+#include "ocpayloadcbor.h"
 #include "payload_logging.h"
-#include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
-#include <strings.h>
-#endif
 
-#ifdef __WITH_DTLS__
-#include "global.h"
+#ifdef HAVE_STRINGS_H
+#include <strings.h>
 #endif
 
-#define TAG  "SRM-DPAIRING"
+#define TAG  "OIC_SRM_DPAIRING"
 
 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
  * The value of payload size is increased until reaching belox max cbor size. */
@@ -105,7 +104,7 @@ void SetDpairingResourceOwner(OicUuid_t *rowner)
     }
 }
 
-#ifdef __WITH_DTLS__
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 /**
  * Function to save PairingPSK.
  *
@@ -136,7 +135,7 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint,
     }
 
     uint8_t pairingPSK[OWNER_PSK_LENGTH_128] = {0};
-    OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128};
+    OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_RAW};
 
     //Generating PairingPSK using OwnerPSK scheme
     CAResult_t pskRet = CAGenerateOwnerPSK((const CAEndpoint_t *)endpoint,
@@ -148,13 +147,14 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint,
 
     if (CA_STATUS_OK == pskRet)
     {
-        OIC_LOG(INFO, TAG, "pairingPSK dump:\n");
-        OIC_LOG_BUFFER(INFO, TAG, pairingPSK, OWNER_PSK_LENGTH_128);
+        OIC_LOG(DEBUG, TAG, "pairingPSK dump:\n");
+        OIC_LOG_BUFFER(DEBUG, TAG, pairingPSK, OWNER_PSK_LENGTH_128);
         //Generating new credential for direct-pairing client
 
         OicSecCred_t *cred = GenerateCredential(peerDevID,
                 SYMMETRIC_PAIR_WISE_KEY, NULL,
-                &pairingKey, owner);
+                &pairingKey, owner, NULL);
+        OICClearMemory(pairingPSK, sizeof(pairingPSK));
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
         res = AddCredential(cred);
@@ -173,7 +173,7 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint,
 exit:
     return res;
 }
-#endif // __WITH_DTLS__
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
 OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size)
 {
@@ -193,8 +193,8 @@ OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **pay
 
     OCStackResult ret = OC_STACK_ERROR;
 
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder dpairMap = { {.ptr = NULL }, .end = 0 };
+    CborEncoder encoder;
+    CborEncoder dpairMap;
 
     int64_t cborEncoderResult = CborNoError;
     uint8_t mapSize = DPAIR_MAP_SIZE;
@@ -244,7 +244,7 @@ OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **pay
 
      if (CborNoError == cborEncoderResult)
     {
-        *size = encoder.ptr - outPayload;
+        *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
         *payload = outPayload;
         ret = OC_STACK_OK;
     }
@@ -254,8 +254,9 @@ exit:
     {
        // reallocate and try again!
        OICFree(outPayload);
+       outPayload = NULL;
        // Since the allocated initial memory failed, double the memory.
-       cborLen += encoder.ptr - encoder.end;
+       cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
        cborEncoderResult = CborNoError;
        ret = DpairingToCBORPayload(dpair, payload, &cborLen);
        *size = cborLen;
@@ -287,9 +288,8 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
     CborValue dpairCbor = { .parser = NULL };
     CborParser parser = { .end = NULL };
     CborError cborFindResult = CborNoError;
-    int cborLen = size;
 
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &dpairCbor);
+    cbor_parser_init(cborPayload, size, 0, &parser, &dpairCbor);
     CborValue dpairMap = { .parser = NULL };
     OicSecDpairing_t *dpair = NULL;
     cborFindResult = cbor_value_enter_container(&dpairCbor, &dpairMap);
@@ -298,7 +298,7 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
     dpair = (OicSecDpairing_t *)OICCalloc(1, sizeof(*dpair));
     VERIFY_NON_NULL(TAG, dpair, ERROR);
 
-    while (cbor_value_is_valid(&dpairMap))
+    while (cbor_value_is_valid(&dpairMap) && cbor_value_is_text_string(&dpairMap))
     {
         char *name = NULL;
         size_t len = 0;
@@ -309,10 +309,13 @@ OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a value in DPair map");
 
         type = cbor_value_get_type(&dpairMap);
-        if (0 == strcmp(OIC_JSON_SPM_NAME, name))
+        if (0 == strcmp(OIC_JSON_SPM_NAME, name) && cbor_value_is_integer(&dpairMap))
         {
-            cborFindResult = cbor_value_get_int(&dpairMap, (int *) &dpair->spm);
+            int spm;
+
+            cborFindResult = cbor_value_get_int(&dpairMap, &spm);
             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SPM Value");
+            dpair->spm = (OicSecPrm_t)spm;
         }
 
         if (0 == strcmp(OIC_JSON_PDEVICE_ID_NAME, name))
@@ -383,9 +386,9 @@ void DPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *
 
         }
 
-#ifdef __WITH_DTLS__
-        CARegisterDTLSHandshakeCallback(NULL);
-#endif // __WITH_DTLS__
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
+        CAregisterSslHandshakeCallback(NULL);
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
         // delete temporary key
         RemoveCredential(&gDpair->pdeviceID);
@@ -404,7 +407,7 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
     const OicSecPconf_t *pconf = GetPconfResourceData();
     if (true == pconf->edp)
     {
-        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
+        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
         size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
         if (payload)
         {
@@ -443,7 +446,7 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
             memcpy(&gDpair->pdeviceID, &newDpair->pdeviceID, sizeof(OicUuid_t));
             memcpy(&gDpair->rownerID, &pconf->rownerID, sizeof(OicUuid_t));
 
-#ifdef __WITH_DTLS__
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
             // Add temporary psk
             OCStackResult res;
             OicUuid_t subjectId = {.id={0}};
@@ -460,19 +463,19 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
 
             // Prepare to establish a secure channel with Pin-based PSK cipher suite
             if (CA_STATUS_OK != CAEnableAnonECDHCipherSuite(false) ||
-                CA_STATUS_OK != CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256))
+                CA_STATUS_OK != CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP))
             {
                 OIC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256");
                 goto exit;
             }
 
-            if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DPairingDTLSHandshakeCB))
+            if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DPairingDTLSHandshakeCB))
             {
                 OIC_LOG(WARNING, TAG, "DirectPairingHandler : Failed to register"
                         " DTLS handshake callback.");
                 goto exit;
             }
-#endif // __WITH_DTLS__
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
             // should be lock /oic/sec/dpairing resource if Direct-Pairing starts normally ?
             OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource created");
@@ -486,20 +489,21 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
     }
 
 
-#ifdef __WITH_DTLS__
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 exit:
-#endif // __WITH_DTLS__
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
-    if (OC_EH_ERROR == ehRet && gDpair)
+    // Send payload to request originator
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
     {
-        RemoveCredential(&gDpair->pdeviceID);
-        gDpair = NULL;
+        ehRet = OC_EH_ERROR;
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPostRequest");
     }
 
-    // Send payload to request originator
-    if(OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
+    if (OC_EH_ERROR == ehRet && gDpair)
     {
-        OIC_LOG (ERROR, TAG, "SendSRMCBORResponse failed in HandleDpairingPostRequest");
+        RemoveCredential(&gDpair->pdeviceID);
+        gDpair = NULL;
     }
 
     DeleteDpairingBinData(newDpair);
@@ -518,7 +522,7 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
     const OicSecPconf_t *pconf = GetPconfResourceData();
     if (true == pconf->edp)
     {
-        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
+        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData;
         size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
         if (payload)
         {
@@ -543,8 +547,9 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
         const OicSecPconf_t *pconf = GetPconfResourceData();
         VERIFY_NON_NULL(TAG, pconf, ERROR);
 
-#ifdef __WITH_DTLS__
-        OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle;
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
+        OCServerRequest *request = GetServerRequestUsingHandle(ehRequest->requestHandle);
+        VERIFY_NON_NULL(TAG, request, ERROR);
         VERIFY_SUCCESS(TAG, (request->devAddr.flags | OC_FLAG_SECURE), ERROR);
 
         //Generate new credential
@@ -553,30 +558,90 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
         OCStackResult res = SavePairingPSK(&request->devAddr, &newDpair->pdeviceID,
                 (OicUuid_t *)&pconf->rownerID, true);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
-#endif //__WITH_DTLS__
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
         //Generate new acl
         OicSecPdAcl_t *pdAcl;
         LL_FOREACH(pconf->pdacls, pdAcl)
         {
-            OicSecAcl_t acl;
-            memset(&acl, 0, sizeof(OicSecAcl_t));
-            memcpy(&acl.subject, &gDpair->pdeviceID, sizeof(OicUuid_t));
-            acl.resources = pdAcl->resources;
-            acl.resourcesLen = pdAcl->resourcesLen;
-            memcpy(&acl.rownerID, &pconf->rownerID, sizeof(OicUuid_t));
-            acl.permission = pdAcl->permission;
-            acl.periods = pdAcl->periods;
-            acl.recurrences = pdAcl->recurrences;
-            acl.prdRecrLen = pdAcl->prdRecrLen;
+            OicSecAcl_t* acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+            VERIFY_NON_NULL(TAG, acl, ERROR);
+
+            OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
+            VERIFY_NON_NULL(TAG, ace, ERROR);
+
+            LL_APPEND(acl->aces, ace);
+
+            memcpy(&ace->subjectuuid, &gDpair->pdeviceID, sizeof(OicUuid_t));
+
+            for(size_t i = 0; i < pdAcl->resourcesLen; i++)
+            {
+                OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
+                VERIFY_NON_NULL(TAG, rsrc, ERROR);
+                LL_APPEND(ace->resources, rsrc);
+
+                //href
+                rsrc->href = OICStrdup(pdAcl->resources[i]);
+
+                // TODO: Append 'if' and 'rt' as workaround
+                // if
+                rsrc->interfaceLen = 1;
+                rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char));
+                VERIFY_NON_NULL(TAG, (rsrc->interfaces), ERROR);
+                rsrc->interfaces[0] = OICStrdup(OC_RSRVD_INTERFACE_DEFAULT);
+                VERIFY_NON_NULL(TAG, (rsrc->interfaces[0]), ERROR);
+
+                //rt
+                rsrc->typeLen = 1;
+                rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char));
+                VERIFY_NON_NULL(TAG, (rsrc->types), ERROR);
+                rsrc->types[0] = OICStrdup("oic.core");
+                VERIFY_NON_NULL(TAG, (rsrc->types[0]), ERROR);
+            }
+
+            ace->permission = pdAcl->permission;
+
+            //Copy the validity
+            if(pdAcl->periods || pdAcl->recurrences)
+            {
+                OicSecValidity_t* validity = (OicSecValidity_t*)OICCalloc(1, sizeof(OicSecValidity_t));
+                VERIFY_NON_NULL(TAG, validity, ERROR);
+
+                if(pdAcl->periods && pdAcl->periods[0])
+                {
+                    size_t periodLen = strlen(pdAcl->periods[0]) + 1;
+                    validity->period = (char*)OICMalloc(periodLen * sizeof(char));
+                    VERIFY_NON_NULL(TAG, (validity->period), ERROR);
+                    OICStrcpy(validity->period, periodLen, pdAcl->periods[0]);
+                }
+
+                if(pdAcl->recurrences && 0 < pdAcl->prdRecrLen)
+                {
+                    validity->recurrenceLen = pdAcl->prdRecrLen;
+                    validity->recurrences = (char**)OICMalloc(sizeof(char*) * pdAcl->prdRecrLen);
+                    VERIFY_NON_NULL(TAG, (validity->recurrences), ERROR);
+
+                    for(size_t i = 0; i < pdAcl->prdRecrLen; i++)
+                    {
+                        size_t recurrenceLen = strlen(pdAcl->recurrences[i]) + 1;
+                        validity->recurrences[i] = (char*)OICMalloc(recurrenceLen  * sizeof(char));
+                        VERIFY_NON_NULL(TAG, (validity->recurrences[i]), ERROR);
+
+                        OICStrcpy(validity->recurrences[i], recurrenceLen, pdAcl->recurrences[i]);
+                    }
+                }
+
+                LL_APPEND(ace->validities, validity);
+            }
 
             size_t size = 0;
             uint8_t *payload = NULL;
-            if (OC_STACK_OK == AclToCBORPayload(&acl, &payload, &size))
+            if (OC_STACK_OK == AclToCBORPayload(acl, &payload, &size))
             {
-                InstallNewACL(payload, size);
+                AppendACL(payload, size);
                 OICFree(payload);
             }
+            DeleteACLList(acl);
         }
 
         //update pconf device list
@@ -593,9 +658,10 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
 exit:
 
     //Send payload to request originator
-    if(OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
     {
-        OIC_LOG (ERROR, TAG, "SendSRMCBORResponse failed in HandleDpairingPutRequest");
+        ehRet = OC_EH_ERROR;
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPutRequest");
     }
 
     DeleteDpairingBinData(newDpair);
@@ -640,7 +706,7 @@ OCEntityHandlerResult DpairingEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
+                SendSRMResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
@@ -656,7 +722,7 @@ OCStackResult CreateDpairingResource()
 
     ret = OCCreateResource(&gDpairHandle,
                            OIC_RSRC_TYPE_SEC_DPAIRING,
-                           OIC_MI_DEF,
+                           OC_RSRVD_INTERFACE_DEFAULT,
                            OIC_RSRC_DPAIRING_URI,
                            DpairingEntityHandler,
                            NULL,
@@ -748,3 +814,14 @@ exit:
     memcpy(gDpair->rownerID.id, prevId.id, sizeof(prevId.id));
     return ret;
 }
+
+OCStackResult GetDpairingRownerId(OicUuid_t *rowneruuid)
+{
+    OCStackResult retVal = OC_STACK_ERROR;
+    if (gDpair)
+    {
+        *rowneruuid = gDpair->rownerID;
+        retVal = OC_STACK_OK;
+    }
+    return retVal;
+}