Common adapter for DTLS/TLS 95/13095/4
authorDmitriy Zhuravlev <d.zhuravlev@samsung.com>
Mon, 3 Oct 2016 13:22:11 +0000 (16:22 +0300)
committerRandeep Singh <randeep.s@samsung.com>
Wed, 12 Oct 2016 04:08:11 +0000 (04:08 +0000)
Format of a certificate changed, so previous X.509 parser
is not able to parse new certificates provided by Cloud:
1) For DTLS and TLS used mbedTLS
2) CKManager removed

Change-Id: Icacf60237a8ce15e996c4bbe4769a230b39c770e
Signed-off-by: Dmitriy Zhuravlev <d.zhuravlev@samsung.com>
X-Origin-Change-Id: I6b47f7b3439b923ec12f26b0e159e3b7a1144658
Signed-off-by: Philippe Coval <philippe.coval@osg.samsung.com>
Signed-off-by: Oleksii Beketov <ol.beketov@samsung.com>
Signed-off-by: Dmitriy Zhuravlev <d.zhuravlev@samsung.com>
Signed-off-by: Trevor Bramwell <tbramwell@linuxfoundation.org>
Reviewed-on: https://gerrit.iotivity.org/gerrit/12029
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Randeep Singh <randeep.s@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/13095
Reviewed-by: Kevin Kane <kkane@microsoft.com>
137 files changed:
build_common/SConscript
build_common/android/SConscript
examples/OICMiddle/SConscript
extlibs/asn1cert/SConscript [deleted file]
extlibs/asn1cert/certificate.asn [deleted file]
extlibs/asn1cert/crl.asn [deleted file]
extlibs/asn1cert/csr.asn [deleted file]
extlibs/mbedtls/SConscript
plugins/samples/linux/SConscript
resource/c_common/byte_array.h [moved from resource/csdk/connectivity/inc/pkix/byte_array.h with 97% similarity]
resource/c_common/ocrandom/test/SConscript
resource/csdk/SConscript
resource/csdk/connectivity/api/casecurityinterface.h
resource/csdk/connectivity/build/android/SConscript
resource/csdk/connectivity/build/tizen/gbsbuild.sh
resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec
resource/csdk/connectivity/inc/ca_adapter_net_ssl.h [moved from resource/csdk/connectivity/inc/ca_adapter_net_tls.h with 72% similarity]
resource/csdk/connectivity/inc/pkix/cert.h [deleted file]
resource/csdk/connectivity/inc/pkix/crl.h [deleted file]
resource/csdk/connectivity/inc/pkix/crypto_adapter.h [deleted file]
resource/csdk/connectivity/inc/pkix/der_dec.h [deleted file]
resource/csdk/connectivity/inc/pkix/pki.h [deleted file]
resource/csdk/connectivity/inc/pkix/pki_errors.h [deleted file]
resource/csdk/connectivity/inc/pkix/sn_store.h [deleted file]
resource/csdk/connectivity/src/SConscript
resource/csdk/connectivity/src/adapter_util/ca_adapter_net_ssl.c [new file with mode: 0644]
resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c
resource/csdk/connectivity/src/adapter_util/pkix/cert.c [deleted file]
resource/csdk/connectivity/src/adapter_util/pkix/crl.c [deleted file]
resource/csdk/connectivity/src/adapter_util/pkix/der_const.c [deleted file]
resource/csdk/connectivity/src/adapter_util/pkix/der_dec.c [deleted file]
resource/csdk/connectivity/src/adapter_util/pkix/pki.c [deleted file]
resource/csdk/connectivity/src/adapter_util/pkix/sn_store.c [deleted file]
resource/csdk/connectivity/src/caconnectivitymanager.c
resource/csdk/connectivity/src/ip_adapter/caipadapter.c
resource/csdk/connectivity/src/ip_adapter/caipserver.c
resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c
resource/csdk/connectivity/src/tcp_adapter/catcpserver.c
resource/csdk/connectivity/test/SConscript
resource/csdk/connectivity/test/ca_api_unittest.cpp
resource/csdk/resource-directory/samples/SConscript
resource/csdk/security/SConscript
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/crlresource.h
resource/csdk/security/include/internal/dpairingresource.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/provisioning/SConscript
resource/csdk/security/provisioning/ck_manager/SConscript [deleted file]
resource/csdk/security/provisioning/ck_manager/include/cert_generator.h [deleted file]
resource/csdk/security/provisioning/ck_manager/include/ck_manager.h [deleted file]
resource/csdk/security/provisioning/ck_manager/include/ckm_info.h [deleted file]
resource/csdk/security/provisioning/ck_manager/include/crl_generator.h [deleted file]
resource/csdk/security/provisioning/ck_manager/include/csr_generator.h [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/Light_sample.cpp [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/README.txt [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json [deleted file]
resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c [deleted file]
resource/csdk/security/provisioning/ck_manager/src/cert_generator.c [deleted file]
resource/csdk/security/provisioning/ck_manager/src/ck_manager.c [deleted file]
resource/csdk/security/provisioning/ck_manager/src/ckm_info.c [deleted file]
resource/csdk/security/provisioning/ck_manager/src/crl_generator.c [deleted file]
resource/csdk/security/provisioning/ck_manager/src/csr_generator.c [deleted file]
resource/csdk/security/provisioning/ck_manager/tools/SConscript [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/SConscript [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/01.der [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/cacert.der [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/capub.der [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/cert_chain.dat [deleted file]
resource/csdk/security/provisioning/ck_manager/unittest/test_data/chain.der [deleted file]
resource/csdk/security/provisioning/include/internal/secureresourceprovider.h
resource/csdk/security/provisioning/include/ocprovisioningmanager.h
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/cloud/cloudCommon.c
resource/csdk/security/provisioning/src/credentialgenerator.c
resource/csdk/security/provisioning/src/ocprovisioningmanager.c
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/oxmjustworks.c
resource/csdk/security/provisioning/src/oxmrandompin.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/provisioning/unittest/SConscript
resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp
resource/csdk/security/src/credresource.c
resource/csdk/security/src/crlresource.c
resource/csdk/security/src/directpairing.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c
resource/csdk/security/src/oxmpincommon.c
resource/csdk/security/src/resourcemanager.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/tool/json2cbor.c
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/crlresourcetest.cpp
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/samples/linux/SimpleClientServer/SConscript
resource/csdk/stack/samples/linux/secure/SConscript
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/tizen/SimpleClientServer/scons/SConscript
resource/csdk/stack/samples/tizen/build/gbsbuild.sh
resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec
resource/csdk/stack/test/SConscript
resource/examples/SConscript
resource/include/OCProvisioningManager.h
resource/provisioning/examples/SConscript
resource/provisioning/src/OCProvisioningManager.cpp
resource/provisioning/unittests/OCCloudProvisioningTest.cpp
resource/provisioning/unittests/SConscript
resource/src/SConscript
resource/unittests/SConscript
service/coap-http-proxy/samples/SConscript
service/easy-setup/enrollee/SConscript
service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh
service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript
service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript
service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript
service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript
service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript
service/resource-encapsulation/examples/linux/SConscript
service/resource-encapsulation/examples/linux/secureResourceExample/SConscript
service/resource-hosting/SampleApp/linux/SConscript
service/scene-manager/sampleapp/linux/SConscript
service/simulator/examples/client/SConscript
service/simulator/examples/server/SConscript
service/things-manager/sampleapp/linux/configuration/SConscript

index 3008842..b5203fb 100644 (file)
@@ -112,7 +112,6 @@ else:
 
 help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os]))
 help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
-help_vars.Add(EnumVariable('DTLS_WITH_X509', 'DTLS with X.509 support', '0', allowed_values=('0', '1')))
 help_vars.Add(EnumVariable('TEST', 'Run unit tests', '0', allowed_values=('0', '1')))
 help_vars.Add(BoolVariable('LOGGING', 'Enable stack logging', logging_default))
 help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
@@ -197,19 +196,13 @@ if target_os in targets_support_cc:
     if prefix or tc_path:
         print tc_set_msg
 
-# Import env variables only if reproductibility is ensured
-if target_os in ['yocto']:
-    env['CONFIG_ENVIRONMENT_IMPORT'] = True
-else:
-    env['CONFIG_ENVIRONMENT_IMPORT'] = False
-
-if env['CONFIG_ENVIRONMENT_IMPORT'] == True:
-    print "warning: importing some environment variables for OS: %s" % target_os
-    for ev in ['PATH', 'PKG_CONFIG', 'PKG_CONFIG_PATH', 'PKG_CONFIG_SYSROOT_DIR']:
-        if os.environ.get(ev) != None:
-            env['ENV'][ev] = os.environ.get(ev)
-    if os.environ['LDFLAGS'] != None:
-        env.AppendUnique(LINKFLAGS = Split(os.environ['LDFLAGS']))
+# If cross-compiling, honor environment settings for toolchain to avoid picking up native tools
+if os.environ.get('PKG_CONFIG') != None:
+       env["ENV"]["PKG_CONFIG"] = os.environ.get("PKG_CONFIG")
+if os.environ.get('PKG_CONFIG_PATH') != None:
+       env["ENV"]["PKG_CONFIG_PATH"] = os.environ.get("PKG_CONFIG_PATH")
+if os.environ.get('PKG_CONFIG_SYSROOT_DIR') != None:
+       env["ENV"]["PKG_CONFIG_SYSROOT_DIR"] = os.environ.get("PKG_CONFIG_SYSROOT_DIR")
 
 # Ensure scons be able to change its working directory
 env.SConscriptChdir(1)
@@ -391,6 +384,8 @@ if target_os == "yocto":
                         env[tool] = os.path.join(path, os.environ[tool])
                         break
         env['CROSS_COMPILE'] = target_prefix[:len(target_prefix) - 1]
+        if os.environ['LDFLAGS'] != None:
+            env.AppendUnique(LINKFLAGS = Split(os.environ['LDFLAGS']))
     except:
         print "ERROR in Yocto cross-toolchain environment"
         Exit(1)
index dcd6481..f24c038 100644 (file)
@@ -222,9 +222,8 @@ env.AppendUnique(LIBS = ['log', 'coap'])
 
 if env.get('SECURED') == '1':
        env.AppendUnique(LIBS = ['tinydtls'])
-       if env.get('WITH_TCP'):
-               env.SConscript('#extlibs/mbedtls/SConscript')
-               env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
+       env.SConscript('#extlibs/mbedtls/SConscript')
+       env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
 
 # From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
 # Due to the limitation of Scons, it's required to added it into the command line
index 4335a48..05b3aae 100644 (file)
@@ -57,9 +57,7 @@ examples_env.AppendUnique(LIBS = ['oc'])
 examples_env.AppendUnique(LIBS = ['rt'])
 
 if env.get('SECURED') == '1':
-    examples_env.AppendUnique(LIBS = ['tinydtls'])
-    if env.get('WITH_TCP') == True:
-               examples_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto'])
+       examples_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto'])
 
 if target_os == 'android':
        examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
diff --git a/extlibs/asn1cert/SConscript b/extlibs/asn1cert/SConscript
deleted file mode 100644 (file)
index 18fec68..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-##
-# Script to generate ASN.1 source code.
-# If asn1 compiler is not installed get it and install it.
-#
-##
-
-import os
-
-Import('env')
-
-asn1_env = env.Clone()
-
-target_os = asn1_env.get('TARGET_OS')
-src_dir = asn1_env.get('SRC_DIR')
-
-targets_need_asn1 = ['linux']
-asn1c_dir      = src_dir + '/extlibs/asn1cert/asn1c-0.9.27'
-asn1c_gz_file = src_dir + '/extlibs/asn1cert/asn1c-0.9.27.tar.gz'
-asn1c_url      = 'http://lionet.info/soft/asn1c-0.9.27.tar.gz'
-asn1c_file = src_dir + '/extlibs/asn1cert/asn1c-0.9.27/asn1c/asn1c'
-
-if target_os in targets_need_asn1:
-       print '*** Checking for installation of asn1c-0.9.27 ***'
-
-       if not os.path.exists(asn1c_dir):
-               # If the asn1 gz file is not already present, download it
-               if not os.path.exists(asn1c_gz_file):
-                       asn1c_gz = asn1_env.Download(asn1c_gz_file, asn1c_url)
-               else:
-                       asn1c_gz = asn1c_gz_file
-
-               # Ungz asn1c
-               print 'Unzipping asn1 compiler'
-               asn1_env.UnpackAll(asn1c_dir, asn1c_gz)
-       if os.path.exists(asn1c_dir):
-               if not os.path.exists(asn1c_file):
-                       # Run configure on asn1
-                       print 'Configuring asn1 compiler'
-                       if asn1_env.get('CROSS_COMPILE'):
-                               asn1_env.Configure(asn1c_dir, './configure --host=' + asn1_env['CROSS_COMPILE'])
-                       else:
-                               asn1_env.Configure(asn1c_dir, './configure')
-
-                       # Run make on asn1
-                       print 'Making asn1 compiler'
-                       asn1_env.Configure(asn1c_dir, 'make')
-       print 'Generating Source Code:'
-       asn1_env.Configure(src_dir + '/extlibs/asn1cert', './asn1c-0.9.27/asn1c/asn1c certificate.asn')
-       asn1_env.Configure(src_dir + '/extlibs/asn1cert', './asn1c-0.9.27/asn1c/asn1c crl.asn')
-       asn1_env.Configure(src_dir + '/extlibs/asn1cert', './asn1c-0.9.27/asn1c/asn1c csr.asn')
-       asn1_env.Configure(src_dir + '/extlibs/asn1cert', 'rm converter-sample.c')
-
-       #Build asn1 as static library
-       asn1_env.Append(CPPPATH=[src_dir + '/extlibs/asn1cert'])
-       asn1_src = Glob('*.c')
-       asn1_lib = asn1_env.StaticLibrary('asn1', asn1_src)
-       asn1_env.InstallTarget(asn1_lib, 'libasn1')
-
diff --git a/extlibs/asn1cert/certificate.asn b/extlibs/asn1cert/certificate.asn
deleted file mode 100644 (file)
index c5053a9..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-CERTIFICATE DEFINITIONS ::= BEGIN\r
-\r
-Certificate ::= SEQUENCE {\r
-        tbsCertificate      TBSCertificate,\r
-        signatureAlgorithm  AlgorithmIdentifier,\r
-        signatureValue      BIT STRING\r
-}\r
-\r
-AlgorithmIdentifier ::= SEQUENCE {\r
-        algorithm       OBJECT IDENTIFIER,\r
-        id-ecPublicKey         OBJECT IDENTIFIER OPTIONAL,\r
-        nul                            NULL OPTIONAL\r
-}\r
-\r
-TBSCertificate ::= SEQUENCE {\r
-        version         [0]    EXPLICIT Version DEFAULT v1,\r
-        serialNumber           CertificateSerialNumber,\r
-        signature              AlgorithmIdentifier,\r
-        issuer                 Name,\r
-        validity               Validity,\r
-        subject                Name,\r
-        subjectPublicKeyInfo   SubjectPublicKeyInfo\r
-}\r
-\r
-Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }\r
-\r
-CertificateSerialNumber ::= INTEGER\r
-\r
-Name ::= RDNSequence\r
-\r
-RDNSequence ::= SEQUENCE OF RelativeDistinguishedName\r
-\r
-RelativeDistinguishedName ::= SET OF AttributeTypeAndValue\r
-\r
-AttributeTypeAndValue ::= SEQUENCE {\r
-     type     AttributeType,\r
-     value    AttributeValue}\r
-\r
-AttributeType ::= OBJECT IDENTIFIER\r
-\r
-AttributeValue ::= UTF8String\r
-\r
-Validity ::= SEQUENCE {\r
-        notBefore   Time,\r
-        notAfter    Time\r
-}\r
-\r
-Time ::= UTCTime\r
-\r
-SubjectPublicKeyInfo ::= SEQUENCE {\r
-        algorithm           AlgorithmIdentifier,\r
-        subjectPublicKey    BIT STRING\r
-}\r
-\r
-ECDSA-Sig-Value ::= SEQUENCE {\r
-          r  INTEGER,\r
-          s  INTEGER\r
-}\r
-\r
-END\r
-
diff --git a/extlibs/asn1cert/crl.asn b/extlibs/asn1cert/crl.asn
deleted file mode 100644 (file)
index c73cb64..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-CRL DEFINITIONS ::= BEGIN
-
-CertificateRevocationList  ::=  SEQUENCE  {
-    tbsCertList          TBSCertList,
-    signatureAlgorithm   AlgorithmIdentifier,
-    signatureValue       BIT STRING  }
-
-TBSCertList  ::=  SEQUENCE  {
-    signature               AlgorithmIdentifier,
-    issuer                  Name,
-    thisUpdate              Time,
-    revokedCertificates     SEQUENCE OF CertificateRevocationInfo
-                           }
-
-CertificateRevocationInfo ::= SEQUENCE  {
-    userCertificate         CertificateSerialNumber,
-    revocationDate          Time
-          }
-
-AlgorithmIdentifier ::= SEQUENCE {
-    algorithm          OBJECT IDENTIFIER,
-    id-ecPublicKey     OBJECT IDENTIFIER OPTIONAL,
-    nul                        NULL OPTIONAL
-}
-
-CertificateSerialNumber ::= INTEGER
-
-Time ::= UTCTime
-
-Name ::= RDNSequence
-
-RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
-
-RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
-
-AttributeTypeAndValue ::= SEQUENCE {
-     type     AttributeType,
-     value    AttributeValue }
-
-AttributeType ::= OBJECT IDENTIFIER
-
-AttributeValue ::= UTF8String
-
-END
-
diff --git a/extlibs/asn1cert/csr.asn b/extlibs/asn1cert/csr.asn
deleted file mode 100644 (file)
index f51fe2c..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-CSR DEFINITIONS ::= BEGIN
-
--- Certificate requests
-
-CertificationRequest ::= SEQUENCE {
-    certificationRequestInfo CertificationRequestInfo,
-    signatureAlgorithm AlgorithmIdentifier,
-    signature          BIT STRING
-}
-
-CertificationRequestInfo ::= SEQUENCE {
-    version       INTEGER { v1(0) },
-    subject       Name,
-    subjectPKInfo SubjectPublicKeyInfo
-}
-
-SubjectPublicKeyInfo ::= SEQUENCE {
-    algorithm        AlgorithmIdentifier,
-    subjectPublicKey BIT STRING
-}
-
-AlgorithmIdentifier ::= SEQUENCE {
-    algorithm       OBJECT IDENTIFIER,
-    id-ecPublicKey  OBJECT IDENTIFIER OPTIONAL,
-    nul             NULL OPTIONAL
-}
-
-Name ::= RDNSequence
-
-RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
-
-RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
-
-AttributeTypeAndValue ::= SEQUENCE {
-     type     AttributeType,
-     value    AttributeValue }
-
-AttributeType ::= OBJECT IDENTIFIER
-
-AttributeValue ::= UTF8String
-
-END
index 1b662b7..5ea4b2e 100644 (file)
@@ -40,7 +40,7 @@ if not os.path.exists(mbedtls_dir):
 if target_os != 'tizen':
     start_dir = os.getcwd()
     os.chdir(mbedtls_dir)
-    cmd = 'git reset --hard ad249f509fd62a3bbea7ccd1fef605dbd482a7bd && git apply ../ocf.patch'
+    cmd = 'git checkout development && git reset --hard ad249f509fd62a3bbea7ccd1fef605dbd482a7bd && git apply --whitespace=fix ../ocf.patch'
     os.system(cmd)
     os.chdir(start_dir)
 
@@ -48,7 +48,7 @@ if target_os != 'tizen':
 mbedtls_env = env.Clone()
 mbedtls_env.PrependUnique(CPPPATH = [mbedtls_dir])
 mbedtls_env.AppendUnique(CPPPATH = [mbedtls_dir+'include/'])
-mbedtls_env.AppendUnique(CFLAGS = ['-fPIC', '-Wall', '-Wextra', '-W', '-Wdeclaration-after-statement', '-Wwrite-strings'])
+mbedtls_env.AppendUnique(CFLAGS = ['-fPIC', '-Wall'])
 
 ######################################################################
 # Source files and Target(s)
index bad07a3..1db50ba 100644 (file)
@@ -62,7 +62,7 @@ elif target_os not in ['arduino']:
        samples_env.AppendUnique(LIBS = ['pthread'])
 
 if env.get('SECURED') == '1':
-    samples_env.AppendUnique(LIBS = ['tinydtls'])
+    samples_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
 
 samples_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
similarity index 97%
rename from resource/csdk/connectivity/inc/pkix/byte_array.h
rename to resource/c_common/byte_array.h
index 22892cd..a736764 100644 (file)
@@ -32,18 +32,18 @@ extern "C" {
 #include <stdint.h>
 
 /**
- * @struct ByteArray
+ * @struct ByteArray_t
  *
  * General purpose byte array structure.
  *
  * Contains pointer to array of bytes and it's length.
  */
 
-typedef struct
+typedef struct ByteArray
 {
     uint8_t *data;    /**< Pointer to the byte array */
     size_t len;      /**< Data size */
-} ByteArray;
+} ByteArray_t;
 
 
 /**@def BYTE_ARRAY_INITIALIZER
@@ -57,7 +57,7 @@ typedef struct
  *
  * Initializes of existing byte array \a array.
  *
- * @param array ByteArray
+ * @param array ByteArray_t
  */
 #undef INIT_BYTE_ARRAY
 #define INIT_BYTE_ARRAY(array) do{  \
index 0f9d732..e3536c1 100644 (file)
@@ -37,6 +37,9 @@ randomtest_env.PrependUnique(LIBS = ['c_common'])
 if target_os in ['linux']:
     randomtest_env.AppendUnique(LIBS = ['m'])
 
+#if randomtest_env.get('SECURED') == '1':
+#      randomtest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto'])
+
 if randomtest_env.get('LOGGING'):
        randomtest_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
index 13781fd..0de9e79 100644 (file)
@@ -96,8 +96,7 @@ if target_os in ['linux'] and liboctbstack_env.get('SIMULATOR', False):
 
 if env.get('SECURED') == '1':
        liboctbstack_env.AppendUnique(LIBS = ['tinydtls'])
-       if env.get('WITH_TCP') == True:
-               liboctbstack_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
+       liboctbstack_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
 
 if target_os in ['android', 'linux', 'tizen', 'msys_nt', 'windows']:
        liboctbstack_env.PrependUnique(LIBS = ['connectivity_abstraction'])
@@ -143,9 +142,6 @@ if target_os == 'android':
 if env.get('LOGGING'):
        liboctbstack_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
-if env.get('DTLS_WITH_X509') == '1':
-       liboctbstack_env.AppendUnique(CPPDEFINES = ['__WITH_X509__'])
-
 liboctbstack_env.Append(LIBS = ['c_common'])
 
 if liboctbstack_env.get('ROUTING') in ['GW', 'EP']:
index bae8653..fa3c2ef 100644 (file)
 #ifndef CA_SECURITY_INTERFACE_H_
 #define CA_SECURITY_INTERFACE_H_
 
-#ifdef __WITH_X509__
-#include "pki.h"
-#endif //__WITH_X509__
 
 #include "cacommon.h"
-
-#ifdef __WITH_TLS__
 #include "byte_array.h"
-#endif
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif
 
-
-#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 /**
  * @enum CADtlsPskCredType_t
  * Type of PSK credential required during DTLS handshake
@@ -70,30 +62,9 @@ typedef enum
  * @return The number of bytes written to @p result or a value
  *         less than zero on error.
  */
-typedef int (*CAGetDTLSPskCredentialsHandler)(CADtlsPskCredType_t type,
+typedef int (*CAgetPskCredentialsHandler)(CADtlsPskCredType_t type,
               const uint8_t *desc, size_t desc_len,
               uint8_t *result, size_t result_length);
-#endif // __WITH_DTLS__ or __WITH_TLS__
-#ifdef __WITH_DTLS__
-
-/**
- * Register callback to receive the result of DTLS handshake.
- * @param[in] dtlsHandshakeCallback callback for get dtls handshake result
- * @return ::CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSHandshakeCallback(CAErrorCallback dtlsHandshakeCallback);
-
-/**
- * Register callback to get DTLS PSK credentials.
- * @param[in]   GetDTLSCredentials    GetDTLS Credetials callback.
- * @return  ::CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentials);
-
-#endif //__WITH_DTLS__
-
-
-#ifdef __WITH_TLS__
 /**
  * This internal callback is used by CA layer to
  * retrieve all credential types from SRM
@@ -109,13 +80,13 @@ typedef void (*CAgetCredentialTypesHandler)(bool * list);
 typedef struct
 {
     // own certificate chain
-    ByteArray crt;
+    ByteArray_t crt;
     // own public key
-    ByteArray key;
+    ByteArray_t key;
     // trusted CA's
-    ByteArray ca;
+    ByteArray_t ca;
     // trusted CRL's
-    ByteArray crl;
+    ByteArray_t crl;
 } PkiInfo_t;
 
 /**
@@ -129,14 +100,14 @@ CAResult_t CAregisterGetCredentialTypesCallback(CAgetCredentialTypesHandler cred
  * @param[in] tlsHandshakeCallback callback for get tls handshake result
  * @return ::CA_STATUS_OK
  */
-CAResult_t CAregisterTlsHandshakeCallback(CAErrorCallback tlsHandshakeCallback);
+CAResult_t CAregisterSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback);
 
 /**
  * Register callback to get TLS PSK credentials.
  * @param[in]   getTLSCredentials    GetDTLS Credetials callback.
  * @return  ::CA_STATUS_OK
  */
-CAResult_t CAregisterTlsCredentialsHandler(CAGetDTLSPskCredentialsHandler getTlsCredentials);
+CAResult_t CAregisterPskCredentialsHandler(CAgetPskCredentialsHandler getTlsCredentials);
 
 /**
  * @brief   Callback function type for getting PKIX info
@@ -149,61 +120,6 @@ typedef void (*CAgetPkixInfoHandler)(PkiInfo_t * inf);
 
 //TODO
 CAResult_t CAregisterPkixInfoHandler(CAgetPkixInfoHandler getPkixInfoHandler);
-#endif //__WITH_TLS__
-
-#ifdef __WITH_X509__
-/**
- * Binary structure containing certificate chain and certificate credentials
- * for this device.
- */
-typedef struct
-{
-    // certificate message  for DTLS
-    unsigned char certificateChain[MAX_CERT_MESSAGE_LEN];
-    // length of the certificate message
-    uint32_t  certificateChainLen;
-    // number of certificates in  certificate message
-    uint8_t   chainLen;
-    // x component of EC public key
-    uint8_t   rootPublicKeyX[PUBLIC_KEY_SIZE / 2];
-    // y component of EC public key
-    uint8_t   rootPublicKeyY[PUBLIC_KEY_SIZE / 2];
-    // EC private key
-    uint8_t   devicePrivateKey[PRIVATE_KEY_SIZE];
-
-} CADtlsX509Creds_t;
-
-/**
- * @brief   Callback function type for getting certificate credentials.
- * @param   credInfo          [OUT] Certificate credentials info. Handler has to allocate new memory for
- *                                  credInfo which is then freed by CA
- * @return  NONE
- */
-typedef int (*CAGetDTLSX509CredentialsHandler)(CADtlsX509Creds_t *credInfo);
-/**
- * @brief   Callback function type for getting CRL.
- * @param   crlInfo          [OUT] Certificate credentials info. Handler has to allocate new memory for
- *                                  credInfo which is then freed by CA
- * @return  NONE
- */
-typedef void (*CAGetDTLSCrlHandler)(ByteArray* crlInfo);
-
-/**
- * @brief   Register callback to get DTLS Cert credentials.
- * @param   GetCertCredentials   [IN] GetCert Credetials callback
- * @return  #CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSX509CredentialsHandler(CAGetDTLSX509CredentialsHandler GetX509Credentials);
-/**
- * @brief   Register callback to get CRL.
- * @param   GetCrl   [IN] GetCrl callback
- * @return  #CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSCrlHandler(CAGetDTLSCrlHandler GetCrl);
-#endif //__WITH_X509__
-
-
-#ifdef __WITH_DTLS__
 
 /**
  * Select the cipher suite for dtls handshake.
@@ -246,7 +162,7 @@ CAResult_t CAEnableAnonECDHCipherSuite(const bool enable);
  * @param[in] provServerDeviceID  label of previous owner.
  * @param[in] provServerDeviceIDLen  byte length of provServerDeviceID.
  * @param[in,out] ownerPSK  Output buffer for owner PSK.
- * @param[in] ownerPSKSize  Byte length of the ownerPSK to be generated.
+ * @param[in] ownerPskSize  Byte length of the ownerPSK to be generated.
  *
  * @retval  ::CA_STATUS_OK    Successful.
  * @retval  ::CA_STATUS_FAILED Operation failed.
@@ -257,7 +173,7 @@ CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t *endpoint,
                               const size_t rsrcServerDeviceIDLen,
                               const uint8_t* provServerDeviceID,
                               const size_t provServerDeviceIDLen,
-                              uint8_t* ownerPSK, const size_t ownerPSKSize);
+                              uint8_t* ownerPSK, const size_t ownerPskSize);
 
 /**
  * Initiate DTLS handshake with selected cipher suite.
@@ -277,11 +193,7 @@ CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint);
  * @retval  ::CA_STATUS_OK    Successful.
  * @retval  ::CA_STATUS_FAILED Operation failed.
  */
-CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint);
-
-#endif /* __WITH_DTLS__ */
-
-#ifdef __WITH_TLS__
+CAResult_t CAcloseSslSession(const CAEndpoint_t *endpoint);
 
 /**
  * Initiate TLS handshake with selected cipher suite.
@@ -291,7 +203,7 @@ CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint);
  * @retval  ::CA_STATUS_OK    Successful.
  * @retval  ::CA_STATUS_FAILED Operation failed.
  */
-CAResult_t CAinitiateTlsHandshake(const CAEndpoint_t *endpoint);
+CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint);
 
 /**
  * Close the DTLS session.
@@ -301,9 +213,7 @@ CAResult_t CAinitiateTlsHandshake(const CAEndpoint_t *endpoint);
  * @retval  ::CA_STATUS_OK    Successful.
  * @retval  ::CA_STATUS_FAILED Operation failed.
  */
-CAResult_t CAcloseTlsConnection(const CAEndpoint_t *endpoint);
-
-#endif /* __WITH_TLS__ */
+CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint);
 
 #ifdef __cplusplus
 } /* extern "C" */
index b2f9297..654e6f3 100644 (file)
@@ -174,7 +174,7 @@ src_dir = env.get('SRC_DIR')
 env.AppendUnique(LIBPATH = [src_dir + '/lib/android'])
 env.AppendUnique(LIBS = ['log', 'coap'])
 if env.get('SECURED') == '1':
-       env.AppendUnique(LIBS = ['tinydtls'])
+       env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
 
 # From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
 # Due to the limitation of Scons, it's required to added it into the command line
index 2376dac..8ccc9b1 100755 (executable)
@@ -55,6 +55,7 @@ mkdir -p $sourcedir/tmp/con/sample/external/inc
 cp -R $cur_dir/external/inc/* $sourcedir/tmp/con/sample/external/inc/
 
 cp -R ./extlibs/tinydtls/ $sourcedir/tmp/con/extlibs/
+cp -R ./extlibs/mbedtls/ $sourcedir/tmp/con/mbedtls/
 cp -R ./extlibs/timer/ $sourcedir/tmp/con/extlibs/
 cp -R ./extlibs/libcoap/ $sourcedir/tmp/con/extlibs/
 mkdir -p $sourcedir/tmp/con/c_common
@@ -86,6 +87,12 @@ cp -R $sourcedir/iotivity.pc.in $sourcedir/tmp/
 cd $sourcedir/tmp
 
 echo `pwd`
+if [ -d ./extlibs/mbedtls/mbedtls ];then
+    cd ./extlibs/mbedtls/mbedtls
+    git reset --hard ad249f509fd62a3bbea7ccd1fef605dbd482a7bd ; git apply --whitespace=fix ../ocf.patch
+    cd -
+    rm -rf ./extlibs/mbedtls/mbedtls/.git*
+fi
 
 whoami
 # Initialize Git repository
index 11e7823..222cd4e 100644 (file)
@@ -47,6 +47,9 @@ cp -f %{ROOTDIR}/con/src/libconnectivity_abstraction.so %{buildroot}/%{_libdir}
 cp -f %{ROOTDIR}/extlibs/libcoap/libcoap.a %{buildroot}/%{_libdir}
 if echo %{SECURED}|grep -qi '1'; then
        cp -f %{ROOTDIR}/con/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir}
+       cp -f %{ROOTDIR}/con/extlibs/mbedtls/libmbedcrypto.a %{buildroot}/%{_libdir}
+       cp -f %{ROOTDIR}/con/extlibs/tinydtls/libmbedtls.a %{buildroot}/%{_libdir}
+       cp -f %{ROOTDIR}/con/extlibs/tinydtls/libmbedx509.a %{buildroot}/%{_libdir}
 fi
 cp -rf %{ROOTDIR}/con/api/cacommon.h* %{DEST_INC_DIR}/
 cp -rf %{ROOTDIR}/con/inc/caadapterinterface.h* %{DEST_INC_DIR}/
  * limitations under the License.
  *
  ******************************************************************/
-#ifndef CA_ADAPTER_NET_TLS_H_
-#define CA_ADAPTER_NET_TLS_H_
+#ifndef CA_ADAPTER_NET_SSL_H_
+#define CA_ADAPTER_NET_SSL_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif //__cplusplus
 
 #include "caadapterutils.h"
 #include "cainterface.h"
@@ -54,7 +58,7 @@ CAResult_t CAsetTlsCipherSuite(const uint32_t cipher);
  * @param[in]  type  type of adapter.
  *
  */
-void CAsetTlsAdapterCallbacks(CAPacketReceivedCallback recvCallback,
+void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
                               CAPacketSendCallback sendCallback,
                               CATransportAdapter_t type);
 
@@ -67,7 +71,7 @@ void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
  * Register callback to get credential types.
  * @param[in]  typesCallback    callback to get credential types.
  */
-void CAsetTlsCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
+void CAsetSslCredentialsCallback(CAgetPskCredentialsHandler credCallback);
 
 /**
  * Close the TLS session
@@ -76,7 +80,7 @@ void CAsetTlsCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
  *
  * @retval  ::CA_STATUS_OK for success, otherwise some error value
  */
-CAResult_t CAcloseTlsConnection(const CAEndpoint_t *endpoint);
+CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint);
 
 /**
  * initialize mbedTLS library and other necessary initialization.
@@ -87,12 +91,12 @@ CAResult_t CAcloseTlsConnection(const CAEndpoint_t *endpoint);
  * @retval  ::CA_STATUS_FAILED Operation failed.
  *
  */
-CAResult_t CAinitTlsAdapter();
+CAResult_t CAinitSslAdapter();
 
 /**
  * de-inits mbedTLS library and free the allocated memory.
  */
-void CAdeinitTlsAdapter();
+void CAdeinitSslAdapter();
 
 /**
  * Performs TLS encryption of the CoAP PDU.
@@ -112,7 +116,7 @@ void CAdeinitTlsAdapter();
  *
  */
 
-CAResult_t CAencryptTls(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen);
+CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint, void *data, uint32_t dataLen);
 
 /**
  * Performs TLS decryption of the data.
@@ -127,7 +131,7 @@ CAResult_t CAencryptTls(const CAEndpoint_t *endpoint, void *data, uint32_t dataL
  * @retval  ::CA_STATUS_FAILED Operation failed.
  *
  */
-CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen);
+CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen);
 
 /**
  * Initiate TLS handshake with selected cipher suite.
@@ -136,28 +140,41 @@ CAResult_t CAdecryptTls(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t d
  *
  * @retval  ::CA_STATUS_OK for success, otherwise some error value
  */
-CAResult_t CAinitiateTlsHandshake(const CAEndpoint_t *endpoint);
+CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint);
 
 /**
  * Register callback to deliver the result of TLS handshake
  * @param[in] tlsHandshakeCallback Callback to receive the result of TLS handshake.
  */
-void CAsetTlsHandshakeCallback(CAErrorCallback tlsHandshakeCallback);
+void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback);
 
 /**
- * Generate ownerPSK using the PKCS#12 derivation function
+ * Generate ownerPSK using PRF
+ * OwnerPSK = TLS-PRF('master key' , 'oic.sec.doxm.jw',
+ *                                    'ID of new device(Resource Server)',
+ *                                    'ID of owner smart-phone(Provisioning Server)')
  *
+ * @param[in] endpoint  information of network address
+ * @param[in] label  Ownership transfer method e.g)"oic.sec.doxm.jw"
+ * @param[in] labelLen  Byte length of label
+ * @param[in] rsrcServerDeviceID  ID of new device(Resource Server)
+ * @param[in] rsrcServerDeviceIDLen  Byte length of rsrcServerDeviceID
+ * @param[in] provServerDeviceID  label of previous owner
+ * @param[in] provServerDeviceIDLen  byte length of provServerDeviceID
  * @param[in,out] ownerPSK  Output buffer for owner PSK
  * @param[in] ownerPSKSize  Byte length of the ownerPSK to be generated
- * @param[in] deviceID  ID of new device(Resource Server)
- * @param[in] deviceIDLen  Byte length of deviceID
  *
  * @retval  ::CA_STATUS_OK for success, otherwise some error value
  */
-CAResult_t CAtlsGenerateOwnerPSK(const CAEndpoint_t *endpoint,
-                                 uint8_t* ownerPSK, const size_t ownerPSKSize,
-                                 const uint8_t* deviceID, const size_t deviceIDLen);
-
-#endif /* CA_ADAPTER_NET_TLS_H_ */
+CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
+                    const uint8_t* label, const size_t labelLen,
+                    const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
+                    const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
+                    uint8_t* ownerPsk, const size_t ownerPskSize);
+#ifdef __cplusplus
+}
+#endif //__cplusplus
+
+#endif /* CA_ADAPTER_NET_SSL_H_ */
 
 
diff --git a/resource/csdk/connectivity/inc/pkix/cert.h b/resource/csdk/connectivity/inc/pkix/cert.h
deleted file mode 100644 (file)
index 03c6f7c..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-#ifndef _CERT_H_
-#define _CERT_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif //__cplusplus
-
-#include "byte_array.h"
-#include "pki_errors.h"
-
-/**
- * @struct CertificateX509
- *
- * Certificate structure.
- *
- * Structure fields contain byte arrays  pointed to relative DER certificate positions.
- */
-typedef struct
-{
-    ByteArray    tbs;       /**< TBS certificate.*/
-    ByteArray    serNum;    /**< Serial number.*/
-    ByteArray    pubKey;    /**< Public key.*/
-
-    ByteArray    signR;     /**< Signature  r value.*/
-    ByteArray    signS;     /**< Signature  s value.*/
-
-    ByteArray    issuer;    /**< Issuer name.*/
-    ByteArray    subject;   /**< Subject name.*/
-
-    ByteArray   validFrom;   /**< Start time of certificate validity. */
-    ByteArray   validTo;     /**< End time of certificate validity. */
-
-} CertificateX509;
-
-/**
- * Reads certificate from byte array and write it into certificate structure.
- *
- * @param[in] code  Byte array with DER encoded certificate
- * @param[out] crt  Pointer to certificate structure
- * @return  PKI_SUCCESS if successful
- */
-PKIError DecodeCertificate(ByteArray code, CertificateX509 *crt);
-
-/**
- * Parse ECDSA public key, remove ASN.1 extra bytes.
- *
- * @param ByteArray structure which contains public key
- * @return PKI_SUCCESS if public key is correct, error code in case of invalid key
- */
-PKIError ParsePublicKey(ByteArray *caPublicKey);
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-
-
-#endif //_CERT_H_
diff --git a/resource/csdk/connectivity/inc/pkix/crl.h b/resource/csdk/connectivity/inc/pkix/crl.h
deleted file mode 100644 (file)
index 9f91e5a..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef _CRL_H_
-#define _CRL_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif //__cplusplus
-
-#include "byte_array.h"
-#include "pki_errors.h"
-
-/// Maximal number of revoked certificates in list
-#ifdef WITH_ARDUINO
-#define CRL_MAX_LEN              (256)
-#else
-#define CRL_MAX_LEN              (1024)
-#endif // WITH_ARDUINO
-/**
- * @struct CertificateList
- *
- * CRL structure.
- *
- * Structure fields contain byte arrays  pointed to relative DER certificate positions.
- */
-typedef struct
-{
-    ByteArray    tbs;       /**< TBS sequence of CRL.*/
-    ByteArray    issuer;    /**< Issuer name.*/
-    ByteArray    date;      /**< The issue-date for CRL.*/
-    ByteArray    signR;     /**< Signature  r value.*/
-    ByteArray    signS;     /**< Signature  s value.*/
-} CertificateList;
-
-/**@def CRL_INITIALIZER
- *
- * Initializes of existing CRL fields to {NULL, 0}.
- */
-#undef CRL_INITIALIZER
-#define CRL_INITIALIZER {BYTE_ARRAY_INITIALIZER,\
-                         BYTE_ARRAY_INITIALIZER,\
-                         BYTE_ARRAY_INITIALIZER,\
-                         BYTE_ARRAY_INITIALIZER,\
-                         BYTE_ARRAY_INITIALIZER}
-
-#ifdef X509_DEBUG
-/**
- * Prints Certificate List to console.
- *
- * @param crl - pointer to certificate list structure
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError PrintCRL(const CertificateList *const crl);
-#endif
-
-/**
- * Decodes and checks Certificate List.
- *
- * @param code - certificate list structure in DER format
- * @param crl - pointer to certificate list structure
- * @param caPubKey - ByteArray structure contains CA public key
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError DecodeCertificateList(ByteArray code, CertificateList *crl,  ByteArray caPubKey);
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-#endif //_CRL_H_
diff --git a/resource/csdk/connectivity/inc/pkix/crypto_adapter.h b/resource/csdk/connectivity/inc/pkix/crypto_adapter.h
deleted file mode 100644 (file)
index bef054c..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef _CRYPTO_ADAPTER_H_
-#define _CRYPTO_ADAPTER_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif //__cplusplus
-
-#include "ecc.h"
-#include "sha2.h"
-
-/// Sizes for ECDSA prime256v1 elliptic curve
-#define PUBLIC_KEY_SIZE     (64)
-#define SIGN_R_LEN          (32)
-#define SIGN_S_LEN          (32)
-#define SIGN_FULL_SIZE      (64)
-#define PRIVATE_KEY_SIZE    (32)
-
-/// Length of SHA 256 hash
-#define SHA_256_HASH_LEN    (32)
-
-#define uECC_SIGN_VERIFICATION_SUCCESS (1)
-
-/**
- * @def GET_SHA_256(tbs, sha256)
- *
- * A macro that compute sha-256 hash of tbs part.
- *
- * @param[in] tbs "to be signed" part
- * @param[out] sha256 hash of tbs
- */
-#undef GET_SHA_256
-#define GET_SHA_256(tbs, sha256) do{                     \
-        dtls_sha256_ctx ctx256;                          \
-        dtls_sha256_init(&ctx256);                       \
-        dtls_sha256_update(&ctx256, tbs.data, tbs.len);  \
-        dtls_sha256_final(sha256, &ctx256);              \
-    }while(0)
-
-/**@def CHECK_SIGN(structure, caPubKey)
- * Checks the sign of ASN.1 structure.
- *
- * @param structure ASN.1 stucture
- * @param caPubKey public key of CA
- */
-#undef CHECK_SIGN
-#define CHECK_SIGN(structure, caPubKey) do{                                  \
-    int err;                                                                 \
-    uint8_t sha256[SHA_256_HASH_LEN];                                        \
-    uint8_t fullSignature[SIGN_FULL_SIZE];                                   \
-    GET_SHA_256((structure).tbs, sha256);                                    \
-    memcpy(fullSignature, (structure).signR.data, SIGN_R_LEN);               \
-    memcpy((fullSignature + SIGN_R_LEN), (structure).signS.data, SIGN_S_LEN);\
-    err = uECC_verify(caPubKey.data, sha256, fullSignature);                 \
-    CHECK_EQUAL(err, uECC_SIGN_VERIFICATION_SUCCESS, PKI_SIG_MISMATCH);      \
-    }while(0)
-
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-#endif //_CRYPTO_ADAPTER_H_
diff --git a/resource/csdk/connectivity/inc/pkix/der_dec.h b/resource/csdk/connectivity/inc/pkix/der_dec.h
deleted file mode 100644 (file)
index b26938a..0000000
+++ /dev/null
@@ -1,144 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-#ifndef _DER_DEC_H_
-#define _DER_DEC_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif //__cplusplus
-
-#include "byte_array.h"
-#include "pki_errors.h"
-#include "crypto_adapter.h"
-
-/// Maximal octet number in certificate's serial number
-#define SERIAL_NUMBER_MAX_LEN    (20)
-/**
- * @name DER constants
- * These constants comply with DER encoded the ANS.1 type tags.
- * DER encoding uses hexadecimal representation.
- */
-#define DER_UNIVERSAL               (0x00)
-#define DER_SEQUENCE                (0x30)
-#define DER_OBJECT_IDENTIFIER       (0x06)
-#define DER_BIT_STRING              (0x03)
-#define DER_INTEGER                 (0x02)
-#define DER_UTC_TIME                (0x17)
-#define DER_VERSION                 (0xa0)
-
-/* The first octet of the OCTET STRING indicates whether the key is
-compressed or uncompressed.  The uncompressed form is indicated by 0x04
-and the compressed form is indicated by either 0x02 or 0x03 (RFC 5480)*/
-#define ASN1_UNCOMPRESSED_KEY   (0x04)
-/// ASN.1 UTC time length
-#define UTC_TIME_LEN            (13)
-///  Length Octet ASN.1
-#define LEN_LONG                (128)
-/// Size of byte
-#define SIZE_OF_BYTE            (8)
-
-#define ECDSA_WITH_SHA256_OID_LEN    (8)
-#define EC_PUBLIC_KEY_OID_LEN        (7)
-#define PRIME_256_V1_OID_LEN         (8)
-
-/**@def SKIP_DER_FIELD(array, type, length)
- * Skips the field in the ASN.1 structure.
- *
- * @param array pointer to ASN.1 stucture
- * @param type type of ASN.1 field
- * @param length length of ASN.1 field
- */
-#undef SKIP_DER_FIELD
-#define SKIP_DER_FIELD(array, type, length) do{                 \
-        CHECK_EQUAL(*((array).data), type, PKI_INVALID_FORMAT); \
-        CHECK_CALL(DecodeLength , &(array), &(length));         \
-        INC_BYTE_ARRAY(array, length);                          \
-        }while(0)
-
-/**@def COPY_DER_FIELD(array, str, field, type, length)
- * Copies the field from the ASN.1 structure.
- *
- * @param array pointer to ASN.1 stucture
- * @param str structure in which the array is copied
- * @param field field of the structure in which the array is copied
- * @param type type of ASN.1 field
- * @param length length of ASN.1 field
- */
-#undef COPY_DER_FIELD
-#define COPY_DER_FIELD(array, crt, field, type, length) do{     \
-        CHECK_EQUAL(*((array).data), type, PKI_INVALID_FORMAT); \
-        CHECK_CALL(DecodeLength , &(array), &(length));         \
-        ((crt)->field).data = (array).data;                     \
-        ((crt)->field).len = length;                            \
-        INC_BYTE_ARRAY(array, length);                          \
-        }while(0)
-
-
-/**@def CHECK_DER_OID(array, oid, length)
- * Checks the field from the ASN.1 structure.
- *
- * @param array pointer to ASN.1 stucture
- * @param oid type of DER object
- * @param oidLen length of DER array
- * @param length length of ASN.1 field
- */
-#undef CHECK_DER_OID
-#undef CHECK_DER_OID
-#define CHECK_DER_OID(array, oid, oidLen, length) do{                              \
-        int ret = 0;                                                               \
-        CHECK_EQUAL(*((array).data), DER_OBJECT_IDENTIFIER, PKI_INVALID_FORMAT);   \
-        CHECK_CALL(DecodeLength , &(array), &(length));                            \
-        CHECK_EQUAL(length, oidLen, PKI_UNKNOWN_OID);                              \
-        ret = memcmp ((array).data, oid, oidLen);                                  \
-        CHECK_EQUAL(ret, 0, PKI_UNKNOWN_OID);                                      \
-        }while(0)
-
-/**@def PARSE_SIGNATURE(structure)
- * Parse signature of ASN.1 structure , remove ASN.1 extra bytes.
- *
- * @param structure Certificate or CertificateList structure
- */
-#undef PARSE_SIGNATURE
-#define PARSE_SIGNATURE(structure) do{                                                       \
-        if (((structure)->signR.len == SIGN_R_LEN + 1) && ((structure)->signR.data[0] == 0)) \
-        INC_BYTE_ARRAY((structure)->signR, 1);                                               \
-        else if ((structure)->signR.len != SIGN_R_LEN)                                       \
-        CHECK_NULL(NULL, PKI_WRONG_ARRAY_LEN);                                               \
-        if (((structure)->signS.len == SIGN_S_LEN + 1) && ((structure)->signS.data[0] == 0)) \
-        INC_BYTE_ARRAY((structure)->signS, 1);                                               \
-        else if ((structure)->signS.len != SIGN_S_LEN)                                       \
-        CHECK_NULL(NULL, PKI_WRONG_ARRAY_LEN);                                               \
-        }while(0)
-
-/**
- * Computes length of ASN.1 object in DER format.
- *
- * @param[in] code array with DER encoded ASN.1 structure
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError DecodeLength(ByteArray *code, size_t *length);
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-
-
-#endif //_X509_PARSE_H_
diff --git a/resource/csdk/connectivity/inc/pkix/pki.h b/resource/csdk/connectivity/inc/pkix/pki.h
deleted file mode 100644 (file)
index 221b6a9..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef _PKI_H_
-#define _PKI_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "byte_array.h"
-#include "pki_errors.h"
-#include "crypto_adapter.h"
-#include "cert.h"
-
-/**
- * Maximal number of certificates in trust chain.
- */
-#define MAX_CHAIN_LEN    (3)
-
-/**
- * Maximal length of the TLS certificate message.
- */
-#define MAX_CERT_MESSAGE_LEN (2048)
-
-#ifdef X509_DEBUG
-/**
- * Prints Certificate to console.
- *
- * @param crt - pointer to Certificate structure
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError PrintCertificate(const CertificateX509 *const crt);
-#endif
-
-/**
- * Checks certificate validity period.
- *
- * @param dateFrom - array with not before field
- * @param dateTo - array with not after field
- * @return PKI_SUCCESS if valid, error code otherwise
- */
-PKIError CheckValidity(ByteArray dateFrom, ByteArray dateTo);
-
-/**
- * Checks certificate date and sign.
- *
- * @param[in] certDerCode - Byte array with DER encoded certificate
- * @param[in] caPublicKey - CA public key
- * @return  0 if successful
- */
-PKIError CheckCertificate(ByteArray certDerCode, ByteArray caPublicKey);
-
-/**
- * Parses each certificates from list.
- *
- * @param[in] chainDerCode Array of DER encoded certificates
- * @param[out] chainCrt Array of parsed certificates
- * @param[in] chainLen Lengths of array
- * @returns  PKI_SUCCESS if no error is occurred
- */
-PKIError ParseCertificateChain (ByteArray *chainDerCode, CertificateX509 *chainCrt,
-                                uint8_t chainLen);
-
-/**
- * Loads certificates in DER format from TLS message to array.
- *
- * @param[in] msg TLS message with certificate's chain
- * @param[out] chain Array of DER encoded certificates
- * @param[out] chainLen Lengths of array
- * @returns  PKI_SUCCESS if no error is occurred
- */
-PKIError LoadCertificateChain (ByteArray msg, ByteArray *chain, uint8_t *chainLength);
-
-/**
- * Checks the signature of each certificate in chain.
- *
- * @param[in] chainCrt Chain of certificates structures
- * @param[in] chainLen Number of certificates in the chain
- * @param[in] caPubKey Public key which sign the last certificate from chain
- * @returns PKI_SUCCESS if no error is occurred
- */
-PKIError CheckCertificateChain (CertificateX509 *chainCrt, uint8_t chainLen, ByteArray caPubKey);
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-#endif // _PKI_H_
diff --git a/resource/csdk/connectivity/inc/pkix/pki_errors.h b/resource/csdk/connectivity/inc/pkix/pki_errors.h
deleted file mode 100644 (file)
index 0d7477f..0000000
+++ /dev/null
@@ -1,320 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef _PKI_ERRORS_H_
-#define _PKI_ERRORS_H_
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif //__cplusplus
-
-#ifdef X509_DEBUG
-#warning "DEBUG is enabled"
-#include <stdio.h>  // <printf>
-#endif
-
-/**
- * @enum PKIError
- *
- * The enumeration of error codes.
- */
-
-typedef enum
-{
-    PKI_SUCCESS = 0,         /**< No error occurred. */
-    PKI_UNKNOWN_ERROR,       /**< Unknown error occurred. */
-    PKI_NULL_PASSED,         /**< NULL passed to function. */
-    PKI_CERT_DATE_INVALID,   /**< Certificate date expired. */
-    PKI_BUFFER_OVERFLOW,     /**< Array out of range. */
-    PKI_WRONG_OCTET_LEN,     /**< Wrong length of octet. */
-    PKI_UNKNOWN_OID,         /**< Requested OID is unknown. */
-    PKI_INVALID_FORMAT,      /**< The CRT/CRL/CSR format is invalid. */
-    PKI_INVALID_DATE_FORMAT, /**< The date tag or value is invalid. */
-    PKI_INVALID_SIGNATURE,   /**< The signature tag or value invalid. */
-    PKI_SIG_MISMATCH,        /**< Signature algorithms do not match.  */
-    PKI_CERT_VERIFY_FAILED,  /**< Certificate verification failed*/
-    PKI_CERT_REVOKED,        /**< Certificate is revoked. */
-    PKI_WRONG_ARRAY_LEN,     /**< Wrong length of input array*/
-    PKI_MEMORY_ALLOC_FAILED, /**< Failed to allocate memory */
-    PKI_BASE64_ERROR,        /**< Base64 convertion error occurred. */
-    PKI_JSON_ERROR,          /**< JSON convertion error occurred. */
-    PKI_JSON_NOT_FOUND,       /**< JSON object not found. */
-
-    ISSUER_CA_STORAGE_FILE_READ_ERROR,          /**< File read error in CA storage */
-    ISSUER_CA_STORAGE_FILE_WRITE_ERROR,         /**< File write error in CA storage */
-    ISSUER_CA_STORAGE_CRL_READ_ERROR,           /**< CRL file read error in CA storage */
-    ISSUER_CA_STORAGE_CRL_WRITE_ERROR,          /**< CRL file write error in CA storage */
-    ISSUER_CA_STORAGE_CRT_READ_ERROR,           /**< Certificate file read error in CA storage */
-    ISSUER_CA_STORAGE_CRT_WRITE_ERROR,          /**< Certificate file write error in CA storage */
-    ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED,      /**< Failed to allocate memory in CA storage */
-    ISSUER_CA_STORAGE_WRONG_SERIAL_NUMBER,      /**< Wrong serial number passed to CA storage */
-    ISSUER_CA_STORAGE_SN_UNDEFINED,             /**< Serial number is not defined in CA storage */
-    ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER,  /**< Wrong CRL serial number passed to CA
-                                                     storage */
-    ISSUER_CA_STORAGE_CRL_SN_UNDEFINED,         /**< CRL serial number is not defined in CA
-                                                     storage */
-    ISSUER_CA_STORAGE_WRONG_PRIVATE_KEY_LEN,    /**< Passed private key length not equal to
-                                                     PRIVATE_KEY_SIZE*/
-    ISSUER_CA_STORAGE_PRIVATE_KEY_UNDEFINED,    /**< CA private key is not defined in CA storage */
-    ISSUER_CA_STORAGE_WRONG_PUBLIC_KEY_LEN,     /**< Passed public key length not equal to
-                                                     PUBLIC_KEY_SIZE*/
-    ISSUER_CA_STORAGE_PUBLIC_KEY_UNDEFINED,     /**< CA public key is not defined in CA storage */
-    ISSUER_CA_STORAGE_CA_CHAIN_LENGTH_UNDEFINED,/**< CA certificate chain length is not defined in
-                                                     CA storage */
-    ISSUER_CA_STORAGE_WRONG_CA_NAME_LEN,        /**< CA name length is bigger than
-                                                     ISSUER_MAX_NAME_SIZE */
-    ISSUER_CA_STORAGE_CA_NAME_UNDEFINED,        /**< CA name is not defined in CA storage */
-    ISSUER_CA_STORAGE_CRL_UNDEFINED,            /**< CRL is not defined in CA storage */
-    ISSUER_CA_STORAGE_NULL_PASSED,              /**< NULL passed to function in CA storage */
-    CKM_INFO_IS_NOT_INIT,                       /**< CKM info storage was not init */
-    ISSUER_CA_STORAGE_WRONG_BYTE_ARRAY_LEN,     /**< ByteArray with wrong lenth passed into
-                                                     CA storage */
-
-    ISSUER_MAKE_KEY_ERROR,      /**< Error during uECC_make_key() */
-    ISSUER_MEMORY_ALLOC_FAILED, /**< Failed to allocate memory in issuer */
-    ISSUER_FILE_WRITE_ERROR,    /**< File write error in issuer */
-    ISSUER_WRONG_SERIAL_NUMBER, /**< Wrong serial number passed to issuer */
-    ISSUER_WRONG_ROOT_NAME_LEN, /**< CA name length is bigger than ISSUER_MAX_NAME_SIZE */
-    ISSUER_NULL_PASSED,         /**< NULL passed to function in issuer */
-    ISSUER_WRONG_BYTE_ARRAY_LEN,/**< ByteArray with wrong length passed into issuer */
-
-    ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED, /**< Failed to allocate memory in CRL encoder */
-    ISSUER_CRL_ENCODER_DER_ENCODE_FAIL,     /**< Failed to encode structure into DER
-                                                 in CRL encoder */
-    ISSUER_CRL_ENCODER_SIGNATURE_FAIL,      /**< Failed to sign TBS in CRL encoder */
-    ISSUER_CRL_NULL_PASSED,                 /**< NULL passed to function in CRL encoder */
-    ISSUER_CRL_WRONG_BYTE_ARRAY_LEN,        /**< ByteArray with wrong length passed into
-                                                 CRL encoder */
-
-    ISSUER_CSR_MEMORY_ALLOC_FAILED, /**< Failed to allocate memory in CSR unit */
-    ISSUER_CSR_DER_ENCODE_FAIL,     /**< Failed to encode structure into DER in CSR unit */
-    ISSUER_CSR_SIGNATURE_FAIL,      /**< Failed to sign TBS in CSR unit */
-    ISSUER_CSR_DER_DECODE_FAIL,     /**< Failed to decode structure from DER in CSR unit */
-    ISSUER_CSR_INVALID_SIGNATURE,   /**< Signature check fail in CSR unit. */
-    ISSUER_CSR_TOO_LONG_NAME,       /**< CSR subject name length is bigger than CSR_MAX_NAME_SIZE */
-    ISSUER_CSR_INVALID_KEY_FORMAT,  /**< Public key format is invalid in CSR unit. */
-    ISSUER_CSR_NULL_PASSED,         /**< NULL passed to function in CSR unit */
-    ISSUER_CSR_WRONG_BYTE_ARRAY_LEN,/**< ByteArray with wrong length passed into CSR unit */
-
-    ISSUER_X509_MEMORY_ALLOC_FAILED, /**< Failed to allocate memory in X.509 encoder */
-    ISSUER_X509_DER_ENCODE_FAIL,     /**< Failed to encode structure into DER in X.509 encoder */
-    ISSUER_X509_SIGNATURE_FAIL,      /**< Failed to sign TBS in X.509 encoder */
-    ISSUER_X509_NULL_PASSED,         /**< NULL passed to function in X.509 encoder */
-    ISSUER_X509_WRONG_BYTE_ARRAY_LEN /**< ByteArray with wrong length passed into X.509 encoder */
-} PKIError;
-
-
-/** @def CHECK_PRINT(err_code, ...)
- *
- * Prints debug information \a err_code and  __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__ values.
- *
- * @param[in] err_code Error code
-*/
-#ifdef X509_DEBUG
-#define CHECK_PRINT(err_code) \
-fprintf(stderr, "%s() in %s, line %i: %d\n",__func__, __FILE__, __LINE__, err_code);
-#else
-# define CHECK_PRINT(...)
-#endif
-
-/**
- * @def CHECK_NULL(param, error)
- * A macro that checks whether \a param is not NULL.
- *
- * If \a (param = NULL) it goes to error processing with \a error code.
- *
- * @param[in] param  Parameter to check
- * @param[in] error Error code
- */
-#define CHECK_NULL(param, error) do {   \
-        if  (!(param)) {                \
-            error_value = error;        \
-            CHECK_PRINT(error);         \
-            goto ERROR_PROC;            \
-        } } while(0)
-
-/** @def CHECK_EQUAL(param, checker, err_code)
- *
- * A macro that checks whether \a param equal to \a checker.
- *
- * If \a (param != checker) it goes to error processing with \a err_code error code.
- *
- * @param[in] param  Parameter to check
- * @param[in] error Error code
- */
-#define CHECK_EQUAL(param, checker, err_code) do { \
-        if ((param) != (checker)) {                \
-            error_value = err_code;                \
-            CHECK_PRINT(err_code);                 \
-            goto ERROR_PROC;                       \
-        } } while(0)
-
-/** @def CHECK_NOT_EQUAL(param, checker, err_code)
- * A macro that checks whether \a param not equal to \a checker.
- *
- * If \a (param == checker) it goes to error processing with \a err_code error code.
- *
- * @param[in] param  Parameter to check
- * @param[in] error Error code
- */
-#define CHECK_NOT_EQUAL(param, checker, err_code) do { \
-        if ((param) == (checker)) {                    \
-            error_value = err_code;                    \
-            CHECK_PRINT(err_code);                     \
-            goto ERROR_PROC;                           \
-        } } while(0)
-
-/** @def CHECK_LESS(param, checker, err_code)
- * A macro that checks whether \a param less then \a checker.
- *
- * If \a (param > checker) it goes to error processing with \a err_code error code.
- *
- * @param[in] param  Parameter to check
- * @param[in] error error code
- */
-#define CHECK_LESS(param, checker, err_code) do { \
-        if ((param) >= (checker)) {               \
-            error_value = err_code;               \
-            CHECK_PRINT(err_code);                \
-            goto ERROR_PROC;                      \
-        } } while(0)
-
-/** @def CHECK_COND(param, err_code)
- *
- * A macro that checks whether condition \a param is true.
- *
- * If \a (param != true) it goes to error processing with \a err_code error code.
- *
- * @param[in] param  Parameter to check
- * @param[in] error error code
- */
-#define CHECK_COND(param, err_code) do { \
-        if (!(param)) {                  \
-            error_value = err_code;      \
-            CHECK_PRINT(err_code);       \
-            goto ERROR_PROC;             \
-        } } while(0)
-
-/** @def CHECK_LESS_EQUAL(param, checker, err_code)
-*
-* A macro that checks whether \a param <= \a checker.
-*
-* If \a (param < checker) it goes to error processing with \a err_code error code.
-*
-* @param[in] param  Parameter to check
-* @param[in] error error code
-*/
-#define CHECK_LESS_EQUAL(param, checker, err_code) do { \
-        if ((param) > (checker)) {                      \
-            error_value = err_code;                     \
-            CHECK_PRINT(err_code);                      \
-            goto ERROR_PROC;                            \
-        } } while(0)
-
-/** @def CHECK_NULL_BYTE_ARRAY_PTR(param, err_code)
- *
- * A macro that checks whether pointer to ByteArray \a param is not NULL and contains a valid pointer.
- *
- * If \a (param != checker) it goes to error processing with \a err_code error code.
- *
- * @param[in] param  Parameter to check
- * @param[in] err_code Error code
- */
-#define CHECK_NULL_BYTE_ARRAY_PTR(param, err_code) do { \
-        CHECK_NULL(param, err_code);                    \
-        CHECK_NULL((param)->data, err_code);            \
-        CHECK_NULL((param)->len, err_code);             \
-    } while(0)
-
-/** @def FUNCTION_INIT(...)
- * A macro for initializations function variables.
- *
- * If error occurs it goes to error processing.
- */
-#define FUNCTION_INIT(...)                    \
-    PKIError error_value = PKI_UNKNOWN_ERROR; \
-    __VA_ARGS__;
-
-/** @def FUNCTION_CLEAR(...)
- *
- * A macro for freeing  function variables.
- *
- * @return  0 if successful
- */
-#define FUNCTION_CLEAR(...)    \
-    error_value = PKI_SUCCESS; \
-    ERROR_PROC:                \
-    __VA_ARGS__                \
-    return error_value;
-
-/** @def CHECK_CALL(fn, ...)
- * A macro that checks \a fn function return code
- *
- * If function return error code it goes to error processing.
- *
- * @param[in] fn  Function to call
- */
-#define CHECK_CALL(fn, ...) do {                    \
-        error_value = fn(__VA_ARGS__);              \
-        if ((int)error_value != (int)PKI_SUCCESS) { \
-            CHECK_PRINT(error_value);               \
-            goto ERROR_PROC;                        \
-        } } while(0)
-
-/** @def CHECK_INC_BYTE_ARRAY_PTR(array, size)
- *
- * Increments byte array pointer \a array by \a size with bound checking.
- *
- * @param array byte array pointer
- * @param size number of positions
- */
-#undef CHECK_INC_BYTE_ARRAY_PTR
-#define CHECK_INC_BYTE_ARRAY_PTR(array, size) do{   \
-        if (size > ((array)->len)){                 \
-            error_value = PKI_BUFFER_OVERFLOW;      \
-            CHECK_PRINT(error_value);               \
-            goto ERROR_PROC; }                      \
-        INC_BYTE_ARRAY_PTR(array, size);            \
-    }while(0)
-
-/** @def CHECK_INC_BYTE_ARRAY(array, size)
- *
- * Increments byte array \a array by \a size with bound checking.
- *
- * @param array byte array pointer
- * @param size number of positions
- */
-#undef CHECK_INC_BYTE_ARRAY
-#define CHECK_INC_BYTE_ARRAY(array, size) do{   \
-        if (size > ((array).len)) {             \
-            error_value = PKI_BUFFER_OVERFLOW;  \
-            CHECK_PRINT(error_value);           \
-            goto ERROR_PROC; }                  \
-        INC_BYTE_ARRAY(array, size);            \
-    }while(0)
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-
-#endif // _PKI_ERRORS_H_
diff --git a/resource/csdk/connectivity/inc/pkix/sn_store.h b/resource/csdk/connectivity/inc/pkix/sn_store.h
deleted file mode 100644 (file)
index 50d8ff2..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-#ifndef _SN_STORE_H_
-#define _SN_STORE_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif //__cplusplus
-
-#include "pki_errors.h"
-#include "byte_array.h"
-
-
-/**
- * Stores serial number to SN storage.
- *
- * @param[in] serNum certificate serial number to be stored
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError StoreSerialNumber(const ByteArray serNum);
-
-/**
- * Check whether there is \a serNum in SN storage.
- *
- * @param[in] serNum certificate serial number to be stored
- * @return PKI_SUCCESS if \a not belongs SN storage, error code otherwise
- */
-PKIError CheckSerialNumber(const ByteArray serNum);
-
-
-#ifdef X509_DEBUG
-/**
- * Prints all serial numbers from SN storage.
- */
-void PrintSNStore(void);
-#endif
-
-
-/**
- * Frees memory occupied by SN storage.
- */
-void FreeSNStore(void);
-
-
-#ifdef __cplusplus
-}
-#endif //__cplusplus
-#endif //_SN_STORE_H_
-
index e944ce9..66b94f2 100644 (file)
@@ -56,11 +56,6 @@ env.SConscript(os.path.join(root_dir, 'util', 'SConscript'))
 # is interpreted by SCons as the top-level iotivity directory where
 # the SConscruct file is found.
 build_dir = env.get('BUILD_DIR')
-if env.get('SECURED') == '1':
-       env.SConscript(build_dir + 'extlibs/tinydtls/SConscript')
-       env.SConscript(build_dir + 'extlibs/timer/SConscript')
-       env.AppendUnique(CPPPATH = ['#extlibs/timer'])
-       env.AppendUnique(CPPPATH = [src_dir + '/resource/csdk/connectivity/inc/pkix'])
 
 env.AppendUnique(CA_SRC = [os.path.join(ca_path,
                                         'adapter_util/caadapterutils.c')])
@@ -70,23 +65,11 @@ if (('BLE' in ca_transport) or ('ALL' in ca_transport)):
                                           'adapter_util/cafragmentation.c')])
 
 if env.get('SECURED') == '1':
-       env.AppendUnique(CA_SRC = [os.path.join(ca_path,
-                                                'adapter_util/caadapternetdtls.c')])
-       env.AppendUnique(CPPPATH = [os.path.join(root_dir,
-                                                 'external/inc')])
-if env.get('DTLS_WITH_X509') == '1':
-       env.AppendUnique(CPPPATH = [src_dir + '/resource/csdk/connectivity/inc/pkix'])
-       env.AppendUnique(CPPPATH = [src_dir + '/extlibs/tinydtls/ecc/'])
-       env.AppendUnique(CPPPATH = [src_dir + '/extlibs/tinydtls/sha2/'])
-       env.AppendUnique(CPPDEFINES = ['__WITH_X509__'])
-       if not env.get('RELEASE'):
-               env.AppendUnique(CPPDEFINES = ['X509_DEBUG'])
-       pkix_src = Glob('adapter_util/pkix/*.c');
-       env.AppendUnique(CA_SRC = pkix_src)
-
-if ((secured == '1') and (with_tcp == True)):
-       env.AppendUnique(CPPPATH = [os.path.join(src_dir, 'resource', 'csdk', 'security', 'include')])
-       env.AppendUnique(CPPDEFINES = ['__WITH_TLS__'])
+       env.SConscript(build_dir + 'extlibs/tinydtls/SConscript')
+       env.AppendUnique(CPPPATH = ['#extlibs/tinydtls'])
+       env.AppendUnique(CPPPATH = [src_dir + '/resource/csdk/security/include'])
+       env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
+       env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'external/inc')])
        tls_path = 'extlibs/mbedtls';
        tls_headers_path = 'mbedtls/include';
        if ca_os == 'tizen' and os.path.exists(root_dir + '/' + tls_path):
@@ -96,7 +79,11 @@ if ((secured == '1') and (with_tcp == True)):
                if ca_os != 'android':
                        env.SConscript('#' + tls_path + '/SConscript')
                env.AppendUnique(CPPPATH = ['#' + tls_path + '/' + tls_headers_path])
-               env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'adapter_util/ca_adapter_net_tls.c')])
+               env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'adapter_util/ca_adapter_net_ssl.c')])
+
+if ((secured == '1') and (with_tcp == True)):
+       env.AppendUnique(CPPDEFINES = ['__WITH_TLS__'])
+
 
 ca_common_src = None
 
@@ -133,12 +120,6 @@ else:
        if (('IP' in ca_transport) or ('ALL' in ca_transport)):
                env.AppendUnique(CA_SRC = [os.path.join(ca_path, 'cablockwisetransfer.c') ])
                env.AppendUnique(CPPDEFINES = ['WITH_BWT'])
-       if secured == '1':
-               env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__'])
-               if ca_os == 'tizen' and os.path.exists(root_dir + '/extlibs/tinydtls'):
-                       env.AppendUnique(CPPPATH = [os.path.join(root_dir, 'extlibs/tinydtls')])
-               else:
-                       env.AppendUnique(CPPPATH = ['#extlibs/tinydtls'])
 
 ca_common_src = [
         os.path.join(ca_path, d) for d in ca_common_src ]
@@ -214,8 +195,7 @@ if ca_os == 'android':
 if ca_os in ['android', 'tizen', 'linux', 'yocto']:
        lib_env.AppendUnique(LIBS = ['coap'])
        if lib_env.get('SECURED') == '1':
-               lib_env.AppendUnique(LIBS = ['tinydtls'])
-               lib_env.AppendUnique(LIBS = ['timer'])
+               lib_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
        if ca_os != 'android':
                lib_env.AppendUnique(LIBS = ['rt'])
                if ((lib_env.get('SECURED') == '1') and ((lib_env.get('WITH_TCP')) or (lib_env.get('WITH_CLOUD')))):
@@ -226,8 +206,7 @@ if ca_os in ['android', 'tizen', 'linux', 'yocto']:
 elif ca_os in ['msys_nt', 'windows']:
        lib_env.AppendUnique(LIBS = ['coap', 'mswsock', 'ws2_32', 'iphlpapi', 'logger'])
        if lib_env.get('SECURED') == '1':
-               lib_env.AppendUnique(LIBS = ['tinydtls'])
-               lib_env.AppendUnique(LIBS = ['timer'])
+               lib_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto'])
        calib = lib_env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
 else:
        calib = lib_env.StaticLibrary('connectivity_abstraction', lib_env.get('CA_SRC'))
diff --git a/resource/csdk/connectivity/src/adapter_util/ca_adapter_net_ssl.c b/resource/csdk/connectivity/src/adapter_util/ca_adapter_net_ssl.c
new file mode 100644 (file)
index 0000000..58b4633
--- /dev/null
@@ -0,0 +1,2005 @@
+/******************************************************************
+ *
+ * Copyright 2016 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#define _GNU_SOURCE
+
+#include <stddef.h>
+#include <stdbool.h>
+#include "ca_adapter_net_ssl.h"
+#include "cacommon.h"
+#include "caipinterface.h"
+#include "oic_malloc.h"
+#include "byte_array.h"
+#include "octhread.h"
+
+// headers required for mbed TLS
+#include "mbedtls/platform.h"
+#include "mbedtls/ssl.h"
+#include "mbedtls/entropy.h"
+#include "mbedtls/ctr_drbg.h"
+#include "mbedtls/pkcs12.h"
+#include "mbedtls/ssl_internal.h"
+#ifdef __WITH_DTLS__
+#include "mbedtls/timing.h"
+#include "mbedtls/ssl_cookie.h"
+#endif
+
+#ifndef NDEBUG
+#include "mbedtls/debug.h"
+#include "mbedtls/version.h"
+#endif
+
+#ifdef __unix__
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#endif
+
+
+/**
+ * @def MBED_TLS_VERSION_LEN
+ * @brief mbedTLS version string length
+ */
+#define MBED_TLS_VERSION_LEN (16)
+/**
+ * @def SEED
+ * @brief Seed for initialization RNG
+ */
+#define SEED "IOTIVITY_RND"
+/**
+ * @def UUID_PREFIX
+ * @brief uuid prefix in certificate subject field
+ */
+#define UUID_PREFIX "uuid:"
+/**
+ * @def USERID_PREFIX
+ * @brief userid prefix in certificate alternative subject name field
+ */
+#define USERID_PREFIX "userid:"
+
+/**
+ * @def NET_SSL_TAG
+ * @brief Logging tag for module name
+ */
+#define NET_SSL_TAG "OIC_CA_NET_SSL"
+/**
+ * @def MBED_TLS_TAG
+ * @brief Logging tag for mbedTLS library
+ */
+#define MBED_TLS_TAG "MBED_TLS"
+/**
+ * @def MMBED_TLS_DEBUG_LEVEL
+ * @brief Logging level for mbedTLS library
+ */
+#define MBED_TLS_DEBUG_LEVEL (4)
+
+/**
+ * @def TLS_MSG_BUF_LEN
+ * @brief Buffer size for TLS record. A single TLS record may be up to 16384 octets in length
+ */
+
+#define TLS_MSG_BUF_LEN (16384)
+/**
+ * @def PSK_LENGTH
+ * @brief PSK keys max length
+ */
+#define PSK_LENGTH (256/8)
+/**
+ * @def UUID_LENGTHPSK_LENGTH
+ * @brief Identity max length
+ */
+#define UUID_LENGTH (128/8)
+/**
+ * @def MASTER_SECRET_LEN
+ * @brief TLS master secret length
+ */
+#define MASTER_SECRET_LEN (48)
+/**
+ * @def RANDOM_LEN
+ * @brief TLS client and server random bytes length
+ */
+#define RANDOM_LEN (32)
+/**
+ * @def RANDOM_LEN
+ * @brief PSK generated keyblock length
+ */
+#define KEY_BLOCK_LEN (96)
+
+/**@def SSL_CLOSE_NOTIFY(peer, ret)
+ *
+ * Notifies of existing \a peer about closing TLS connection.
+ *
+ * @param[in] peer remote peer
+ * @param[in] ret used internaly
+ */
+#define SSL_CLOSE_NOTIFY(peer, ret)                                                                \
+do                                                                                                 \
+{                                                                                                  \
+    (ret) = mbedtls_ssl_close_notify(&(peer)->ssl);                                                \
+} while (MBEDTLS_ERR_SSL_WANT_WRITE == (ret))
+
+/**@def SSL_RES(peer, status)
+ *
+ * Sets SSL result for callback.
+ *
+ * @param[in] peer remote peer
+ */
+#define SSL_RES(peer, status)                                                                      \
+if (g_sslCallback)                                                                                 \
+{                                                                                                  \
+    CAErrorInfo_t errorInfo;                                                                       \
+    errorInfo.result = (status);                                                                   \
+    g_sslCallback(&(peer)->sep.endpoint, &errorInfo);                                              \
+}
+/**@def SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)
+ *
+ * Checks handshake result and send alert if needed.
+ *
+ * @param[in] peer remote peer
+ * @param[in] ret error code
+ * @param[in] str debug string
+ * @param[in] mutex ca mutex
+ * @param[in] return error code
+ * @param[in] msg allert message
+ */
+#define SSL_CHECK_FAIL(peer, ret, str, mutex, error, msg)                                          \
+if (0 != (ret) && MBEDTLS_ERR_SSL_WANT_READ != (int) (ret) &&                                      \
+    MBEDTLS_ERR_SSL_WANT_WRITE != (int) (ret) &&                                                   \
+    MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED != (int) (ret) &&                                        \
+    MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY != (int) (ret))                                              \
+{                                                                                                  \
+    OIC_LOG_V(ERROR, NET_SSL_TAG, "%s: -0x%x", (str), -(ret));                                     \
+    if ((int) MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE != (int) (ret) &&                                \
+       (int) MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO != (int) (ret))                                   \
+    {                                                                                              \
+        mbedtls_ssl_send_alert_message(&(peer)->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, (msg));        \
+    }                                                                                              \
+    SSL_RES((peer), CA_STATUS_FAILED);                                                             \
+    RemovePeerFromList(&(peer)->sep.endpoint);                                                     \
+    if (mutex)                                                                                     \
+    {                                                                                              \
+        oc_mutex_unlock(g_sslContextMutex);                                                        \
+    }                                                                                              \
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);                                             \
+    return (error);                                                                                \
+}
+/** @def CHECK_MBEDTLS_RET(f, ...)
+ * A macro that checks \a f function return code
+ *
+ * If function returns error code it goes to error processing.
+ *
+ * @param[in] f  Function to call
+ */
+#define CHECK_MBEDTLS_RET(f, ...) do {                                                             \
+int ret = (f)(__VA_ARGS__);                                                                        \
+if (0 != ret) {                                                                                    \
+    OIC_LOG_V(ERROR, NET_SSL_TAG, "%s returned -0x%04x\n", __func__, -(ret));                      \
+    goto exit;                                                                                     \
+} } while(0)
+
+typedef enum
+{
+    ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA,
+    ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
+    ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256,
+    ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
+    ADAPTER_CIPHER_MAX
+} AdapterCipher_t;
+
+typedef enum
+{
+    ADAPTER_CURVE_SECP256R1,
+    ADAPTER_CURVE_MAX
+} AdapterCurve_t;
+
+int tlsCipher[ADAPTER_CIPHER_MAX][2] =
+{
+    {MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA, 0},
+    {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, 0},
+    {MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256, 0},
+    {MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, 0}
+};
+
+static int g_cipherSuitesList[ADAPTER_CIPHER_MAX];
+
+mbedtls_ecp_group_id curve[ADAPTER_CURVE_MAX][2] =
+{
+    {MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_NONE}
+};
+
+static PkiInfo_t g_pkiInfo = {{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}};
+
+typedef struct  {
+    int code;
+    int alert;
+} CrtVerifyAlert_t;
+
+static const CrtVerifyAlert_t crtVerifyAlerts[] = {
+    {MBEDTLS_X509_BADCERT_EXPIRED,       MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED},
+    {MBEDTLS_X509_BADCERT_REVOKED,       MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED},
+    {MBEDTLS_X509_BADCERT_CN_MISMATCH,   MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN},
+    {MBEDTLS_X509_BADCERT_NOT_TRUSTED,   MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
+    {MBEDTLS_X509_BADCRL_NOT_TRUSTED,    MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA},
+    {MBEDTLS_X509_BADCRL_EXPIRED,        MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
+    {MBEDTLS_X509_BADCERT_MISSING,       MBEDTLS_SSL_ALERT_MSG_NO_CERT},
+    {MBEDTLS_X509_BADCERT_SKIP_VERIFY,   MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
+    {MBEDTLS_X509_BADCERT_OTHER,         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR},
+    {MBEDTLS_X509_BADCERT_FUTURE,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_FUTURE,         MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY},
+    {MBEDTLS_X509_BADCERT_KEY_USAGE,     MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_NS_CERT_TYPE,  MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_BAD_MD,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_BAD_PK,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCERT_BAD_KEY,       MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_BAD_MD,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_BAD_PK,         MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {MBEDTLS_X509_BADCRL_BAD_KEY,        MBEDTLS_SSL_ALERT_MSG_BAD_CERT},
+    {0, 0}
+};
+
+static int GetAlertCode(uint32_t flags)
+{
+    const CrtVerifyAlert_t *cur;
+
+    for (cur = crtVerifyAlerts; cur->alert != 0 ; cur++)
+    {
+        if (flags & cur->code)
+        {
+            return cur->alert;
+        }
+    }
+    return 0;
+}
+
+#ifndef NDEBUG
+/**
+ * Pass a message to the OIC logger.
+ *
+ * @param[in] ctx  opaque context for the callback
+ * @param[in] level  debug level
+ * @param[in] file  file name
+ * @param[in] line  line number
+ * @param[in] str  message
+ */
+static void DebugSsl(void *ctx, int level, const char *file, int line, const char *str)
+{
+    ((void) level);
+    ((void) file);
+    ((void) line);
+    ((void) ctx);
+
+    OIC_LOG_V(DEBUG, MBED_TLS_TAG, "%s", str);
+}
+#endif
+
+#if defined(_WIN32)
+/*
+ * Finds the first occurrence of the byte string s in byte string l.
+ */
+
+static void * memmem(const void *l, size_t lLen, const void *s, size_t sLen)
+{
+    char *cur;
+    char *last;
+    const char *cl = (const char *)l;
+    const char *cs = (const char *)s;
+
+    if (lLen == 0 || sLen == 0)
+    {
+        return NULL;
+    }
+    if (lLen < sLen)
+    {
+        return NULL;
+    }
+    if (sLen == 1)
+    {
+        return memchr(l, (int)*cs, lLen);
+    }
+
+    last = (char *)cl + lLen - sLen;
+
+    for (cur = (char *)cl; cur <= last; cur++)
+    {
+        if (cur[0] == cs[0] && memcmp(cur, cs, sLen) == 0)
+        {
+            return cur;
+        }
+    }
+    return NULL;
+}
+#endif
+/**
+ * structure to holds the information of cache message and address info.
+ */
+typedef ByteArray_t SslCacheMessage_t;
+
+
+/**
+ * Data structure for holding the send and recv callbacks.
+ */
+typedef struct TlsCallBacks
+{
+    CAPacketReceivedCallback recvCallback;  /**< Callback used to send data to upper layer. */
+    CAPacketSendCallback sendCallback;      /**< Callback used to send data to socket layer. */
+} SslCallbacks_t;
+
+/**
+ * Data structure for holding the mbedTLS interface related info.
+ */
+typedef struct SslContext
+{
+    u_arraylist_t *peerList;         /**< peer list which holds the mapping between
+                                              peer id, it's n/w address and mbedTLS context. */
+    mbedtls_entropy_context entropy;
+    mbedtls_ctr_drbg_context rnd;
+    mbedtls_x509_crt ca;
+    mbedtls_x509_crt crt;
+    mbedtls_pk_context pkey;
+
+    mbedtls_ssl_config clientTlsConf;
+    mbedtls_ssl_config serverTlsConf;
+    mbedtls_ssl_config clientDtlsConf;
+    mbedtls_ssl_config serverDtlsConf;
+#ifdef __WITH_DTLS__
+    mbedtls_ssl_cookie_ctx cookie_ctx;
+    mbedtls_timing_delay_context timer;
+#endif // __WITH_DTLS__
+    AdapterCipher_t cipher;
+    SslCallbacks_t adapterCallbacks[MAX_SUPPORTED_ADAPTERS];
+    mbedtls_x509_crl crl;
+    bool cipherFlag[2];
+    int selectedCipher;
+
+} SslContext_t;
+
+/**
+ * @var g_caSslContext
+ * @brief global context which holds tls context and cache list information.
+ */
+static SslContext_t * g_caSslContext = NULL;
+
+/**
+ * @var g_getCredentialsCallback
+ * @brief callback to get TLS credentials (same as for DTLS)
+ */
+static CAgetPskCredentialsHandler g_getCredentialsCallback = NULL;
+/**
+ * @var g_getCerdentilTypesCallback
+ * @brief callback to get different credential types from SRM
+ */
+static CAgetCredentialTypesHandler g_getCredentialTypesCallback = NULL;
+/**
+ * @var g_getPkixInfoCallback
+ *
+ * @brief callback to get X.509-based Public Key Infrastructure
+ */
+static CAgetPkixInfoHandler g_getPkixInfoCallback = NULL;
+
+/**
+ * @var g_dtlsContextMutex
+ * @brief Mutex to synchronize access to g_caSslContext.
+ */
+static oc_mutex g_sslContextMutex = NULL;
+
+/**
+ * @var g_sslCallback
+ * @brief callback to deliver the TLS handshake result
+ */
+static CAErrorCallback g_sslCallback = NULL;
+
+/**
+ * Data structure for holding the data to be received.
+ */
+typedef struct SslRecBuf
+{
+    uint8_t * buff;
+    size_t len;
+    size_t loaded;
+} SslRecBuf_t;
+/**
+ * Data structure for holding the data related to endpoint
+ * and TLS session.
+ */
+typedef struct SslEndPoint
+{
+    mbedtls_ssl_context ssl;
+    CASecureEndpoint_t sep;
+    u_arraylist_t * cacheList;
+    SslRecBuf_t recBuf;
+    uint8_t master[MASTER_SECRET_LEN];
+    uint8_t random[2*RANDOM_LEN];
+#ifdef __WITH_DTLS__
+    mbedtls_ssl_cookie_ctx cookieCtx;
+#endif
+
+} SslEndPoint_t;
+
+void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback)
+{
+    // TODO Does this method needs protection of tlsContextMutex?
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    g_getCredentialsCallback = credCallback;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+
+void CAsetPkixInfoCallback(CAgetPkixInfoHandler infoCallback)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    g_getPkixInfoCallback = infoCallback;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credTypesCallback)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    g_getCredentialTypesCallback = credTypesCallback;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+
+static int GetAdapterIndex(CATransportAdapter_t adapter)
+{
+    switch (adapter)
+    {
+        case CA_ADAPTER_IP:
+            return 0;
+        case CA_ADAPTER_TCP:
+            return 1;
+        default:
+            OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
+            return -1;
+    }
+}
+/**
+ * Write callback.
+ *
+ * @param[in]  tep    TLS endpoint
+ * @param[in]  data    message
+ * @param[in]  dataLen    message length
+ *
+ * @return  message length
+ */
+static int SendCallBack(void * tep, const unsigned char * data, size_t dataLen)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "secure endpoint is NULL", 0);
+    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data len: %zu", dataLen);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Adapter: %u", ((SslEndPoint_t * )tep)->sep.endpoint.adapter);
+    int adapterIndex = GetAdapterIndex(((SslEndPoint_t * )tep)->sep.endpoint.adapter);
+    if (0 == adapterIndex || 1 == adapterIndex)
+    {
+        CAPacketSendCallback sendCallback = g_caSslContext->adapterCallbacks[adapterIndex].sendCallback;
+        sendCallback(&(((SslEndPoint_t * )tep)->sep.endpoint), (const void *) data, (uint32_t) dataLen);
+    }
+    else
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Unsupported adapter");
+        dataLen = 0;
+    }
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return dataLen;
+}
+/**
+ * Read callback.
+ *
+ * @param[in]  tep    TLS endpoint
+ * @param[in]  data    message
+ * @param[in]  dataLen    message length
+ *
+ * @return  read length
+ */
+static int RecvCallBack(void * tep, unsigned char * data, size_t dataLen)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(tep, NET_SSL_TAG, "endpoint is NULL", 0);
+    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "data is NULL", 0);
+
+    SslRecBuf_t *recBuf = &((SslEndPoint_t *)tep)->recBuf;
+    size_t retLen = (recBuf->len > recBuf->loaded ? recBuf->len - recBuf->loaded : 0);
+    retLen = (retLen < dataLen ? retLen : dataLen);
+
+    memcpy(data, recBuf->buff + recBuf->loaded, retLen);
+    recBuf->loaded += retLen;
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return (int)retLen;
+}
+
+/**
+ * Parse chain of X.509 certificates.
+ *
+ * @param[out] crt     container for X.509 certificates
+ * @param[in]  data    buffer with X.509 certificates. Certificates may be in either in PEM
+                       or DER format in a jumble. Each PEM certificate must be NULL-terminated.
+ * @param[in]  bufLen  buffer length
+ *
+ * @return  0 on success, -1 on error
+ */
+static int ParseChain(mbedtls_x509_crt * crt, const unsigned char * buf, int bufLen)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(crt, NET_SSL_TAG, "Param crt is NULL" , -1);
+    VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "Param buf is NULL" , -1);
+
+    int pos = 0;
+    int ret = 0;
+    size_t len = 0;
+    unsigned char * tmp = NULL;
+
+    char pemCertHeader[] = {
+        0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x42, 0x45, 0x47, 0x49, 0x4e, 0x20, 0x43, 0x45, 0x52,
+        0x54, 0x49, 0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
+    };
+    char pemCertFooter[] = {
+        0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x45, 0x4e, 0x44, 0x20, 0x43, 0x45, 0x52, 0x54, 0x49,
+        0x46, 0x49, 0x43, 0x41, 0x54, 0x45, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d
+    };
+    size_t pemCertHeaderLen = sizeof(pemCertHeader);
+    size_t pemCertFooterLen = sizeof(pemCertFooter);
+
+    while (pos < bufLen)
+    {
+        if (buf[pos] == 0x30 && buf[pos + 1] == 0x82)
+        {
+            tmp = (unsigned char *)buf + pos + 1;
+            CHECK_MBEDTLS_RET(mbedtls_asn1_get_len, &tmp, buf + bufLen, &len);
+            if (pos + len < bufLen)
+            {
+                CHECK_MBEDTLS_RET(mbedtls_x509_crt_parse_der, crt, buf + pos, len + 4);
+            }
+            pos += len + 4;
+        }
+        else if (0 == memcmp(buf + pos, pemCertHeader, pemCertHeaderLen))
+        {
+            void * endPos = NULL;
+            endPos = memmem(&(buf[pos]), bufLen - pos, pemCertFooter, pemCertFooterLen);
+            if (NULL == endPos)
+            {
+                OIC_LOG(ERROR, NET_SSL_TAG, "Error: end of PEM certificate not found.");
+                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+                return -1;
+            }
+            if ((*((char*)endPos + pemCertFooterLen + 0) == 0x0d) &&
+                (*((char*)endPos + pemCertFooterLen + 1) == 0x0a) &&
+                (*((char*)endPos + pemCertFooterLen + 2) == 0x00))
+            {
+                len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen + 3;
+            }
+            else if ((*((char*)endPos + pemCertFooterLen + 0) == 0x0a) &&
+                     (*((char*)endPos + pemCertFooterLen + 1) == 0x00))
+            {
+                len = (char*)endPos - ((char*)buf + pos) + pemCertFooterLen + 2;
+            }
+            else
+            {
+                OIC_LOG_V(ERROR, NET_SSL_TAG, "Incorrect PEM certificate ending");
+                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+                return -1;
+            }
+            CHECK_MBEDTLS_RET(mbedtls_x509_crt_parse, crt, buf + pos, len);
+            pos += len;
+        }
+        else
+        {
+             OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, buf, bufLen);
+             OIC_LOG_V(ERROR, NET_SSL_TAG, "parseChain returned -0x%x", -ret);
+             OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+             return -1;
+        }
+    }
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return 0;
+
+exit:
+    return -1;
+}
+
+//Loads PKIX related information from SRM
+static int InitPKIX(CATransportAdapter_t adapter)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(g_getPkixInfoCallback, NET_SSL_TAG, "PKIX info callback is NULL", -1);
+    g_getPkixInfoCallback(&g_pkiInfo);
+
+    mbedtls_x509_crt_free(&g_caSslContext->ca);
+    mbedtls_x509_crt_free(&g_caSslContext->crt);
+    mbedtls_pk_free(&g_caSslContext->pkey);
+    mbedtls_x509_crl_free(&g_caSslContext->crl);
+
+    mbedtls_x509_crt_init(&g_caSslContext->ca);
+    mbedtls_x509_crt_init(&g_caSslContext->crt);
+    mbedtls_pk_init(&g_caSslContext->pkey);
+    mbedtls_x509_crl_init(&g_caSslContext->crl);
+
+    mbedtls_ssl_config * serverConf = (adapter == CA_ADAPTER_IP ?
+                                   &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
+    mbedtls_ssl_config * clientConf = (adapter == CA_ADAPTER_IP ?
+                                   &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
+    // optional
+    int ret = ParseChain(&g_caSslContext->crt, g_pkiInfo.crt.data, g_pkiInfo.crt.len);
+    if (0 != ret)
+    {
+        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate chain parsing error");
+        goto required;
+    }
+    ret =  mbedtls_pk_parse_key(&g_caSslContext->pkey, g_pkiInfo.key.data, g_pkiInfo.key.len,
+                                                                               NULL, 0);
+    if (0 != ret)
+    {
+        OIC_LOG(WARNING, NET_SSL_TAG, "Key parsing error");
+        goto required;
+    }
+
+    ret = mbedtls_ssl_conf_own_cert(serverConf, &g_caSslContext->crt, &g_caSslContext->pkey);
+    if (0 != ret)
+    {
+        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate parsing error");
+        goto required;
+    }
+    ret = mbedtls_ssl_conf_own_cert(clientConf, &g_caSslContext->crt, &g_caSslContext->pkey);
+    if(0 != ret)
+    {
+        OIC_LOG(WARNING, NET_SSL_TAG, "Own certificate configuration error");
+        goto required;
+    }
+
+    required:
+    ret = ParseChain(&g_caSslContext->ca, g_pkiInfo.ca.data, g_pkiInfo.ca.len);
+    if(0 != ret)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "CA chain parsing error");
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return -1;
+    }
+
+    ret = mbedtls_x509_crl_parse_der(&g_caSslContext->crl, g_pkiInfo.crl.data, g_pkiInfo.crl.len);
+    if(0 != ret)
+    {
+        OIC_LOG(WARNING, NET_SSL_TAG, "CRL parsing error");
+        mbedtls_ssl_conf_ca_chain(clientConf, &g_caSslContext->ca, NULL);
+        mbedtls_ssl_conf_ca_chain(serverConf, &g_caSslContext->ca, NULL);
+    }
+    else
+    {
+        mbedtls_ssl_conf_ca_chain(clientConf, &g_caSslContext->ca, &g_caSslContext->crl);
+        mbedtls_ssl_conf_ca_chain(serverConf, &g_caSslContext->ca, &g_caSslContext->crl);
+    }
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return 0;
+}
+
+/*
+ * PSK callback.
+ *
+ * @param[in]  notUsed     opaque context
+ * @param[in]  ssl    mbedTLS context
+ * @param[in]  desc    identity
+ * @param[in]  descLen    identity length
+ *
+ * @return  0 on success any other return value will result in a denied PSK identity
+ */
+static int GetPskCredentialsCallback(void * notUsed, mbedtls_ssl_context * ssl,
+                                     const unsigned char * desc, size_t descLen)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_SSL_TAG, "Credential callback s NULL", -1);
+    VERIFY_NON_NULL_RET(ssl, NET_SSL_TAG, "ssl pointer is NULL", -1);
+    VERIFY_NON_NULL_RET(desc, NET_SSL_TAG, "desc pointer is NULL", -1);
+    if (descLen > CA_MAX_ENDPOINT_IDENTITY_LEN)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "desc too long!");
+        return -1;
+    }
+    (void) notUsed;
+    uint8_t keyBuf[PSK_LENGTH] = {0};
+
+    // Retrieve the credentials blob from security module
+    int ret = g_getCredentialsCallback(CA_DTLS_PSK_KEY, desc, descLen, keyBuf, PSK_LENGTH);
+    if (ret > 0)
+    {
+        memcpy(((SslEndPoint_t *) ssl)->sep.identity.id, desc, descLen);
+        ((SslEndPoint_t *) ssl)->sep.identity.id_length = descLen;
+        OIC_LOG(DEBUG, NET_SSL_TAG, "PSK:");
+        OIC_LOG_BUFFER(DEBUG, NET_SSL_TAG, keyBuf, ret);
+
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return(mbedtls_ssl_set_hs_psk(ssl, keyBuf, ret));
+    }
+    OIC_LOG_V(WARNING, NET_SSL_TAG, "Out %s", __func__);
+    return -1;
+}
+/**
+ * Gets session corresponding for endpoint.
+ *
+ * @param[in]  peer    remote address
+ *
+ * @return  TLS session or NULL
+ */
+static SslEndPoint_t *GetSslPeer(const CAEndpoint_t *peer)
+{
+    uint32_t listIndex = 0;
+    uint32_t listLength = 0;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(peer, NET_SSL_TAG, "TLS peer is NULL", NULL);
+
+    SslEndPoint_t *tep = NULL;
+    listLength = u_arraylist_length(g_caSslContext->peerList);
+    for (listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        tep = (SslEndPoint_t *) u_arraylist_get(g_caSslContext->peerList, listIndex);
+        if (NULL == tep)
+        {
+            continue;
+        }
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Compare [%s:%d] and [%s:%d]",
+                  peer->addr, peer->port, tep->sep.endpoint.addr, tep->sep.endpoint.port);
+        if((0 == strncmp(peer->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA))
+                && (peer->port == tep->sep.endpoint.port))
+        {
+            OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+            return tep;
+        }
+    }
+    OIC_LOG(DEBUG, NET_SSL_TAG, "Return NULL");
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return NULL;
+}
+/**
+ * Deletes cached message.
+ *
+ * @param[in]  msg    message
+ */
+static void DeleteCacheMessage(SslCacheMessage_t * msg)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_VOID(msg, NET_SSL_TAG, "msg");
+
+    OICFree(msg->data);
+    OICFree(msg);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+/**
+ * Deletes cached message list.
+ *
+ * @param[in] cacheList  list of cached messages
+ */
+static void DeleteCacheList(u_arraylist_t * cacheList)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_VOID(cacheList, NET_SSL_TAG, "cacheList");
+    uint32_t listIndex = 0;
+    uint32_t listLength = 0;
+
+    listLength = u_arraylist_length(cacheList);
+    for (listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(cacheList, listIndex);
+        if (NULL != msg)
+        {
+            DeleteCacheMessage(msg);
+        }
+    }
+    u_arraylist_free(&cacheList);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+/**
+ * Deletes endpoint with session.
+ *
+ * @param[in]  tep    endpoint with session info
+ */
+static void DeleteSslEndPoint(SslEndPoint_t * tep)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "tep");
+
+    mbedtls_ssl_free(&tep->ssl);
+#ifdef __WITH_DTLS__
+    mbedtls_ssl_cookie_free(&tep->cookieCtx);
+#endif
+    DeleteCacheList(tep->cacheList);
+    OICFree(tep);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+/**
+ * Removes endpoint session from list.
+ *
+ * @param[in]  endpoint    remote address
+ */
+static void RemovePeerFromList(CAEndpoint_t * endpoint)
+{
+    uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
+    VERIFY_NON_NULL_VOID(endpoint, NET_SSL_TAG, "endpoint");
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
+        if (NULL == tep)
+        {
+            continue;
+        }
+        if(0 == strncmp(endpoint->addr, tep->sep.endpoint.addr, MAX_ADDR_STR_SIZE_CA)
+                && (endpoint->port == tep->sep.endpoint.port))
+        {
+            u_arraylist_remove(g_caSslContext->peerList, listIndex);
+            DeleteSslEndPoint(tep);
+            return;
+        }
+    }
+}
+/**
+ * Deletes session list.
+ */
+static void DeletePeerList()
+{
+    uint32_t listLength = u_arraylist_length(g_caSslContext->peerList);
+    for (uint32_t listIndex = 0; listIndex < listLength; listIndex++)
+    {
+        SslEndPoint_t * tep = (SslEndPoint_t *)u_arraylist_get(g_caSslContext->peerList,listIndex);
+        if (NULL == tep)
+        {
+            continue;
+        }
+        DeleteSslEndPoint(tep);
+    }
+    u_arraylist_free(&g_caSslContext->peerList);
+}
+
+CAResult_t CAcloseSslConnection(const CAEndpoint_t *endpoint)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
+
+    oc_mutex_lock(g_sslContextMutex);
+    if (NULL == g_caSslContext)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+    SslEndPoint_t * tep = GetSslPeer(endpoint);
+    if (NULL == tep)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+    /* No error checking, the connection might be closed already */
+    int ret = 0;
+    do
+    {
+        ret = mbedtls_ssl_close_notify(&tep->ssl);
+    }
+    while (MBEDTLS_ERR_SSL_WANT_WRITE == ret);
+
+    RemovePeerFromList(&tep->sep.endpoint);
+    oc_mutex_unlock(g_sslContextMutex);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
+/**
+ * Creates session for endpoint.
+ *
+ * @param[in]  endpoint    remote address
+ * @param[in]  config    mbedTLS configuration info
+ *
+ * @return  TLS endpoint or NULL
+ */
+static SslEndPoint_t * NewSslEndPoint(const CAEndpoint_t * endpoint, mbedtls_ssl_config * config)
+{
+    SslEndPoint_t * tep = NULL;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint", NULL);
+    VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "config", NULL);
+
+    tep = (SslEndPoint_t *) OICCalloc(1, sizeof (SslEndPoint_t));
+    if (NULL == tep)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
+        return NULL;
+    }
+
+    tep->sep.endpoint = *endpoint;
+    tep->sep.endpoint.flags = (CATransportFlags_t)(tep->sep.endpoint.flags | CA_SECURE);
+
+    if(0 != mbedtls_ssl_setup(&tep->ssl, config))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Setup failed");
+        OICFree(tep);
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return NULL;
+    }
+
+    mbedtls_ssl_set_bio(&tep->ssl, tep, SendCallBack, RecvCallBack, NULL);
+    if (MBEDTLS_SSL_TRANSPORT_DATAGRAM == config->transport)
+    {
+        mbedtls_ssl_set_timer_cb(&tep->ssl, &g_caSslContext->timer,
+                                  mbedtls_timing_set_delay, mbedtls_timing_get_delay);
+        if (MBEDTLS_SSL_IS_SERVER == config->endpoint)
+        {
+            if (0 != mbedtls_ssl_cookie_setup(&tep->cookieCtx, mbedtls_ctr_drbg_random,
+                                              &g_caSslContext->rnd))
+            {
+                OIC_LOG(ERROR, NET_SSL_TAG, "Cookie setup failed!");
+                OICFree(tep);
+                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+                return NULL;
+            }
+            mbedtls_ssl_conf_dtls_cookies(config, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check,
+                                          &tep->cookieCtx);
+            if (0 != mbedtls_ssl_set_client_transport_id(&tep->ssl,
+                                    (const unsigned char *) endpoint->addr, sizeof(endpoint->addr)))
+            {
+                OIC_LOG(ERROR, NET_SSL_TAG, "Transport id setup failed!");
+                OICFree(tep);
+                OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+                return NULL;
+            }
+        }
+    }
+    tep->cacheList = u_arraylist_create();
+    if (NULL == tep->cacheList)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "cacheList initialization failed!");
+        mbedtls_ssl_free(&tep->ssl);
+        OICFree(tep);
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return NULL;
+    }
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return tep;
+}
+/**
+ * Initializes PSK identity.
+ *
+ * @param[out]  config    client/server config to be updated
+ *
+ * @return  0 on success or -1 on error
+ */
+static int InitPskIdentity(mbedtls_ssl_config * config)
+{
+    uint8_t idBuf[UUID_LENGTH] = {0};
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(config, NET_SSL_TAG, "Param config is NULL" , -1);
+
+    if (0 > g_getCredentialsCallback(CA_DTLS_PSK_IDENTITY, NULL, 0, idBuf, UUID_LENGTH))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Identity not found");
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return -1;
+    }
+    if (0 != mbedtls_ssl_conf_psk(config, idBuf, 0, idBuf, UUID_LENGTH))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Identity initialization failed!");
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return -1;
+    }
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return 0;
+}
+static void SetupCipher(mbedtls_ssl_config * config, CATransportAdapter_t adapter)
+{
+    int index = 0;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    if (NULL == g_getCredentialTypesCallback)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Param callback is null");
+        return;
+    }
+
+    g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
+    // Retrieve the PSK credential from SRM
+    // PIN OTM if (true == g_caSslContext->cipherFlag[0] && 0 != InitPskIdentity(config))
+    if (0 != InitPskIdentity(config))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "PSK identity initialization failed!");
+    }
+
+    // Retrieve the ECC credential from SRM
+    if (true == g_caSslContext->cipherFlag[1] || ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA == g_caSslContext->cipher)
+    {
+        int ret = InitPKIX(adapter);
+        if (0 != ret)
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "Failed to init X.509");
+        }
+    }
+
+    memset(g_cipherSuitesList, 0, sizeof(g_cipherSuitesList));
+    if (ADAPTER_CIPHER_MAX != g_caSslContext->cipher)
+    {
+        g_cipherSuitesList[index] = tlsCipher[g_caSslContext->cipher][0];
+        index ++;
+    }
+    if (true == g_caSslContext->cipherFlag[1])
+    {
+        g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
+        index ++;
+    }
+    if (true == g_caSslContext->cipherFlag[0])
+    {
+       g_cipherSuitesList[index] = MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
+    }
+
+    mbedtls_ssl_conf_ciphersuites(config, g_cipherSuitesList);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+/**
+ * Initiate TLS handshake with endpoint.
+ *
+ * @param[in]  endpoint    remote address
+ *
+ * @return  TLS endpoint or NULL
+ */
+static SslEndPoint_t * InitiateTlsHandshake(const CAEndpoint_t *endpoint)
+{
+    int ret = 0;
+    SslEndPoint_t * tep = NULL;
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , NULL);
+
+
+    mbedtls_ssl_config * config = (endpoint->adapter == CA_ADAPTER_IP ?
+                                   &g_caSslContext->clientDtlsConf : &g_caSslContext->clientTlsConf);
+    tep = NewSslEndPoint(endpoint, config);
+    if (NULL == tep)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
+        return NULL;
+    }
+
+    //Load allowed SVR suites from SVR DB
+    SetupCipher(config, endpoint->adapter);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Add %s:%d", tep->sep.endpoint.addr, tep->sep.endpoint.port);
+    ret = u_arraylist_add(g_caSslContext->peerList, (void *) tep);
+    if (!ret)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
+        DeleteSslEndPoint(tep);
+        return NULL;
+    }
+
+    while (MBEDTLS_SSL_HANDSHAKE_OVER > tep->ssl.state)
+    {
+        ret = mbedtls_ssl_handshake_step(&tep->ssl);
+        if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
+        {
+            break;
+        }
+        SSL_CHECK_FAIL(tep, ret, "Handshake error", 0, NULL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
+    }
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return tep;
+}
+
+void CAdeinitSslAdapter()
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+
+    VERIFY_NON_NULL_VOID(g_caSslContext, NET_SSL_TAG, "context is NULL");
+    VERIFY_NON_NULL_VOID(g_sslContextMutex, NET_SSL_TAG, "context mutex is NULL");
+
+    //Lock tlsContext mutex
+    oc_mutex_lock(g_sslContextMutex);
+
+    // Clear all lists
+    DeletePeerList();
+
+    // De-initialize mbedTLS
+    mbedtls_x509_crt_free(&g_caSslContext->crt);
+    mbedtls_pk_free(&g_caSslContext->pkey);
+#ifdef __WITH_TLS__
+    mbedtls_ssl_config_free(&g_caSslContext->clientTlsConf);
+    mbedtls_ssl_config_free(&g_caSslContext->serverTlsConf);
+#endif // __WITH_TLS__
+#ifdef __WITH_DTLS__
+    mbedtls_ssl_config_free(&g_caSslContext->clientDtlsConf);
+    mbedtls_ssl_config_free(&g_caSslContext->serverDtlsConf);
+#endif // __WITH_DTLS__
+    mbedtls_ctr_drbg_free(&g_caSslContext->rnd);
+    mbedtls_entropy_free(&g_caSslContext->entropy);
+
+    // De-initialize tls Context
+    OICFree(g_caSslContext);
+    g_caSslContext = NULL;
+
+    // Unlock tlsContext mutex and de-initialize it
+    oc_mutex_unlock(g_sslContextMutex);
+    oc_mutex_free(g_sslContextMutex);
+    g_sslContextMutex = NULL;
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s ", __func__);
+}
+
+static int InitConfig(mbedtls_ssl_config * conf, int transport, int mode)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(conf, NET_SSL_TAG, "Param conf is NULL" , -1);
+    mbedtls_ssl_config_init(conf);
+    if (mbedtls_ssl_config_defaults(conf, mode, transport, MBEDTLS_SSL_PRESET_DEFAULT) != 0)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Config initialization failed!");
+        return -1;
+    }
+
+    mbedtls_ssl_conf_psk_cb(conf, GetPskCredentialsCallback, NULL);
+    mbedtls_ssl_conf_rng(conf, mbedtls_ctr_drbg_random, &g_caSslContext->rnd);
+    mbedtls_ssl_conf_curves(conf, curve[ADAPTER_CURVE_SECP256R1]);
+    mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
+    mbedtls_ssl_conf_renegotiation(conf, MBEDTLS_SSL_RENEGOTIATION_DISABLED);
+    mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+
+#ifndef NDEBUG
+    mbedtls_ssl_conf_dbg(conf, DebugSsl, NULL);
+    mbedtls_debug_set_threshold(MBED_TLS_DEBUG_LEVEL);
+#endif
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return 0;
+}
+
+CAResult_t CAinitSslAdapter()
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    // Initialize mutex for tlsContext
+    if (NULL == g_sslContextMutex)
+    {
+        g_sslContextMutex = oc_mutex_new();
+        VERIFY_NON_NULL_RET(g_sslContextMutex, NET_SSL_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
+    }
+    else
+    {
+        OIC_LOG(INFO, NET_SSL_TAG, "Done already!");
+        return CA_STATUS_OK;
+    }
+
+    // Lock tlsContext mutex and create tlsContext
+    oc_mutex_lock(g_sslContextMutex);
+    g_caSslContext = (SslContext_t *)OICCalloc(1, sizeof(SslContext_t));
+
+    if (NULL == g_caSslContext)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Context malloc failed");
+        oc_mutex_unlock(g_sslContextMutex);
+        oc_mutex_free(g_sslContextMutex);
+        g_sslContextMutex = NULL;
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    // Create peer list
+    g_caSslContext->peerList = u_arraylist_create();
+
+    if(NULL == g_caSslContext->peerList)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "peerList initialization failed!");
+        OICFree(g_caSslContext);
+        g_caSslContext = NULL;
+        oc_mutex_unlock(g_sslContextMutex);
+        oc_mutex_free(g_sslContextMutex);
+        g_sslContextMutex = NULL;
+        return CA_STATUS_FAILED;
+    }
+
+    /* Initialize TLS library
+     */
+#ifndef NDEBUG
+    char version[MBED_TLS_VERSION_LEN];
+    mbedtls_version_get_string(version);
+    OIC_LOG_V(INFO, NET_SSL_TAG, "mbed TLS version: %s", version);
+#endif
+
+    /* Entropy settings
+     */
+    mbedtls_entropy_init(&g_caSslContext->entropy);
+    mbedtls_ctr_drbg_init(&g_caSslContext->rnd);
+
+#ifdef __unix__
+    unsigned char seed[sizeof(SEED)] = {0};
+    int urandomFd = -2;
+    urandomFd = open("/dev/urandom", O_RDONLY);
+    if(urandomFd == -1)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Fails open /dev/urandom!");
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        return CA_STATUS_FAILED;
+    }
+    if(0 > read(urandomFd, seed, sizeof(seed)))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Fails read from /dev/urandom!");
+        close(urandomFd);
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        return CA_STATUS_FAILED;
+    }
+    close(urandomFd);
+
+#else
+    unsigned char * seed = (unsigned char*) SEED;
+#endif
+    if(0 != mbedtls_ctr_drbg_seed(&g_caSslContext->rnd, mbedtls_entropy_func,
+                                  &g_caSslContext->entropy, seed, sizeof(SEED)))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Seed initialization failed!");
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        return CA_STATUS_FAILED;
+    }
+    mbedtls_ctr_drbg_set_prediction_resistance(&g_caSslContext->rnd, MBEDTLS_CTR_DRBG_PR_OFF);
+
+#ifdef __WITH_TLS__
+    if (0 != InitConfig(&g_caSslContext->clientTlsConf,
+                        MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_CLIENT))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return CA_STATUS_FAILED;
+    }
+
+    if (0 != InitConfig(&g_caSslContext->serverTlsConf,
+                        MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_IS_SERVER))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return CA_STATUS_FAILED;
+    }
+#endif // __WITH_TLS__
+#ifdef __WITH_DTLS__
+    if (0 != InitConfig(&g_caSslContext->clientDtlsConf,
+                        MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_CLIENT))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Client config initialization failed!");
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return CA_STATUS_FAILED;
+    }
+
+    if (0 != InitConfig(&g_caSslContext->serverDtlsConf,
+                        MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_IS_SERVER))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Server config initialization failed!");
+        oc_mutex_unlock(g_sslContextMutex);
+        CAdeinitSslAdapter();
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return CA_STATUS_FAILED;
+    }
+#endif // __WITH_DTLS__
+
+    // set default cipher
+    g_caSslContext->cipher = ADAPTER_CIPHER_MAX;
+
+    // init X.509
+    mbedtls_x509_crt_init(&g_caSslContext->ca);
+    mbedtls_x509_crt_init(&g_caSslContext->crt);
+    mbedtls_pk_init(&g_caSslContext->pkey);
+    mbedtls_x509_crl_init(&g_caSslContext->crl);
+
+    oc_mutex_unlock(g_sslContextMutex);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
+
+SslCacheMessage_t *  NewCacheMessage(uint8_t * data, size_t dataLen)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , NULL);
+    if (0 == dataLen)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "dataLen is equal to zero");
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return NULL;
+    }
+    SslCacheMessage_t * message = (SslCacheMessage_t *) OICCalloc(1, sizeof(SslCacheMessage_t));
+    if (NULL == message)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return NULL;
+    }
+
+    message->data = (uint8_t *)OICCalloc(dataLen, sizeof(uint8_t));
+    if (NULL == message->data)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "calloc failed!");
+        OICFree(message);
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return NULL;
+    }
+    memcpy(message->data, data, dataLen);
+    message->len = dataLen;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return message;
+}
+
+/* Send data via TLS connection.
+ */
+CAResult_t CAencryptSsl(const CAEndpoint_t *endpoint,
+                        void *data, uint32_t dataLen)
+{
+    int ret = 0;
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s ", __func__);
+
+    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG,"Remote address is NULL", CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Data is NULL", CA_STATUS_INVALID_PARAM);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Port %d", endpoint->port);
+
+    if (0 == dataLen)
+    {
+        OIC_LOG_V(ERROR, NET_SSL_TAG, "dataLen is zero [%d]", dataLen);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Data to be encrypted dataLen [%d]", dataLen);
+
+    oc_mutex_lock(g_sslContextMutex);
+    if(NULL == g_caSslContext)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    SslEndPoint_t * tep = GetSslPeer(endpoint);
+    if (NULL == tep)
+    {
+        tep = InitiateTlsHandshake(endpoint);
+    }
+    if (NULL == tep)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    if (MBEDTLS_SSL_HANDSHAKE_OVER == tep->ssl.state)
+    {
+        ret = mbedtls_ssl_write(&tep->ssl, (unsigned char *) data, dataLen);
+
+        if(ret < 0)
+        {
+            OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedTLS write returned %d", ret);
+            RemovePeerFromList(&tep->sep.endpoint);
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+    else
+    {
+        SslCacheMessage_t * msg = NewCacheMessage((uint8_t*) data, dataLen);
+        if (NULL == msg || !u_arraylist_add(tep->cacheList, (void *) msg))
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    oc_mutex_unlock(g_sslContextMutex);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
+/**
+ * Sends cached messages via TLS connection.
+ *
+ * @param[in]  tep    remote address with session info
+ */
+static void SendCacheMessages(SslEndPoint_t * tep)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_VOID(tep, NET_SSL_TAG, "Param tep is NULL");
+
+    uint32_t listIndex = 0;
+    uint32_t listLength = 0;
+    listLength = u_arraylist_length(tep->cacheList);
+    for (listIndex = 0; listIndex < listLength;)
+    {
+        int ret = 0;
+        SslCacheMessage_t * msg = (SslCacheMessage_t *) u_arraylist_get(tep->cacheList, listIndex);
+        if (NULL != msg && NULL != msg->data && 0 != msg->len)
+        {
+            do
+            {
+                ret = mbedtls_ssl_write(&tep->ssl, (unsigned char *) msg->data, msg->len);
+            }
+            while(MBEDTLS_ERR_SSL_WANT_WRITE == ret);
+
+            if(ret < 0)
+            {
+                OIC_LOG_V(ERROR, NET_SSL_TAG,"mbedTLS write returned %d", ret );
+            }
+            if (u_arraylist_remove(tep->cacheList, listIndex))
+            {
+                DeleteCacheMessage(msg);
+                // Reduce list length by 1 as we removed one element.
+                listLength--;
+            }
+            else
+            {
+                OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_remove failed.");
+                break;
+            }
+        }
+        else
+        {
+            // Move to the next element
+            ++listIndex;
+        }
+    }
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+
+void CAsetSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    g_sslCallback = tlsHandshakeCallback;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+// TODO move ConvertStrToUuid function to common module
+/*
+ * Converts string UUID to CARemoteId_t
+ *
+ * @param strUuid Device UUID in string format
+ * @param uuid converted UUID in CARemoteId_t format
+ *
+ * @return 0 for success.
+ * */
+static int ConvertStrToUuid(const char* strUuid, CARemoteId_t* uuid)
+{
+    if(NULL == strUuid || NULL == uuid)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "ConvertStrToUuid : Invalid param");
+        return -1;
+    }
+
+    size_t urnIdx = 0;
+    size_t uuidIdx = 0;
+    size_t strUuidLen = 0;
+    char convertedUuid[UUID_LENGTH * 2] = {0};
+
+    strUuidLen = strlen(strUuid);
+    if(0 == strUuidLen)
+    {
+        OIC_LOG(INFO, NET_SSL_TAG, "The empty string detected, The UUID will be converted to "\
+                           "\"00000000-0000-0000-0000-000000000000\"");
+    }
+    else if(UUID_LENGTH * 2 + 4 == strUuidLen)
+    {
+        for(uuidIdx=0, urnIdx=0; uuidIdx < UUID_LENGTH ; uuidIdx++, urnIdx+=2)
+        {
+            if(*(strUuid + urnIdx) == '-')
+            {
+                urnIdx++;
+            }
+            sscanf(strUuid + urnIdx, "%2hhx", &convertedUuid[uuidIdx]);
+        }
+    }
+    else
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Invalid string uuid format");
+        return -1;
+    }
+
+    memcpy(uuid->id, convertedUuid, UUID_LENGTH);
+    uuid->id_length = UUID_LENGTH;
+    return 0;
+}
+
+/* Read data from TLS connection
+ */
+CAResult_t CAdecryptSsl(const CASecureEndpoint_t *sep, uint8_t *data, uint32_t dataLen)
+{
+    int ret = 0;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(sep, NET_SSL_TAG, "endpoint is NULL" , CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(data, NET_SSL_TAG, "Param data is NULL" , CA_STATUS_INVALID_PARAM);
+
+    oc_mutex_lock(g_sslContextMutex);
+    if (NULL == g_caSslContext)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+
+    SslEndPoint_t * peer = GetSslPeer(&sep->endpoint);
+    if (NULL == peer)
+    {
+        mbedtls_ssl_config * config = (sep->endpoint.adapter == CA_ADAPTER_IP ?
+                                   &g_caSslContext->serverDtlsConf : &g_caSslContext->serverTlsConf);
+        peer = NewSslEndPoint(&sep->endpoint, config);
+        if (NULL == peer)
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "Malloc failed!");
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
+        //Load allowed TLS suites from SVR DB
+        SetupCipher(config, sep->endpoint.adapter);
+
+        ret = u_arraylist_add(g_caSslContext->peerList, (void *) peer);
+        if (!ret)
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "u_arraylist_add failed!");
+            OICFree(peer);
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    peer->recBuf.buff = data;
+    peer->recBuf.len = dataLen;
+    peer->recBuf.loaded = 0;
+
+    while (MBEDTLS_SSL_HANDSHAKE_OVER != peer->ssl.state)
+    {
+        ret = mbedtls_ssl_handshake_step(&peer->ssl);
+        if (MBEDTLS_ERR_SSL_CONN_EOF == ret)
+        {
+            break;
+        }
+
+        if (MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED == ret)
+        {
+            OIC_LOG(DEBUG, NET_SSL_TAG, "Hello verification requested");
+            mbedtls_ssl_session_reset(&peer->ssl);
+            mbedtls_ssl_set_client_transport_id(&peer->ssl,
+                                                (const unsigned char *) sep->endpoint.addr,
+                                                 sizeof(sep->endpoint.addr));
+            ret = mbedtls_ssl_handshake_step(&peer->ssl);
+        }
+        uint32_t flags = mbedtls_ssl_get_verify_result(&peer->ssl);
+        if (0 != flags)
+        {
+            OIC_LOG_BUFFER(ERROR, NET_SSL_TAG, (const uint8_t *) &flags, sizeof(flags));
+            SSL_CHECK_FAIL(peer, flags, "Cert verification failed", 1,
+                                                     CA_STATUS_FAILED, GetAlertCode(flags));
+        }
+        SSL_CHECK_FAIL(peer, ret, "Handshake error", 1, CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
+        if (MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC == peer->ssl.state)
+        {
+            memcpy(peer->master, peer->ssl.session_negotiate->master, sizeof(peer->master));
+            g_caSslContext->selectedCipher = peer->ssl.session_negotiate->ciphersuite;
+        }
+        if (MBEDTLS_SSL_CLIENT_KEY_EXCHANGE == peer->ssl.state)
+        {
+            memcpy(peer->random, peer->ssl.handshake->randbytes, sizeof(peer->random));
+        }
+
+        if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
+        {
+            SSL_RES(peer, CA_STATUS_OK);
+            if (MBEDTLS_SSL_IS_CLIENT == peer->ssl.conf->endpoint)
+            {
+                SendCacheMessages(peer);
+            }
+
+            if (MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 == g_caSslContext->selectedCipher ||
+                MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA == g_caSslContext->selectedCipher)
+            {
+                char uuid[UUID_LENGTH * 2 + 5] = {0};
+                void * uuidPos = NULL;
+                void * userIdPos = NULL;
+                const mbedtls_x509_crt * peerCert = mbedtls_ssl_get_peer_cert(&peer->ssl);
+                ret = (NULL == peerCert ? -1 : 0);
+                SSL_CHECK_FAIL(peer, ret, "Failed to retrieve cert", 1,
+                                            CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_NO_CERT);
+                uuidPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
+                                                 UUID_PREFIX, sizeof(UUID_PREFIX) - 1);
+
+                if (NULL != uuidPos)
+                {
+                    memcpy(uuid, (char*) uuidPos + sizeof(UUID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
+                    ret = ConvertStrToUuid(uuid, &peer->sep.identity);
+                    SSL_CHECK_FAIL(peer, ret, "Failed to convert subject", 1,
+                                          CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
+                }
+                else
+                {
+                    OIC_LOG(WARNING, NET_SSL_TAG, "uuid not found");
+                }
+
+                userIdPos = memmem(peerCert->subject_raw.p, peerCert->subject_raw.len,
+                                             USERID_PREFIX, sizeof(USERID_PREFIX) - 1);
+                if (NULL != userIdPos)
+                {
+                    memcpy(uuid, (char*) userIdPos + sizeof(USERID_PREFIX) - 1, UUID_LENGTH * 2 + 4);
+                    ret = ConvertStrToUuid(uuid, &peer->sep.userId);
+                    SSL_CHECK_FAIL(peer, ret, "Failed to convert subject alt name", 1,
+                                      CA_STATUS_FAILED, MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT);
+                }
+                else
+                {
+                    OIC_LOG(WARNING, NET_SSL_TAG, "Subject alternative name not found");
+                }
+            }
+
+            oc_mutex_unlock(g_sslContextMutex);
+            OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+            return CA_STATUS_OK;
+        }
+    }
+
+    if (MBEDTLS_SSL_HANDSHAKE_OVER == peer->ssl.state)
+    {
+        uint8_t decryptBuffer[TLS_MSG_BUF_LEN] = {0};
+        do
+        {
+            ret = mbedtls_ssl_read(&peer->ssl, decryptBuffer, TLS_MSG_BUF_LEN);
+        } while (MBEDTLS_ERR_SSL_WANT_READ == ret);
+
+        if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret)
+        {
+            OIC_LOG(INFO, NET_SSL_TAG, "Connection was closed gracefully");
+            SSL_CLOSE_NOTIFY(peer, ret);
+            RemovePeerFromList(&peer->sep.endpoint);
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_OK;
+        }
+
+        if (0 > ret)
+        {
+            OIC_LOG_V(ERROR, NET_SSL_TAG, "mbedtls_ssl_read returned -0x%x", -ret);
+            //SSL_RES(peer, CA_STATUS_FAILED);
+            RemovePeerFromList(&peer->sep.endpoint);
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
+        int adapterIndex = GetAdapterIndex(peer->sep.endpoint.adapter);
+        if (0 == adapterIndex || adapterIndex == 1)
+        {
+            g_caSslContext->adapterCallbacks[adapterIndex].recvCallback(&peer->sep, decryptBuffer, ret);
+        }
+        else
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "Unsuported adapter");
+            RemovePeerFromList(&peer->sep.endpoint);
+            oc_mutex_unlock(g_sslContextMutex);
+            return CA_STATUS_FAILED;
+        }
+    }
+
+    oc_mutex_unlock(g_sslContextMutex);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
+
+void CAsetSslAdapterCallbacks(CAPacketReceivedCallback recvCallback,
+                              CAPacketSendCallback sendCallback,
+                              CATransportAdapter_t type)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_VOID(sendCallback, NET_SSL_TAG, "sendCallback is NULL");
+    VERIFY_NON_NULL_VOID(recvCallback, NET_SSL_TAG, "recvCallback is NULL");
+    oc_mutex_lock(g_sslContextMutex);
+    if (NULL == g_caSslContext)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
+        oc_mutex_unlock(g_sslContextMutex);
+        return;
+    }
+
+//    if (MAX_SUPPORTED_ADAPTERS > type)
+    {
+        switch (type)
+        {
+            case CA_ADAPTER_IP:
+                g_caSslContext->adapterCallbacks[0].recvCallback = recvCallback;
+                g_caSslContext->adapterCallbacks[0].sendCallback = sendCallback;
+                break;
+            case CA_ADAPTER_TCP:
+                g_caSslContext->adapterCallbacks[1].recvCallback = recvCallback;
+                g_caSslContext->adapterCallbacks[1].sendCallback = sendCallback;
+                break;
+            default:
+                OIC_LOG_V(ERROR, NET_SSL_TAG, "Unsupported adapter: %d", type);
+        }
+    }
+
+    oc_mutex_unlock(g_sslContextMutex);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+}
+
+CAResult_t CAsetTlsCipherSuite(const uint32_t cipher)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(g_getCredentialTypesCallback, NET_SSL_TAG, "Param callback is null", CA_STATUS_FAILED);
+    g_getCredentialTypesCallback(g_caSslContext->cipherFlag);
+    switch(cipher)
+    {
+        case MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA:
+        {
+#ifdef __WITH_TLS__
+            //todo check that Cred with RSA cert exists
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
+                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
+                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
+#endif
+#ifdef __WITH_DTLS__
+            //todo check that Cred with RSA cert exists
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
+                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
+                                         tlsCipher[ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA]);
+#endif
+            g_caSslContext->cipher = ADAPTER_TLS_RSA_WITH_AES_256_CBC_SHA;
+            break;
+        }
+        case MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8:
+        {
+            if (false == g_caSslContext->cipherFlag[1])
+            {
+                OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for ECC");
+                return CA_STATUS_FAILED;
+            }
+#ifdef __WITH_TLS__
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
+#endif
+#ifdef __WITH_DTLS__
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8]);
+#endif
+            g_caSslContext->cipher = ADAPTER_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8;
+            break;
+        }
+        case MBEDTLS_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256:
+        {
+#ifdef __WITH_TLS__
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
+#endif
+#ifdef __WITH_DTLS__
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
+                                         tlsCipher[ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256]);
+#endif
+            g_caSslContext->cipher = ADAPTER_TLS_ECDH_ANON_WITH_AES_128_CBC_SHA_256;
+            break;
+        }
+        case MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
+        {
+#if 0 // PIN OTM
+            if (false == g_caSslContext->cipherFlag[0])
+            {
+                OIC_LOG(ERROR, NET_SSL_TAG, "No Credential for PSK");
+                return CA_STATUS_FAILED;
+            }
+#endif
+#ifdef __WITH_TLS__
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientTlsConf,
+                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverTlsConf,
+                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
+#endif
+#ifdef __WITH_DTLS__
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->clientDtlsConf,
+                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
+            mbedtls_ssl_conf_ciphersuites(&g_caSslContext->serverDtlsConf,
+                                          tlsCipher[ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256]);
+#endif
+            g_caSslContext->cipher = ADAPTER_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256;
+            break;
+        }
+        default:
+        {
+            OIC_LOG(ERROR, NET_SSL_TAG, "Unknown cipher");
+            return CA_STATUS_FAILED;
+        }
+    }
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Selected cipher: 0x%x", cipher);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAinitiateSslHandshake(const CAEndpoint_t *endpoint)
+{
+    CAResult_t res = CA_STATUS_OK;
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "Param endpoint is NULL" , CA_STATUS_INVALID_PARAM);
+    oc_mutex_lock(g_sslContextMutex);
+    if (NULL == InitiateTlsHandshake(endpoint))
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "TLS handshake failed");
+        res = CA_STATUS_FAILED;
+    }
+    oc_mutex_unlock(g_sslContextMutex);
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return res;
+}
+/**
+ * Expands the secret into blocks of data according
+ * to the algorithm specified in section 5 of RFC 4346
+ *
+ * This function writes upto @p bufLen bytes into the given output buffer @p buf
+ *
+ * @param  key    secret key.
+ * @param  keyLen    secret key length.
+ * @param  label    A PRF label.
+ * @param  labelLen     Actual length of @p label.
+ * @param  random1    Random seed.
+ * @param  random1Len     Actual length of @p random1 (may be zero).
+ * @param  random2     Random seed.
+ * @param  random2Len    Actual length of @p random2 (may be zero).
+ * @param  buf    Output buffer for generated random data.
+ * @param  bufLen    Maximum size of @p buf.
+ *
+ * @return The actual number of bytes written to @p buf or @c -1 on error.
+ */
+
+static int pHash (const unsigned char *key, size_t keyLen,
+     const unsigned char *label, size_t labelLen,
+     const unsigned char *random1, size_t random1Len,
+     const unsigned char *random2, size_t random2Len,
+     unsigned char *buf, size_t bufLen)
+{
+    unsigned char A[RANDOM_LEN] = {0};
+    unsigned char tmp[RANDOM_LEN] = {0};
+    size_t dLen;   /* digest length */
+    size_t len = 0;   /* result length */
+
+    VERIFY_NON_NULL_RET(key, NET_SSL_TAG, "key is NULL", -1);
+    VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", -1);
+    VERIFY_NON_NULL_RET(random1, NET_SSL_TAG, "random1 is NULL", -1);
+    VERIFY_NON_NULL_RET(random2, NET_SSL_TAG, "random2 is NULL", -1);
+    VERIFY_NON_NULL_RET(buf, NET_SSL_TAG, "buf is NULL", -1);
+
+    mbedtls_md_context_t hmacA;
+    mbedtls_md_context_t hmacP;
+
+    mbedtls_md_init(&hmacA);
+    mbedtls_md_init(&hmacP);
+
+    CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacA, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
+    CHECK_MBEDTLS_RET(mbedtls_md_setup, &hmacP, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 1);
+
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen );
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, label, labelLen);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random1, random1Len);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, random2, random2Len);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
+
+    dLen = RANDOM_LEN;
+
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
+
+    while (len + dLen < bufLen)
+    {
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
+
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
+
+        len += RANDOM_LEN;
+
+        memcpy(buf, tmp, dLen);
+        buf += dLen;
+
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacA);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacA, key, keyLen);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacA, A, dLen);
+        CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacA, A);
+    }
+
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_reset, &hmacP);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_starts, &hmacP, key, keyLen);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, A, dLen);
+
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, label, labelLen);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random1, random1Len);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_update, &hmacP, random2, random2Len);
+    CHECK_MBEDTLS_RET(mbedtls_md_hmac_finish, &hmacP, tmp);
+
+    memcpy(buf, tmp, bufLen - len);
+
+    mbedtls_md_free(&hmacA);
+    mbedtls_md_free(&hmacP);
+    return bufLen;
+
+exit:
+    mbedtls_md_free(&hmacA);
+    mbedtls_md_free(&hmacP);
+    return -1;
+}
+
+CAResult_t CAsslGenerateOwnerPsk(const CAEndpoint_t *endpoint,
+                            const uint8_t* label, const size_t labelLen,
+                            const uint8_t* rsrcServerDeviceId, const size_t rsrcServerDeviceIdLen,
+                            const uint8_t* provServerDeviceId, const size_t provServerDeviceIdLen,
+                            uint8_t* ownerPsk, const size_t ownerPskSize)
+{
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "In %s", __func__);
+    VERIFY_NON_NULL_RET(endpoint, NET_SSL_TAG, "endpoint is NULL", CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(label, NET_SSL_TAG, "label is NULL", CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(rsrcServerDeviceId, NET_SSL_TAG, "rsrcId is NULL", CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(provServerDeviceId, NET_SSL_TAG, "provId is NULL", CA_STATUS_INVALID_PARAM);
+    VERIFY_NON_NULL_RET(ownerPsk, NET_SSL_TAG, "ownerPSK is NULL", CA_STATUS_INVALID_PARAM);
+
+    oc_mutex_lock(g_sslContextMutex);
+    if (NULL == g_caSslContext)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Context is NULL");
+        oc_mutex_unlock(g_sslContextMutex);
+        OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+        return CA_STATUS_FAILED;
+    }
+    SslEndPoint_t * tep = GetSslPeer(endpoint);
+    if (NULL == tep)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "Session does not exist");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    uint8_t keyblock[KEY_BLOCK_LEN] = {0};
+    // "key expansion"
+    uint8_t lab[] = {0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e};
+    int ret = pHash(tep->master, sizeof(tep->master), lab, sizeof(lab),
+                    (tep->random) + RANDOM_LEN, RANDOM_LEN, tep->random, RANDOM_LEN,
+                    keyblock, KEY_BLOCK_LEN);
+    if (-1 == ret)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+    ret = pHash(keyblock, sizeof(keyblock), label, labelLen,
+                rsrcServerDeviceId, rsrcServerDeviceIdLen,
+                provServerDeviceId, provServerDeviceIdLen,
+                ownerPsk, ownerPskSize);
+    if (-1 == ret)
+    {
+        OIC_LOG(ERROR, NET_SSL_TAG, "PSK not generated");
+        oc_mutex_unlock(g_sslContextMutex);
+        return CA_STATUS_FAILED;
+    }
+
+    oc_mutex_unlock(g_sslContextMutex);
+
+    OIC_LOG_V(DEBUG, NET_SSL_TAG, "Out %s", __func__);
+    return CA_STATUS_OK;
+}
index 3e591fe..9e52db8 100644 (file)
@@ -89,20 +89,6 @@ static CAGetDTLSPskCredentialsHandler g_getCredentialsCallback = NULL;
  */
 static CAErrorCallback g_dtlsHandshakeCallback = NULL;
 
-#ifdef __WITH_X509__
-/**
- * @var g_getX509CredentialsCallback
- * @brief callback to get DTLS certificate credentials
- */
-static CAGetDTLSX509CredentialsHandler g_getX509CredentialsCallback = NULL;
-/**
- * @var g_getCrlCallback
- * @brief callback to get CRL for DTLS
- */
-static CAGetDTLSCrlHandler g_getCrlCallback = NULL;
-#endif //__WITH_X509__
-
-
 static CASecureEndpoint_t *GetPeerInfo(const CAEndpoint_t *peer)
 {
     uint32_t list_index = 0;
diff --git a/resource/csdk/connectivity/src/adapter_util/pkix/cert.c b/resource/csdk/connectivity/src/adapter_util/pkix/cert.c
deleted file mode 100644 (file)
index 4a02949..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#include "byte_array.h"
-#include "cert.h"
-#include "der_dec.h"
-
-
-extern const uint8_t g_ECDSA_WITH_SHA256_OID[];
-extern const uint8_t g_EC_PUBLIC_KEY_OID[];
-extern const uint8_t g_PRIME_256_V1_OID[];
-
-/**
- * Decodes TBSCertificate.
- */
-static PKIError DecodeTbs(CertificateX509 *const crt)
-{
-    FUNCTION_INIT(
-        size_t length, temp_len;
-        ByteArray tbs = crt->tbs, temp;
-        CHECK_NULL(crt, PKI_NULL_PASSED);
-    );
-    //skip version
-    SKIP_DER_FIELD(tbs, DER_VERSION, length);
-    //serial number
-    COPY_DER_FIELD(tbs, crt, serNum, DER_INTEGER, length);
-
-    CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &tbs, &length);
-    //copy to temp
-    temp = tbs; // OPTIONAL
-    INC_BYTE_ARRAY(tbs, length); // skip algorithm identifier
-    //check_signature_algorithm
-    //1.2.840.10045.4.3.2
-    CHECK_DER_OID(temp, g_ECDSA_WITH_SHA256_OID, ECDSA_WITH_SHA256_OID_LEN, temp_len);
-    //copy issuer X.500 name
-    COPY_DER_FIELD(tbs, crt, issuer, DER_SEQUENCE, length);
-    CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &tbs, &length);
-
-    //copy valid period
-    COPY_DER_FIELD(tbs, crt, validFrom, DER_UTC_TIME, length);
-    COPY_DER_FIELD(tbs, crt, validTo, DER_UTC_TIME, length);
-
-    //copy subject X.500 name
-    COPY_DER_FIELD(tbs, crt, subject, DER_SEQUENCE, length);
-    //public key
-    CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &tbs, &length);
-    CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &tbs, &length);
-    //check public key type
-    //1.2.840.10045.2.1
-    CHECK_DER_OID(tbs, g_EC_PUBLIC_KEY_OID, EC_PUBLIC_KEY_OID_LEN, length);
-    INC_BYTE_ARRAY(tbs, length);
-    //check curve
-    //1.2.840.10045.3.1.7
-    CHECK_DER_OID(tbs, g_PRIME_256_V1_OID, PRIME_256_V1_OID_LEN, length);
-    INC_BYTE_ARRAY(tbs, length);
-    //copy public key
-    COPY_DER_FIELD(tbs, crt, pubKey, DER_BIT_STRING, length);
-    FUNCTION_CLEAR();
-}
-
-
-/**
- * Decodes certificate in DER format.
- */
-PKIError DecodeCertificate(ByteArray code, CertificateX509 *crt)
-{
-    FUNCTION_INIT(
-        size_t length, tempLen;
-        ByteArray temp;
-        CHECK_NULL(crt, PKI_NULL_PASSED);
-        CHECK_NULL(code.data, PKI_NULL_PASSED);
-    );
-    CHECK_EQUAL(*(code.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //store sequence position
-    temp = code;
-    //TODO check length of TBS
-    //copy tbs
-    COPY_DER_FIELD(code, crt, tbs, DER_SEQUENCE, length);
-    //decode tbs
-    CHECK_CALL(DecodeTbs, crt);
-    //include sequense and len to tbs
-    crt->tbs.len +=  crt->tbs.data - temp.data;
-    crt->tbs.data = temp.data;
-    //printf("DATA %02X\n", *(code.data));
-    CHECK_EQUAL(*(code.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //copy to temp
-    temp = code;
-    INC_BYTE_ARRAY(code, length); // skip algorithm identifier
-    //check_signature_algorithm
-    //1.2.840.10045.4.3.2
-    CHECK_DER_OID(temp, g_ECDSA_WITH_SHA256_OID, ECDSA_WITH_SHA256_OID_LEN, tempLen);
-    //decode_signature_value
-    CHECK_EQUAL(*(code.data), DER_BIT_STRING, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //skip DER_UNIVERSAL
-    CHECK_EQUAL(*(code.data), DER_UNIVERSAL, PKI_INVALID_FORMAT);
-    CHECK_INC_BYTE_ARRAY(code, 1);
-    CHECK_EQUAL(*(code.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //copy sign r value
-    COPY_DER_FIELD(code, crt, signR, DER_INTEGER, length);
-    //copy sign s value
-    COPY_DER_FIELD(code, crt, signS, DER_INTEGER, length);
-
-    PARSE_SIGNATURE(crt);
-
-    FUNCTION_CLEAR();
-}
-
-#ifdef X509_DEBUG
-/**
- * Prints certificate to console.
- */
-PKIError PrintCertificate(const CertificateX509 *const crt)
-{
-    FUNCTION_INIT(
-        CHECK_NULL(crt, PKI_NULL_PASSED);
-    );
-    printf("\n-----BEGIN CERTIFICATE-----\n");
-    PRINT_BYTE_ARRAY("SER NUM:\n", crt->serNum);
-    PRINT_BYTE_ARRAY("ISSUER:\n", crt->issuer);
-    PRINT_BYTE_ARRAY("SUBJECT:\n", crt->subject);
-    PRINT_BYTE_ARRAY("PUB KEY:\n", crt->pubKey);
-    PRINT_BYTE_ARRAY("SIGN R VALUE:\n", crt->signR);
-    PRINT_BYTE_ARRAY("SIGN S VALUE:\n", crt->signS);
-    PRINT_BYTE_ARRAY("TBS:\n", crt->tbs);
-    printf("-----END CERTIFICATE-----\n");
-    FUNCTION_CLEAR(
-    );
-}
-#endif
-
-PKIError ParsePublicKey(ByteArray *caPublicKey)
-{
-    FUNCTION_INIT(
-        CHECK_NULL(caPublicKey, PKI_NULL_PASSED);
-    );
-
-    if ((caPublicKey->len == PUBLIC_KEY_SIZE + 2) && (caPublicKey->data[0] == 0)
-        && (caPublicKey->data[1] == ASN1_UNCOMPRESSED_KEY))
-        INC_BYTE_ARRAY(*caPublicKey, 2);
-    else if (caPublicKey->len != PUBLIC_KEY_SIZE)
-        CHECK_NULL(NULL, PKI_WRONG_ARRAY_LEN);
-
-    FUNCTION_CLEAR();
-}
diff --git a/resource/csdk/connectivity/src/adapter_util/pkix/crl.c b/resource/csdk/connectivity/src/adapter_util/pkix/crl.c
deleted file mode 100644 (file)
index 91a7608..0000000
+++ /dev/null
@@ -1,170 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#include "crl.h"
-#include "byte_array.h"
-#include "der_dec.h"
-#include "sn_store.h"
-#include "der_dec.h"
-#include "crypto_adapter.h"
-
-
-extern const uint8_t g_ECDSA_WITH_SHA256_OID[ECDSA_WITH_SHA256_OID_LEN];
-extern const uint8_t g_EC_PUBLIC_KEY_OID[EC_PUBLIC_KEY_OID_LEN];
-extern const uint8_t g_PRIME_256_V1_OID[PRIME_256_V1_OID_LEN];
-
-/*
- *   TBSCertList  ::=  SEQUENCE  {
- *       version                 Version OPTIONAL,
- *                                     -- if present, MUST be v2
- *        signature               AlgorithmIdentifier,
- *        issuer                  Name,
- *        thisUpdate              Time,
- *        revokedCertificates     SEQUENCE OF SEQUENCE  {
- *             userCertificate         CertificateSerialNumber,
- *             revocationDate          Time
- *                                  }  OPTIONAL,
- *                                  }
-*/
-
-
-/**
- * Decodes TBS of CRL.
- */
-static PKIError DecodeTbs(CertificateList *const crl)
-{
-    FUNCTION_INIT(
-        size_t length;
-        ByteArray tbs = crl->tbs, temp;
-        CHECK_NULL(crl, PKI_NULL_PASSED);
-        ByteArray sn = BYTE_ARRAY_INITIALIZER;
-        FreeSNStore();
-    );
-
-    CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &tbs, &length);
-
-    INC_BYTE_ARRAY(tbs, length); // skip algorithm identifier
-    //1.2.840.10045.4.3.2
-    //copy issuer X.500 name
-    COPY_DER_FIELD(tbs, crl, issuer, DER_SEQUENCE, length);
-    //copy date
-    COPY_DER_FIELD(tbs, crl, date, DER_UTC_TIME, length);
-    //COPY_DER_FIELD(tbs, crl, date, DER_UTC_TIME, length); // optional
-    // copy serial numbers
-    CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &tbs, &length);
-    temp.data = tbs.data;
-    temp.len = length;
-    while (tbs.data < temp.data + temp.len)
-    {
-        CHECK_EQUAL(*(tbs.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-        CHECK_CALL(DecodeLength , &tbs, &length);
-        //serial number
-        CHECK_EQUAL(*(tbs.data), DER_INTEGER, PKI_INVALID_FORMAT);
-        CHECK_CALL(DecodeLength , &tbs, &length);
-        sn.data = tbs.data;
-        sn.len = length;
-        CHECK_CALL(StoreSerialNumber, sn);
-        INC_BYTE_ARRAY(tbs, length);
-        SKIP_DER_FIELD(tbs, DER_UTC_TIME, length);
-    }
-    FUNCTION_CLEAR();
-}
-
-/*
- * CertificateList  ::=  SEQUENCE  {
- *      tbsCertList          TBSCertList,
- *      signatureAlgorithm   AlgorithmIdentifier,
- *      signatureValue       BIT STRING  }
-*/
-
-/**
- * Decodes certificate in DER format.
- */
-PKIError DecodeCertificateList(ByteArray code, CertificateList *crl, ByteArray caPubKey)
-{
-    FUNCTION_INIT(
-        size_t length, tempLen;
-        ByteArray temp;
-        CHECK_NULL(crl, PKI_NULL_PASSED);
-        CHECK_NULL(code.data, PKI_NULL_PASSED);
-    );
-    CHECK_EQUAL(*(code.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //store sequence position
-    temp = code;
-    //TODO check length of TBS
-    //copy tbs
-    COPY_DER_FIELD(code, crl, tbs, DER_SEQUENCE, length);
-    //decode tbs
-    CHECK_CALL(DecodeTbs, crl);  //TODO
-    //include sequense and len to tbs
-    crl->tbs.len +=  crl->tbs.data - temp.data;
-    crl->tbs.data = temp.data;
-
-    CHECK_EQUAL(*(code.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //copy to temp
-    temp = code;
-    INC_BYTE_ARRAY(code, length); // skip algorithm identifier
-    //check_signature_algorithm
-    //1.2.840.10045.4.3.2
-    CHECK_DER_OID(temp, g_ECDSA_WITH_SHA256_OID, ECDSA_WITH_SHA256_OID_LEN, tempLen);
-    //decode_signature_value
-    CHECK_EQUAL(*(code.data), DER_BIT_STRING, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //skip DER_UNIVERSAL
-    CHECK_EQUAL(*(code.data), DER_UNIVERSAL, PKI_INVALID_FORMAT);
-    CHECK_INC_BYTE_ARRAY(code, 1);
-    CHECK_EQUAL(*(code.data), DER_SEQUENCE, PKI_INVALID_FORMAT);
-    CHECK_CALL(DecodeLength , &code, &length);
-    //copy sign r value
-    COPY_DER_FIELD(code, crl, signR, DER_INTEGER, length);
-    //copy sign s value
-    COPY_DER_FIELD(code, crl, signS, DER_INTEGER, length);
-    if (caPubKey.data != NULL)
-    {
-        PARSE_SIGNATURE(crl);
-        CHECK_SIGN(*crl, caPubKey);
-    }
-    FUNCTION_CLEAR();
-}
-
-#ifdef X509_DEBUG
-/**
- * Prints CRL to console.
- */
-PKIError PrintCRL(const CertificateList *const crl)
-{
-    FUNCTION_INIT(
-        CHECK_NULL(crl, PKI_NULL_PASSED);
-    );
-    printf("\n-----BEGIN CRL-----\n");
-    PRINT_BYTE_ARRAY("ISSUER:\n", crl->issuer);
-    PRINT_BYTE_ARRAY("DATE:\n", crl->date);
-    PRINT_BYTE_ARRAY("TBS:\n", crl->tbs);
-    printf("-----END CRL-----\n");
-    FUNCTION_CLEAR(
-    );
-}
-#endif
diff --git a/resource/csdk/connectivity/src/adapter_util/pkix/der_const.c b/resource/csdk/connectivity/src/adapter_util/pkix/der_const.c
deleted file mode 100644 (file)
index b342918..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-#include "stdint.h"
-
-const uint8_t g_ECDSA_WITH_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02};
-const uint8_t g_EC_PUBLIC_KEY_OID[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01};
-const uint8_t g_PRIME_256_V1_OID[] = {0x2A, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07};
-
-
diff --git a/resource/csdk/connectivity/src/adapter_util/pkix/der_dec.c b/resource/csdk/connectivity/src/adapter_util/pkix/der_dec.c
deleted file mode 100644 (file)
index 06e46b9..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-#include "der_dec.h"
-
-/**
- * Computes length.
- */
-PKIError DecodeLength(ByteArray *code, size_t *length)
-{
-    FUNCTION_INIT(
-        CHECK_NULL_BYTE_ARRAY_PTR(code, PKI_NULL_PASSED);
-    );
-    CHECK_INC_BYTE_ARRAY_PTR(code, 1);
-
-    if ((*(code->data)) < LEN_LONG)
-    {
-        *length = *(code->data);
-        CHECK_INC_BYTE_ARRAY_PTR(code, 1);
-    }
-    else
-    {
-        uint8_t i = 0;
-        uint8_t blocksNum = *(code->data) - LEN_LONG;
-        CHECK_INC_BYTE_ARRAY_PTR(code, 1);
-        CHECK_LESS(blocksNum, 5, PKI_WRONG_OCTET_LEN);
-        *length = 0;
-
-        for (i = 0; i < blocksNum; ++i)
-        {
-            *length |= (size_t) (((size_t) *(code->data)) << ((blocksNum - i - 1) * SIZE_OF_BYTE));
-            CHECK_INC_BYTE_ARRAY_PTR(code, 1);
-        }
-    }
-
-    //should be: length  <=  array size
-    CHECK_LESS_EQUAL(*length, code->len, PKI_WRONG_OCTET_LEN);
-    FUNCTION_CLEAR();
-}
diff --git a/resource/csdk/connectivity/src/adapter_util/pkix/pki.c b/resource/csdk/connectivity/src/adapter_util/pkix/pki.c
deleted file mode 100644 (file)
index 8d32cc9..0000000
+++ /dev/null
@@ -1,225 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-#include "pki.h"
-#include "cert.h"
-#include "sn_store.h"
-#include "der_dec.h"
-#include "crypto_adapter.h"
-
-#ifndef WITH_ARDUINO
-#include <time.h>
-#endif
-
-
-/**
- * Check: notBefore <= now <= notAfter.
- */
-PKIError CheckValidity(ByteArray dateFrom, ByteArray dateTo)
-{
-    FUNCTION_INIT(
-        struct tm t = {0};
-        struct tm lnow = {0};
-        time_t now;
-        int i;
-        ByteArray date;
-        CHECK_EQUAL(dateFrom.len, UTC_TIME_LEN, PKI_INVALID_DATE_FORMAT);
-        CHECK_EQUAL(dateTo.len, UTC_TIME_LEN, PKI_INVALID_DATE_FORMAT);
-    );
-    /* Get the current time */
-    now = time(NULL);
-    gmtime_r( &now, &lnow);
-    for (i = 0; i < 2; i ++)
-    {
-        date = (i == 0 ? dateFrom : dateTo);
-        t.tm_year = (date.data[0] - '0') * 10 + date.data[1] - '0';
-        /* It is considered date from 1950 to 2050 */
-        if (t.tm_year < 50)
-        {
-            t.tm_year += 100;
-        }
-        t.tm_mon = (date.data[2] - '0') * 10 + date.data[3] - '0' - 1;
-        t.tm_mday = (date.data[4] - '0') * 10 + date.data[5] - '0';
-        t.tm_hour = (date.data[6] - '0') * 10 + date.data[7] - '0';
-        t.tm_min = (date.data[8] - '0') * 10 + date.data[9] - '0';
-        t.tm_sec = (date.data[10] - '0') * 10 + date.data[11] - '0';
-        if (i == 0)
-        {
-            CHECK_LESS_EQUAL(t.tm_year, lnow.tm_year, PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year)
-            CHECK_LESS_EQUAL(t.tm_mon, lnow.tm_mon, PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon)
-                CHECK_LESS_EQUAL(t.tm_mday, lnow.tm_mday, PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon &&  t.tm_mday == lnow.tm_mday)
-                CHECK_LESS_EQUAL(t.tm_hour, lnow.tm_hour, PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon &&  t.tm_mday == lnow.tm_mday
-                && t.tm_hour == lnow.tm_hour)
-                CHECK_LESS_EQUAL(t.tm_min, lnow.tm_min, PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon &&  t.tm_mday == lnow.tm_mday
-                && t.tm_hour == lnow.tm_hour && t.tm_min == lnow.tm_min)
-                CHECK_LESS_EQUAL(t.tm_sec, lnow.tm_sec, PKI_CERT_DATE_INVALID);
-        }
-        else
-        {
-            CHECK_LESS_EQUAL(lnow.tm_year, t.tm_year,  PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year)
-            CHECK_LESS_EQUAL(lnow.tm_mon, t.tm_mon,  PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon)
-                CHECK_LESS_EQUAL(lnow.tm_mday, t.tm_mday,  PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon &&  t.tm_mday == lnow.tm_mday)
-                CHECK_LESS_EQUAL(lnow.tm_hour, t.tm_hour,  PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon &&  t.tm_mday == lnow.tm_mday
-                && t.tm_hour == lnow.tm_hour)
-                CHECK_LESS_EQUAL(lnow.tm_min, t.tm_min,  PKI_CERT_DATE_INVALID);
-            if (t.tm_year == lnow.tm_year && t.tm_mon == lnow.tm_mon &&  t.tm_mday == lnow.tm_mday
-                && t.tm_hour == lnow.tm_hour && t.tm_min == lnow.tm_min)
-                CHECK_LESS_EQUAL(lnow.tm_sec, t.tm_sec, PKI_CERT_DATE_INVALID);
-        }
-    }
-    FUNCTION_CLEAR();
-}
-
-/**
- * Decode certDerCode certificate and performs verification.
- *
- * @param[in] certDerCode  Byte array with DER encoded certificate
- * @param[in] caPublicKey  Byte array with CA public key
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CheckCertificate(ByteArray certDerCode, ByteArray caPublicKey)
-{
-    FUNCTION_INIT(
-        CertificateX509 crt;
-        INIT_BYTE_ARRAY(crt.tbs);
-        INIT_BYTE_ARRAY(crt.signR);
-        INIT_BYTE_ARRAY(crt.signS);
-        INIT_BYTE_ARRAY(crt.pubKey);
-        INIT_BYTE_ARRAY(crt.issuer);
-        INIT_BYTE_ARRAY(crt.subject);
-    );
-
-    CHECK_CALL(DecodeCertificate, certDerCode, &crt);
-    CHECK_CALL(CheckValidity, crt.validFrom, crt.validTo);
-    CHECK_CALL(ParsePublicKey, &caPublicKey);
-    CHECK_SIGN(crt, caPublicKey);
-    CHECK_CALL(CheckSerialNumber, crt.serNum);
-
-    FUNCTION_CLEAR();
-}
-
-/*
- * https://tools.ietf.org/html/rfc5246
- * This is a sequence (chain) of certificates.  The sender's  certificate MUST come first
- * in the list.  Each following certificate MUST directly certify the one preceding it.
- */
-
-
-/*
- * Handshake Message: certificate consist of the list of certificates.
- * Certificate length (3 bytes)
- * DER encoded certificate
- * The first is server’s certificate
- * Other certificates are optional
- * Usually intermediate CA certificates
- */
-
-// Parses each certificate from list.
-PKIError ParseCertificateChain (ByteArray *chainDerCode, CertificateX509 *chainCrt,
-                                uint8_t chainLen)
-{
-    FUNCTION_INIT(
-        int i;
-        CHECK_NULL(chainDerCode, PKI_NULL_PASSED);
-        CHECK_NULL(chainCrt, PKI_NULL_PASSED);
-        CHECK_LESS_EQUAL(chainLen, MAX_CHAIN_LEN, PKI_WRONG_ARRAY_LEN);
-    );
-    for (i = 0; i < chainLen; i++)
-    {
-        CHECK_CALL(DecodeCertificate, (*chainDerCode), chainCrt);
-#ifdef X509_DEBUG
-        PrintCertificate(chainCrt);
-#endif
-        chainDerCode++;
-        chainCrt++;
-    }
-    FUNCTION_CLEAR();
-}
-
-// Loads certificates from TLS message
-PKIError LoadCertificateChain (ByteArray msg, ByteArray *chain, uint8_t *chainLength)
-{
-    FUNCTION_INIT(
-        CHECK_NULL(msg.data, PKI_NULL_PASSED);
-        CHECK_LESS_EQUAL(3, msg.len, PKI_WRONG_ARRAY_LEN);
-        CHECK_NULL(chain, PKI_NULL_PASSED);
-        CHECK_NULL(chainLength, PKI_NULL_PASSED);
-        uint32_t tmpLengthChain = 0;
-        *chainLength = 0;
-    );
-
-    CHECK_COND(msg.data[0] != 0 || msg.data[1] != 0 || msg.data[2] != 3, PKI_SUCCESS);
-#ifdef X509_DEBUG
-    printf("start chain parsing\n");
-#endif
-    while (msg.len > 0)
-    {
-#ifdef X509_DEBUG
-        printf("chain parsing: %d\n", msg.len);
-#endif
-        CHECK_LESS_EQUAL(3, msg.len, PKI_WRONG_ARRAY_LEN);
-        tmpLengthChain = (((uint32_t) msg.data[0]) << 16) | (((uint32_t) msg.data[1]) << 8) | msg.data[2];
-        CHECK_INC_BYTE_ARRAY(msg, 3);
-        (*chain).data = msg.data;
-        (*chain).len = tmpLengthChain;
-        chain ++;
-        (*chainLength) ++;
-        CHECK_LESS_EQUAL((*chainLength), MAX_CHAIN_LEN, PKI_WRONG_ARRAY_LEN);
-        CHECK_INC_BYTE_ARRAY(msg, tmpLengthChain); // Check this
-    }
-    FUNCTION_CLEAR();
-}
-
-/*
- * Certificate validation requires that root keys be distributed independently, 
- * the self-signed certificate that specifies the root certificate authority MAY be omitted 
- * from the chain, under the assumption that the remote end must already possess it in order to
- * validate it in any case.
- */
-
-// Verifies each certificate from list using next public key from list
-PKIError CheckCertificateChain (CertificateX509 *chainCrt, uint8_t chainLen, ByteArray caPubKey)
-{
-    FUNCTION_INIT(
-        int i;
-        CHECK_NULL(chainCrt, PKI_NULL_PASSED);
-        CHECK_LESS_EQUAL(chainLen, MAX_CHAIN_LEN, PKI_WRONG_ARRAY_LEN);
-    );
-    for (i = 0; i < chainLen - 1; i++)
-    {
-       ParsePublicKey(&(chainCrt + 1)->pubKey);
-       CHECK_SIGN(*chainCrt, (chainCrt + 1)->pubKey);
-       CHECK_CALL(CheckSerialNumber, chainCrt->serNum);
-       chainCrt++;
-    }
-    CHECK_SIGN(*chainCrt, caPubKey);
-    CHECK_CALL(CheckSerialNumber, chainCrt->serNum);
-    FUNCTION_CLEAR();
-}
-
diff --git a/resource/csdk/connectivity/src/adapter_util/pkix/sn_store.c b/resource/csdk/connectivity/src/adapter_util/pkix/sn_store.c
deleted file mode 100644 (file)
index f3db429..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-#include "sn_store.h"
-#include <string.h>
-#include <stdlib.h>
-
-//Size of initial memory
-#define CRL_BLOCK_LEN 20
-
-
-/**
- * @struct SNStore
- *
- * General structure for storing serial numbers.
- *
- * Contains pointer to array of bytes and it's length.
- */
-typedef struct
-{
-    ByteArray array;     /**< Byte array with data*/
-    size_t blockNumber;  /**< Number of used memory blocks */
-} SNStore;
-
-
-/**
- * Internal storage for serial numbers.
- */
-static SNStore  Store = {{NULL, 0}, 1};
-
-// Frees memory occupied by SN storage.
-void FreeSNStore(void)
-{
-    free(Store.array.data);
-    INIT_BYTE_ARRAY(Store.array);
-    Store.blockNumber = 1;
-}
-
-// Stores serial number to SN storage.
-PKIError StoreSerialNumber(const ByteArray sn)
-{
-    FUNCTION_INIT(
-        uint8_t *temp = NULL;
-        CHECK_NULL(sn.data, PKI_NULL_PASSED);
-    );
-    if (Store.array.len == 0 || Store.array.len + sn.len + 1 > CRL_BLOCK_LEN * Store.blockNumber)
-    {
-        temp = (uint8_t *) realloc(Store.array.data,
-                                    sizeof(uint8_t) * CRL_BLOCK_LEN * Store.blockNumber * 2);
-        CHECK_NULL(temp, PKI_MEMORY_ALLOC_FAILED);
-        Store.array.data = temp;
-        Store.blockNumber *= 2;
-    }
-    Store.array.data[Store.array.len] = sn.len;
-    memcpy(&Store.array.data[Store.array.len + 1], sn.data, sn.len);
-    Store.array.len += sn.len + 1;
-    FUNCTION_CLEAR(
-        if (error_value != PKI_SUCCESS)  free(temp);
-    );
-}
-
-
-// Checks whether there is serial number in SN storage
-PKIError CheckSerialNumber(const ByteArray sn)
-{
-    FUNCTION_INIT(
-        unsigned long int i;
-        int res;
-        CHECK_NULL(sn.data, PKI_NULL_PASSED);
-    );
-    CHECK_NULL(Store.array.data, PKI_SUCCESS);
-    for ( i = 0; i < Store.array.len; i += Store.array.data[i] + 1)
-    {
-        if (sn.len == Store.array.data[i])
-        {
-            res  = memcmp(&Store.array.data[i + 1], sn.data, sn.len);
-            CHECK_NOT_EQUAL(res, 0, PKI_CERT_REVOKED);
-        }
-    }
-    FUNCTION_CLEAR();
-}
-
-#ifdef X509_DEBUG
-//Prints store content
-void PrintSNStore(void)
-{
-    ByteArray curr;
-    int i, count = 0;
-    if (Store.array.data != NULL)
-    {
-        for ( i = 0; i < Store.array.len; i += Store.array.data[i] + 1)
-        {
-            curr.len = Store.array.data[i];
-            curr.data = &Store.array.data[i + 1];
-            PRINT_BYTE_ARRAY("", curr);
-            count++;
-        }
-    }
-    printf("\nSN STORE CONTAINS %d ELEMENTS\n", count);
-}
-#endif //DEBUG
index 0dc5a52..f430de2 100644 (file)
 #include "canetworkconfigurator.h"
 #include "cainterfacecontroller.h"
 #include "logger.h"
-#ifdef __WITH_DTLS__
-#include "caadapternetdtls.h"
-#endif
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
+#include "ca_adapter_net_ssl.h"
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
 #ifdef TCP_ADAPTER
 #include "catcpadapter.h"
-#ifdef __WITH_TLS__
-#include "ca_adapter_net_tls.h"
-#endif
 #endif
 
 CAGlobals_t caglobals = { .clientFlags = 0,
@@ -49,24 +46,12 @@ CAGlobals_t caglobals = { .clientFlags = 0,
 
 static bool g_isInitialized = false;
 
-#ifdef __WITH_DTLS__
-// CAAdapterNetDTLS will register the callback.
-// Taking callback all the way through adapters not the right approach, hence calling here.
-extern void CADTLSSetCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
-#endif
-
-#ifdef __WITH_X509__
-// CAAdapterNetDTLS will register the callback.
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 // Taking callback all the way through adapters not the right approach, hence calling here.
-extern void CADTLSSetX509CredentialsCallback(CAGetDTLSX509CredentialsHandler credCallback);
-extern void CADTLSSetCrlCallback(CAGetDTLSCrlHandler crlCallback);
-#endif
-
-#ifdef __WITH_TLS__
 extern void CAsetPkixInfoCallback(CAgetPkixInfoHandler infCallback);
-extern void CAsetTlsCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
+extern void CAsetPskCredentialsCallback(CAgetPskCredentialsHandler credCallback);
 extern void CAsetCredentialTypesCallback(CAgetCredentialTypesHandler credCallback);
-#endif
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
 
 CAResult_t CAInitialize()
@@ -155,50 +140,21 @@ void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHand
 
     CASetInterfaceCallbacks(ReqHandler, RespHandler, ErrorHandler);
 }
-
-#ifdef __WITH_DTLS__
-CAResult_t CARegisterDTLSHandshakeCallback(CAErrorCallback dtlsHandshakeCallback)
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
+CAResult_t CAregisterSslHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
 {
-    OIC_LOG(DEBUG, TAG, "CARegisterDTLSHandshakeCallback");
-
-    if (!g_isInitialized)
-    {
-        return CA_STATUS_NOT_INITIALIZED;
-    }
-
-    CADTLSSetHandshakeCallback(dtlsHandshakeCallback);
-
-    return CA_STATUS_OK;
-}
-
-CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentialsHandler)
-{
-    OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
-
-    if (!g_isInitialized)
-    {
-        return CA_STATUS_NOT_INITIALIZED;
-    }
-
-    CADTLSSetCredentialsCallback(GetDTLSCredentialsHandler);
-    return CA_STATUS_OK;
-}
-#endif //__WITH_DTLS__
-#ifdef __WITH_TLS__
-CAResult_t CAregisterTlsHandshakeCallback(CAErrorCallback tlsHandshakeCallback)
-{
-    OIC_LOG(DEBUG, TAG, "CARegisterTlsHandshakeCallback");
+    OIC_LOG(DEBUG, TAG, "CAregisterSslHandshakeCallback");
 
     if(!g_isInitialized)
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
 
-    CAsetTlsHandshakeCallback(tlsHandshakeCallback);
+    CAsetSslHandshakeCallback(tlsHandshakeCallback);
     return CA_STATUS_OK;
 }
 
-CAResult_t CAregisterTlsCredentialsHandler(CAGetDTLSPskCredentialsHandler getTlsCredentialsHandler)
+CAResult_t CAregisterPskCredentialsHandler(CAgetPskCredentialsHandler getTlsCredentialsHandler)
 {
     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
 
@@ -206,7 +162,7 @@ CAResult_t CAregisterTlsCredentialsHandler(CAGetDTLSPskCredentialsHandler getTls
     {
         return CA_STATUS_NOT_INITIALIZED;
     }
-    CAsetTlsCredentialsCallback(getTlsCredentialsHandler);
+    CAsetPskCredentialsCallback(getTlsCredentialsHandler);
     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
     return CA_STATUS_OK;
 }
@@ -236,35 +192,7 @@ CAResult_t CAregisterGetCredentialTypesHandler(CAgetCredentialTypesHandler getCr
     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
     return CA_STATUS_OK;
 }
-#endif
-
-#ifdef __WITH_X509__
-CAResult_t CARegisterDTLSX509CredentialsHandler(CAGetDTLSX509CredentialsHandler GetDTLSX509CredentialsHandler)
-{
-    OIC_LOG(DEBUG, TAG, "CARegisterDTLSX509CredentialsHandler");
-
-    if (!g_isInitialized)
-    {
-        return CA_STATUS_NOT_INITIALIZED;
-    }
-
-    CADTLSSetX509CredentialsCallback(GetDTLSX509CredentialsHandler);
-    return CA_STATUS_OK;
-}
-
-CAResult_t CARegisterDTLSCrlHandler(CAGetDTLSCrlHandler GetDTLSCrlHandler)
-{
-    OIC_LOG(DEBUG, TAG, "CARegisterDTLSCrlHandler");
-
-    if (!g_isInitialized)
-    {
-        return CA_STATUS_NOT_INITIALIZED;
-    }
-
-    CADTLSSetCrlCallback(GetDTLSCrlHandler);
-    return CA_STATUS_OK;
-}
-#endif //__WITH_X509__
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
 CAResult_t CACreateEndpoint(CATransportFlags_t flags,
                             CATransportAdapter_t adapter,
@@ -534,27 +462,14 @@ CAResult_t CAHandleRequestResponse()
 #if defined (__WITH_DTLS__) || defined(__WITH_TLS__)
 CAResult_t CASelectCipherSuite(const uint16_t cipher, CATransportAdapter_t adapter)
 {
-    OIC_LOG_V(DEBUG, TAG, "IN CASelectCipherSuite");
-    OIC_LOG_V(DEBUG, TAG, "cipher : %d , CATransportAdapter : %d",cipher, adapter);
-    if(CA_ADAPTER_IP == adapter)
+    OIC_LOG_V(DEBUG, TAG, "IN %s", __func__);
+    OIC_LOG_V(DEBUG, TAG, "cipher : %d , CATransportAdapter : %d", cipher, adapter);
+    if (CA_STATUS_OK != CAsetTlsCipherSuite(cipher))
     {
-        if (CA_STATUS_OK != CADtlsSelectCipherSuite(cipher))
-        {
-            OIC_LOG_V(DEBUG, TAG, "CADtlsSelectCipherSuite failed");
-            return CA_STATUS_FAILED;
-        }
-    }
-#ifdef __WITH_TLS__
-    else if(CA_ADAPTER_TCP == adapter)
-    {
-        if (CA_STATUS_OK != CAsetTlsCipherSuite(cipher))
-        {
-            OIC_LOG_V(DEBUG, TAG, "CAsetTlsCipherSuite failed");
-            return CA_STATUS_FAILED;
-        }
+        OIC_LOG_V(ERROR, TAG, "Out %s", __func__);
+        return CA_STATUS_FAILED;
     }
-#endif
-    OIC_LOG_V(DEBUG, TAG, "CASelectCipherSuite OK");
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
     return CA_STATUS_OK;
 }
 
@@ -562,13 +477,7 @@ CAResult_t CAEnableAnonECDHCipherSuite(const bool enable)
 {
     OIC_LOG_V(DEBUG, TAG, "CAEnableAnonECDHCipherSuite");
 
-#ifdef __WITH_DTLS__
-    if (CA_STATUS_OK != CADtlsEnableAnonECDHCipherSuite(enable))
-    {
-        return CA_STATUS_FAILED;
-    }
-#endif
-#ifdef __WITH_TLS__
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
     // TLS_ECDH_ANON_WITH_AES_128_CBC_SHA256    0xFF00 replaces 0xC018
     // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256    0xC037
     if (CA_STATUS_OK != CAsetTlsCipherSuite(enable ? 0xFF00 : 0xC037))
@@ -583,32 +492,23 @@ CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t* endpoint,
                     const uint8_t* label, const size_t labelLen,
                     const uint8_t* rsrcServerDeviceID, const size_t rsrcServerDeviceIDLen,
                     const uint8_t* provServerDeviceID, const size_t provServerDeviceIDLen,
-                    uint8_t* ownerPSK, const size_t ownerPSKSize)
+                    uint8_t* ownerPSK, const size_t ownerPskSize)
 {
     OIC_LOG_V(DEBUG, TAG, "IN : CAGenerateOwnerPSK");
 
     CAResult_t res = CA_STATUS_OK;
 
     //newOwnerLabel and prevOwnerLabe can be NULL
-    if (!endpoint || !label || 0 == labelLen || !ownerPSK || 0 == ownerPSKSize)
+    if (!endpoint || !label || 0 == labelLen || !ownerPSK || 0 == ownerPskSize)
     {
         return CA_STATUS_INVALID_PARAM;
     }
 
-    if(CA_ADAPTER_IP == endpoint->adapter)
-    {
-        res = CADtlsGenerateOwnerPSK(endpoint, label, labelLen,
+    res = CAsslGenerateOwnerPsk(endpoint, label, labelLen,
                                       rsrcServerDeviceID, rsrcServerDeviceIDLen,
                                       provServerDeviceID, provServerDeviceIDLen,
-                                      ownerPSK, ownerPSKSize);
-    }
-#ifdef __WITH_TLS__
-    else
-    {
-        res = CAtlsGenerateOwnerPSK(endpoint, ownerPSK, ownerPSKSize,
-                rsrcServerDeviceID, rsrcServerDeviceIDLen);
-    }
-#endif
+                                      ownerPSK, ownerPskSize);
+
     if (CA_STATUS_OK != res)
     {
         OIC_LOG_V(ERROR, TAG, "Failed to CAGenerateOwnerPSK : %d", res);
@@ -629,10 +529,10 @@ CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint)
         return CA_STATUS_INVALID_PARAM;
     }
 
-    res = CADtlsInitiateHandshake(endpoint);
+    res = CAinitiateSslHandshake(endpoint);
     if (CA_STATUS_OK != res)
     {
-        OIC_LOG_V(ERROR, TAG, "Failed to CADtlsInitiateHandshake : %d", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to CAinitiateSslHandshake : %d", res);
     }
 
     OIC_LOG_V(DEBUG, TAG, "OUT : CAInitiateHandshake");
@@ -640,9 +540,9 @@ CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint)
     return res;
 }
 
-CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint)
+CAResult_t CAcloseSslSession(const CAEndpoint_t *endpoint)
 {
-    OIC_LOG_V(DEBUG, TAG, "IN : CACloseDtlsSession");
+    OIC_LOG_V(DEBUG, TAG, "IN : CAcloseSslSession");
     CAResult_t res = CA_STATUS_OK;
 
     if (!endpoint)
@@ -650,13 +550,13 @@ CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint)
         return CA_STATUS_INVALID_PARAM;
     }
 
-    res = CADtlsClose(endpoint);
+    res = CAcloseSslConnection(endpoint);
     if (CA_STATUS_OK != res)
     {
-        OIC_LOG_V(ERROR, TAG, "Failed to CADtlsClose : %d", res);
+        OIC_LOG_V(ERROR, TAG, "Failed to CAsslClose : %d", res);
     }
 
-    OIC_LOG_V(DEBUG, TAG, "OUT : CACloseDtlsSession");
+    OIC_LOG_V(DEBUG, TAG, "OUT : CAcloseSslSession");
 
     return res;
 }
index 381b67c..42fe1a6 100644 (file)
@@ -29,7 +29,7 @@
 #include "caqueueingthread.h"
 #include "caadapterutils.h"
 #ifdef __WITH_DTLS__
-#include "caadapternetdtls.h"
+#include "ca_adapter_net_ssl.h"
 #endif
 #include "octhread.h"
 #include "uarraylist.h"
@@ -244,9 +244,14 @@ CAResult_t CAInitializeIP(CARegisterConnectivityCallback registerCallback,
     CAIPSetPacketReceiveCallback(CAIPPacketReceivedCB);
 
 #ifdef __WITH_DTLS__
-    CAAdapterNetDtlsInit();
-
-    CADTLSSetAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, 0);
+    if (CA_STATUS_OK != CAinitSslAdapter())
+    {
+        OIC_LOG(ERROR, TAG, "Failed to init SSL adapter");
+    }
+    else
+    {
+        CAsetSslAdapterCallbacks(CAIPPacketReceivedCB, CAIPPacketSendCB, CA_ADAPTER_IP);
+    }
 #endif
 
     static const CAConnectivityHandler_t ipHandler =
@@ -401,7 +406,7 @@ CAResult_t CAReadIPData()
 CAResult_t CAStopIP()
 {
 #ifdef __WITH_DTLS__
-    CAAdapterNetDtlsDeInit();
+    CAdeinitSslAdapter();
 #endif
 
 #ifndef SINGLE_THREAD
@@ -422,7 +427,7 @@ CAResult_t CAStopIP()
 void CATerminateIP()
 {
 #ifdef __WITH_DTLS__
-    CADTLSSetAdapterCallbacks(NULL, NULL, 0);
+    CAsetSslAdapterCallbacks(NULL, NULL, CA_ADAPTER_IP);
 #endif
 
     CAIPSetPacketReceiveCallback(NULL);
@@ -456,15 +461,13 @@ void CAIPSendDataThread(void *threadData)
 #ifdef __WITH_DTLS__
         if (ipData->remoteEndpoint && ipData->remoteEndpoint->flags & CA_SECURE)
         {
-            OIC_LOG(DEBUG, TAG, "CAAdapterNetDtlsEncrypt called!");
-            CAResult_t result = CAAdapterNetDtlsEncrypt(ipData->remoteEndpoint,
-                                               ipData->data, ipData->dataLen);
+            OIC_LOG(DEBUG, TAG, "DTLS encrypt called");
+            CAResult_t result = CAencryptSsl(ipData->remoteEndpoint, ipData->data, ipData->dataLen);
             if (CA_STATUS_OK != result)
             {
-                OIC_LOG(ERROR, TAG, "CAAdapterNetDtlsEncrypt failed!");
+                OIC_LOG(ERROR, TAG, "CAencryptSsl failed!");
             }
-            OIC_LOG_V(DEBUG, TAG,
-                      "CAAdapterNetDtlsEncrypt returned with result[%d]", result);
+            OIC_LOG_V(DEBUG, TAG, "CAencryptSsl returned with result[%d]", result);
         }
         else
         {
index 281a618..1e2a1f9 100644 (file)
@@ -61,8 +61,8 @@
 #include "caipinterface.h"
 #include "caipnwmonitor.h"
 #include "caadapterutils.h"
-#ifdef __WITH_DTLS__
-#include "caadapternetdtls.h"
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
+#include "ca_adapter_net_ssl.h"
 #endif
 #include "octhread.h"
 #include "oic_malloc.h"
@@ -623,8 +623,8 @@ static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
     if (flags & CA_SECURE)
     {
 #ifdef __WITH_DTLS__
-        int ret = CAAdapterNetDtlsDecrypt(&sep, (uint8_t *)recvBuffer, recvLen);
-        OIC_LOG_V(DEBUG, TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
+        int ret = CAdecryptSsl(&sep, (uint8_t *)recvBuffer, recvLen);
+        OIC_LOG_V(DEBUG, TAG, "CAdecryptSsl returns [%d]", ret);
 #else
         OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
 #endif
index 082bd19..0be6df6 100644 (file)
@@ -40,7 +40,7 @@
 #include "logger.h"
 #include "oic_malloc.h"
 #ifdef __WITH_TLS__
-#include "ca_adapter_net_tls.h"
+#include "ca_adapter_net_ssl.h"
 #endif
 
 /**
@@ -293,8 +293,14 @@ CAResult_t CAInitializeTCP(CARegisterConnectivityCallback registerCallback,
     CATCPSetErrorHandler(CATCPErrorHandler);
 
 #ifdef __WITH_TLS__
-    CAinitTlsAdapter();
-    CAsetTlsAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, 0);
+    if (CA_STATUS_OK != CAinitSslAdapter())
+    {
+        OIC_LOG(ERROR, TAG, "Failed to init SSL adapter");
+    }
+    else
+    {
+        CAsetSslAdapterCallbacks(CATCPPacketReceivedCB, CATCPPacketSendCB, CA_ADAPTER_TCP);
+    }
 #endif
 
     CAConnectivityHandler_t tcpHandler = {
@@ -470,7 +476,7 @@ CAResult_t CAStopTCP()
     CAInitializeTCPGlobals();
 
 #ifdef __WITH_TLS__
-    CAdeinitTlsAdapter();
+    CAdeinitSslAdapter();
 #endif
 
     return CA_STATUS_OK;
@@ -503,8 +509,8 @@ void CATCPSendDataThread(void *threadData)
          if (tcpData->remoteEndpoint && tcpData->remoteEndpoint->flags & CA_SECURE)
          {
              CAResult_t result = CA_STATUS_OK;
-             OIC_LOG(DEBUG, TAG, "CAencryptTls called!");
-             result = CAencryptTls(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
+             OIC_LOG(DEBUG, TAG, "CAencryptSsl called!");
+             result = CAencryptSsl(tcpData->remoteEndpoint, tcpData->data, tcpData->dataLen);
 
              if (CA_STATUS_OK != result)
              {
index dfdf6a7..4cdcf9f 100644 (file)
@@ -46,7 +46,7 @@
 #include "oic_string.h"
 
 #ifdef __WITH_TLS__
-#include "ca_adapter_net_tls.h"
+#include "ca_adapter_net_ssl.h"
 #endif
 
 /**
@@ -550,9 +550,9 @@ static void CAExecuteRequest(CATCPSessionInfo_t *svritem)
         case TLS:
 #ifdef __WITH_TLS__
         {
-            int ret = CAdecryptTls(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
+            int ret = CAdecryptSsl(&svritem->sep, (uint8_t *)svritem->data, svritem->len);
 
-            OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptTls returned %d", __func__, ret);
+            OIC_LOG_V(DEBUG, TAG, "%s: CAdecryptSsl returned %d", __func__, ret);
         }
         break;
 #endif
@@ -1204,7 +1204,10 @@ CAResult_t CADisconnectTCPSession(CATCPSessionInfo_t *svritem, size_t index)
     oc_mutex_lock(g_mutexObjectList);
 
 #ifdef __WITH_TLS__
-    CAcloseTlsConnection(&svritem->sep.endpoint);
+    if (CA_STATUS_OK != CAcloseSslConnection(&svritem->sep.endpoint))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to close TLS session");
+    }
 #endif
 
     // close the socket and remove TCP connection info in list
@@ -1240,7 +1243,7 @@ void CATCPDisconnectAll()
         if (svritem && svritem->fd >= 0)
         {
 #ifdef __WITH_TLS__
-            CAcloseTlsConnection(&svritem->sep.endpoint);
+            CAcloseSslConnection(&svritem->sep.endpoint);
 #endif
             shutdown(svritem->fd, SHUT_RDWR);
             close(svritem->fd);
index e0d4376..4baa1e8 100644 (file)
@@ -46,10 +46,7 @@ if target_os not in ['arduino', 'darwin', 'ios', 'msys_nt', 'windows']:
        catest_env.AppendUnique(LIBS=['rt'])
 
 if catest_env.get('SECURED') == '1':
-       catest_env.AppendUnique(LIBS = ['tinydtls'])
-       catest_env.AppendUnique(LIBS = ['timer'])
-       if catest_env.get('WITH_TCP') == True:
-               catest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto'])
+       catest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto'])
 
 if catest_env.get('WITH_RD') == '1':
        catest_env.PrependUnique(LIBS = ['resource_directory'])
index f773e9c..c2e5fff 100644 (file)
@@ -525,7 +525,7 @@ TEST_F (CATests, GetNetworkInformationTest)
 TEST_F(CATests, RegisterDTLSCredentialsHandlerTest)
 {
 #ifdef __WITH_DTLS__
-    EXPECT_EQ(CA_STATUS_OK, CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials));
+    EXPECT_EQ(CA_STATUS_OK, CAregisterPskCredentialsHandler(CAGetDtlsPskCredentials));
 #endif
 }
 
index c3d3e5f..0e98a20 100644 (file)
@@ -42,7 +42,7 @@ rd_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
 rd_sample_app_env.PrependUnique(LIBS = ['resource_directory', 'oc', 'octbstack'])
 
 if env.get('SECURED') == '1':
-    rd_sample_app_env.AppendUnique(LIBS = ['tinydtls'])
+    rd_sample_app_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto'])
 
 if env.get('LOGGING'):
     rd_sample_app_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
index ca5714a..a1e5f11 100644 (file)
@@ -57,7 +57,6 @@ libocsrm_env.PrependUnique(CPPPATH = [
                '../../oc_logger/include',
                '../connectivity/external/inc',
                '../connectivity/common/inc',
-               '../connectivity/inc/pkix',
                '../connectivity/inc',
                '../connectivity/api',
                '../security/include',
@@ -89,9 +88,6 @@ if target_os in ['darwin', 'ios']:
 if env.get('LOGGING'):
        libocsrm_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
 
-if env.get('DTLS_WITH_X509') == '1':
-       libocsrm_env.AppendUnique(CPPDEFINES = ['__WITH_X509__'])
-
 ######################################################################
 # Source files and Targets
 ######################################################################
@@ -120,12 +116,11 @@ libocsrm_src = [
 
 if libocsrm_env.get('SECURED') == '1':
        libocsrm_src = libocsrm_src + [OCSRM_SRC + 'oxmpincommon.c', OCSRM_SRC + 'pbkdf2.c']
+       libocsrm_src  = libocsrm_src + [OCSRM_SRC + 'crlresource.c', OCSRM_SRC + 'pkix_interface.c']
 
 if target_os in ['windows', 'msys_nt']:
        libocsrm_src  = libocsrm_src + [OCSRM_SRC + 'strptime.c']
 
-if (env.get('DTLS_WITH_X509') == '1' or env.get('WITH_TCP') == True) and env.get('SECURED') == '1':
-       libocsrm_src  = libocsrm_src + [OCSRM_SRC + 'crlresource.c', OCSRM_SRC + 'pkix_interface.c']
 
 libocsrm_src.extend(env['cbor_files'])
 
index 00708b1..0ba8041 100644 (file)
@@ -124,7 +124,7 @@ OCStackResult RemoveCredential(const OicUuid_t *subject);
  */
 OCStackResult RemoveCredentialByCredId(uint16_t credId);
 
-#if defined(__WITH_DTLS__)
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 /**
  * This internal callback is used by lower stack (i.e. CA layer) to
  * retrieve PSK credentials from RI security layer.
@@ -159,18 +159,7 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
                             const OicUuid_t * rownerID,
                             OicUuid_t* tmpCredSubject);
 
-#endif /* __WITH_DTLS__ */
-
-#ifdef __WITH_X509__
-/**
- * This function is used toretrieve certificate credentials from RI security layer.
- *
- * @param credInfo is the binary structure containing certificate credentials
- *
- * @return 0 on success.
- */
-int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo);
-#endif /*__WITH_X509__*/
+#endif // __WITH_DTLS__ or __WITH_TLS__
 
 /**
  * Function to getting credential list
@@ -204,25 +193,25 @@ OCStackResult SetCredRownerId(const OicUuid_t* newROwner);
  */
 OCStackResult GetCredRownerId(OicUuid_t *rowneruuid);
 
-#ifdef __WITH_TLS__
+#if defined(__WITH_TLS__) || defined(__WITH_DTLS__)
 /**
  * Used by mbedTLS to retrieve trusted CA certificates
  *
  * @param[out] crt certificates to be filled.
  */
-void GetDerCaCert(ByteArray * crt);
+void GetDerCaCert(ByteArray_t * crt);
 /**
  * Used by mbedTLS to retrieve own certificate chain
  *
  * @param[out] crt certificate chain to be filled.
  */
-void GetDerOwnCert(ByteArray * crt);
+void GetDerOwnCert(ByteArray_t * crt);
 /**
  * Used by mbedTLS to retrieve owm private key
  *
  * @param[out] key key to be filled.
  */
-void GetDerKey(ByteArray * key);
+void GetDerKey(ByteArray_t * key);
 /**
  * Used by CA to retrieve credential types
  *
index 28ba5b1..97eb65e 100644 (file)
@@ -50,7 +50,7 @@ uint8_t* GetCrl();
  *
  * @return encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set).
  */
-void  GetDerCrl(ByteArray* crlArray);
+void  GetDerCrl(ByteArray_t* crlArray);
 
 /**
  * This function converts CRL to CBOR
index c69c5e6..ee158b4 100644 (file)
@@ -76,7 +76,7 @@ OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **pay
  */\r
 void DeleteDpairingBinData(OicSecDpairing_t* dpair);\r
 \r
-#ifdef __WITH_DTLS__\r
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)\r
 /**\r
  * Function to save PairingPSK.\r
  *\r
@@ -88,7 +88,7 @@ void DeleteDpairingBinData(OicSecDpairing_t* dpair);
  */\r
 OCStackResult SavePairingPSK(OCDevAddr *endpoint,\r
             OicUuid_t *peerDevID, OicUuid_t *owner, bool isPairingServer);\r
-#endif // __WITH_DTLS__\r
+#endif // __WITH_DTLS__ or __WITH_TLS__\r
 \r
 /**\r
  * Gets the OicUuid_t value for the rownerid of the Dpairing resource.\r
index 2101381..de17cad 100644 (file)
@@ -45,9 +45,9 @@
 
 #include <stdint.h> // for uint8_t typedef
 #include <stdbool.h>
-#if defined(__WITH_X509__) || defined(__WITH_TLS__)
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 #include "byte_array.h"
-#endif /* __WITH_X509__  or __WITH_TLS__*/
+#endif /* __WITH_DTLS__  or __WITH_TLS__*/
 
 #ifdef __cplusplus
 extern "C" {
@@ -293,12 +293,12 @@ typedef char *OicUrn_t; //TODO is URN type defined elsewhere?
 typedef struct OicUuid OicUuid_t; //TODO is UUID type defined elsewhere?
 
 
-#if defined(__WITH_X509__) || defined(__WITH_TLS__)
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
 typedef struct OicSecCrl OicSecCrl_t;
-typedef ByteArray OicSecCert_t;
+typedef ByteArray_t OicSecCert_t;
 #else
 typedef void OicSecCert_t;
-#endif /* __WITH_X509__ or __WITH_TLS__*/
+#endif /* __WITH_DTLS__ or __WITH_TLS__*/
 
 /**
  * /oic/uuid (Universal Unique Identifier) data type.
@@ -400,11 +400,11 @@ struct OicSecCred
     //size_t              roleIdsLen;     // the number of elts in RoleIds
     //OicSecRole_t        *roleIds;       // 2:R:M:N:oic.sec.role
     OicSecCredType_t    credType;       // 3:R:S:Y:oic.sec.credtype
-#if defined(__WITH_X509__) || defined(__WITH_TLS__)
+#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
     OicSecCert_t        publicData;     // own cerificate chain
     char            *credUsage;            // 4:R:S:N:String
     OicSecKey_t        optionalData;   // CA's cerificate chain
-#endif /* __WITH_X509__  or __WITH_TLS__*/
+#endif /* __WITH_DTLS__  or __WITH_TLS__*/
     OicSecKey_t         privateData;    // 6:R:S:N:oic.sec.key
     char                *period;        // 7:R:S:N:String
     OicUuid_t           rownerID;        // 8:R:S:Y:oic.uuid
@@ -490,14 +490,14 @@ struct OicSecSvc
     OicSecSvc_t             *next;
 };
 
-#if defined(__WITH_X509__) ||  defined(__WITH_TLS__)
+#if defined(__WITH_DTLS__) ||  defined(__WITH_TLS__)
 struct OicSecCrl
 {
     uint16_t CrlId;
-    ByteArray ThisUpdate;
+    ByteArray_t ThisUpdate;
     OicSecKey_t CrlData;
 };
-#endif /* __WITH_X509__ or __WITH_TLS__ */
+#endif /* __WITH_DTLS__ or __WITH_TLS__ */
 
 /**
  * @brief   direct pairing data type
index e1739ec..4ef5a44 100644 (file)
@@ -70,21 +70,14 @@ if 'g++' in provisioning_env.get('CXX'):
 provisioning_env.AppendUnique(LIBPATH = [provisioning_env.get('BUILD_DIR')])
 provisioning_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap', 'ocsrm'])
 
-provisioning_env.AppendUnique(LIBS = ['tinydtls'])
+provisioning_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto'])
 
-if provisioning_env.get('WITH_TCP') == True:
-       provisioning_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto'])
-
-if provisioning_env.get('DTLS_WITH_X509') == '1':
-       provisioning_env.AppendUnique(LIBS = ['CKManager', 'asn1'])
-if provisioning_env.get('WITH_TCP') == True:
-       provisioning_env.AppendUnique(LIBS = ['mbedtls'])
 
 if target_os not in ['msys_nt', 'windows', 'android']:
        provisioning_env.ParseConfig('pkg-config --libs glib-2.0')
 
 if target_os in ['windows', 'msys_nt']:
-       provisioning_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi', 'timer'])
+       provisioning_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'iphlpapi'])
 
 if target_os in ['android']:
        provisioning_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
@@ -110,6 +103,7 @@ provisioning_src = [
        'src/provisioningdatabasemanager.c' ]
 
 if provisioning_env.get('WITH_TCP') == True:
+       provisioning_env.AppendUnique(CPPDEFINES= ['__WITH_TLS__'])
        provisioning_src = provisioning_src + [
        'src/cloud/utils.c',
        'src/cloud/crl.c',
@@ -135,9 +129,6 @@ else:
 provisioning_env.InstallTarget(provisioningserver, 'ocpmapi')
 provisioning_env.UserInstallTargetLib(provisioningserver, 'ocpmapi')
 
-if provisioning_env.get('DTLS_WITH_X509') == '1':
-       SConscript('ck_manager/SConscript')
-
 if target_os in ['linux', 'msys_nt', 'windows', 'tizen']:
        SConscript('sample/SConscript')
 
diff --git a/resource/csdk/security/provisioning/ck_manager/SConscript b/resource/csdk/security/provisioning/ck_manager/SConscript
deleted file mode 100644 (file)
index a473e5e..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-# SConscript file for Local PKI project
-
-Import('env')
-
-x509_env = env.Clone()
-
-EXTLIBS_DIR = "/extlibs/"
-
-# Includes
-INCLUDE_DIRS = []
-
-src_dir = x509_env.get('SRC_DIR')
-
-SConscript(src_dir + '/extlibs/asn1cert/SConscript')
-
-#Internal sources
-INCLUDE_DIRS.append(src_dir +'/resource/csdk/security/provisioning/ck_manager/include/');
-INCLUDE_DIRS.append(src_dir + '/resource/csdk/connectivity/inc/pkix/');
-
-#External sources
-INCLUDE_DIRS.append(src_dir + '/extlibs/tinydtls/ecc/');
-INCLUDE_DIRS.append(src_dir + '/extlibs/tinydtls/sha2/');
-INCLUDE_DIRS.append(src_dir + '/extlibs/asn1cert/');
-INCLUDE_DIRS.append(src_dir + '/extlibs/cjson/');
-
-#OIC incude
-INCLUDE_DIRS.append(src_dir + '/resource/csdk/security/include/');
-INCLUDE_DIRS.append(src_dir + '/resource/csdk/security/include/internal/');
-INCLUDE_DIRS.append(src_dir + '/resource/csdk/stack/include/');
-
-DEFINES = ['WITH_SHA256', 'uECC_CURVE=uECC_secp256r1', 'X509_DEBUG']
-
-x509_env.AppendUnique(CPPPATH = INCLUDE_DIRS)
-x509_env.AppendUnique(CPPDEFINES = DEFINES)
-
-#Encoder/Decoder source code
-ckmanager_src = Glob('src/*.c')
-
-#Build static libraries
-ckmStaticLib = x509_env.StaticLibrary('CKManager', ckmanager_src)
-
-x509_env.InstallTarget(ckmStaticLib, 'libCKManager')
-
-#x509_env.AppendUnique(LIBS = ['ocsrm'])
-x509_env.AppendUnique(LIBS = ['asn1'])
-x509_env.AppendUnique(LIBS = ['Base64'])
-x509_env.AppendUnique(LIBS = ['Json'])
-
-SConscript('sample/SConscript')
-SConscript('unittest/SConscript')
diff --git a/resource/csdk/security/provisioning/ck_manager/include/cert_generator.h b/resource/csdk/security/provisioning/ck_manager/include/cert_generator.h
deleted file mode 100644 (file)
index a21980f..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef INCLUDE_ISSUER_ISSUER_H_
-#define INCLUDE_ISSUER_ISSUER_H_
-
-#include "Certificate.h" // Certificate ASN.1 type
-#include "pki.h"
-#include "pki_errors.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define X509_V1 0
-#define X509_V2 1
-#define X509_V3 2
-
-/**
- * Encodes X.509 certificate with specified parameters.
- *
- * @param[in] subjectName pointer to serial subject's common name
- * @param[in] issuerName pointer to issuer's common name
- * @param[in] notBefore pointer to certificate validity limit
- * @param[in] notAfter pointer to certificate validity limit
- * @param[in] subjectPublicKey pointer to subject's public key to be signed
- * @param[in] issuerPrivateKey pointer to issuer's private key to sign certificate
- * @param[out] encodedCertificate pointer to allocated memory for DER encoded certificate
- *          (ISSUER_MAX_CERT_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateCertificate (const UTF8String_t *subjectName, const UTF8String_t *issuerName,
-                        const UTCTime_t *notBefore, const UTCTime_t *notAfter,
-                        const BIT_STRING_t *subjectPublicKey, const BIT_STRING_t *issuerPrivateKey,
-                        ByteArray *encodedCertificate);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* INCLUDE_ISSUER_ISSUER_H_ */
diff --git a/resource/csdk/security/provisioning/ck_manager/include/ck_manager.h b/resource/csdk/security/provisioning/ck_manager/include/ck_manager.h
deleted file mode 100644 (file)
index 19b5081..0000000
+++ /dev/null
@@ -1,208 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#ifndef INCLUDE_MASTER_ISSUER_H_
-#define INCLUDE_MASTER_ISSUER_H_
-
-#include "byte_array.h"
-#include "cert_generator.h"
-#include "ckm_info.h"
-#include "csr_generator.h"
-#include "ecc.h"
-#include "crl_generator.h"
-#include "pki_errors.h"
-#include <stdio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define ISSUER_DEFAULT_CA_NAME          "CA_name"
-#define ISSUER_DEFAULT_SUBJECT_NAME     "Subj_name"
-#define ISSUER_DEFAULT_NOT_BEFORE       "130101000000Z"
-#define ISSUER_DEFAULT_NOT_AFTER        "490101000000Z"
-#define ISSUER_DEFAULT_THIS_UPDATE      "150601000000Z"
-
-/**
- * Set serial number for next certificate and save it in the CA storage.
- *
- * Used by CKMSetCAInfo()
- *
- * @param[in] serNum certificate serial number to be set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetSerialNumber (const long serNum);
-
-/**
- * Set CA common name and save it in the CA storage.
- *
- * Used by CKMSetCAInfo()
- *
- * @param[in] rootName CA common name to be set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetRootName (const ByteArray rootName);
-
-/**
- * Set CA info and save it in the CA storage.
- *
- * Should be called before certificate generation
- *
- * @param[in] serNum certificate serial number to be set
- * @param[in] rootName CA common name to be set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CKMSetCAInfo (const long serNum, const ByteArray rootName);
-
-/**
- * Generate key pair for CA.
- *
- * Should be called before certificate generation
- *
- * @param[out] caPrivateKey pointer to allocated ByteArray for CA private key
- * @param[out] caPublicKey pointer to allocated ByteArray for CA public key
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateCAKeyPair (ByteArray *caPrivateKey, ByteArray *caPublicKey);
-
-/**
- * Issues X.509 certificate with specified parameters.
- *
- * SetSerialNumber, SetRootName and GenerateCAKeyPair should be called before.
- *
- * @param[in] uint8NotBefore pointer to string with certificate validity limit
- *                             or 0 to use default value
- * @param[in] uint8NotAfter pointer to string with certificate validity limit
- *                            or 0 to use default value
- * @param[out] issuedCertificate pointer to allocated memory for DER encoded certificate
- *          (ISSUER_MAX_CERT_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CKMIssueRootCertificate (const uint8_t *uint8NotBefore, const uint8_t *uint8NotAfter,
-                                     ByteArray *issuedRootCertificate);
-
-/**
- * Generate key pair for ordinary device.
- *
- * @param[out] privateKey pointer to allocated ByteArray for private key
- * @param[out] publicKey pointer to allocated ByteArray for public key
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateKeyPair (ByteArray *privateKey, ByteArray *publicKey);
-
-/**
- * Issues X.509 certificate with specified parameters.
- *
- * SetSerialNumber, SetRootName and GenerateCAKeyPair should be called before.
- *
- * @param[in] uint8SubjectName pointer to string with serial subject's common name
- *                               or 0 to use default value
- * @param[in] uint8NotBefore pointer to string with certificate validity limit
- *                             or 0 to use default value
- * @param[in] uint8NotAfter pointer to string with certificate validity limit
- *                            or 0 to use default value
- * @param[in] uint8SubjectPublicKey pointer to array with subject's public key to be signed
- * @param[out] issuedCertificate pointer to allocated memory for DER encoded certificate
- *          (ISSUER_MAX_CERT_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CKMIssueDeviceCertificate (const uint8_t *uint8SubjectName,
-                                    const uint8_t *uint8NotBefore, const uint8_t *uint8NotAfter,
-                                    const uint8_t *uint8SubjectPublicKey,
-                                    ByteArray *issuedCertificate);
-
-/**
- * Write certificate into specified file.
- *
- * @param[in] certificate pointer to DER-encoded certificate that should be written into the file
- * @param[in] certFileName pointer to null-terminated string with file name
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char * const certFileName);
-
-/**
- * Issues certificate signing request with specified parameters.
- *
- * @param[in] uint8SubjectName pointer to string with serial subject's common name
- *                               or 0 to use default value
- * @param[in] uint8SubjectPublicKey pointer to array with subject's public key to be signed
- * @param[in] uint8SubjectPrivateKey pointer to array with subject's private key to be signed
- * @param[out] encodedCSR pointer to allocated memory for DER encoded certificate signing request
- *          (CSR_MAX_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateCSR (const uint8_t *uint8SubjectName,
-                         const uint8_t *uint8SubjectPublicKey,
-                         const uint8_t *uint8SubjectPrivateKey,
-                         ByteArray *encodedCSR);
-
-/**
- * Issues X.509 certificate based on certificate signing request.
- *
- * @param[in] encodedCSR pointer to array with DER encoded certificate signing request
- * @param[out] issuedCertificate pointer to allocated memory for DER encoded certificate
- *          (MAX_CERT_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateCertificateByCSR (const ByteArray *encodedCSR, ByteArray *issuedCertificate);
-
-/**
- * Generate certificate revocation list with specified parameters.
- *
- * @param[in] thisUpdateTime pointer to time of issuing CRL or 0 to use default
- * @param[in] nuberOfRevoked number of revoked certificates
- * @param[in] revokedNumbers array with numbers of revoked certificates
- * @param[in] revocationDates
- * @param[out] encodedCRL pointer to allocated memory for DER encoded certificate revocation list
- *          ( (CRL_MIN_SIZE + nuberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)) bytes
- *          should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CKMIssueCRL (const uint8_t *uint8ThisUpdateTime, const uint32_t nuberOfRevoked,
-                      const uint32_t *revokedNumbers, const uint8_t **revocationDates,
-                      ByteArray *encodedCRL);
-
-/**
- * Gets current certificate revocation list.
- *
- * @param[out] certificateRevocationList pointer to the certificate revocation list to get
- *            (Memory should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CKMGetCRL (ByteArray *certificateRevocationList);
-
-/**
- * Add specified certificate into certificate revocation list.
- *
- * @param[in] thisUpdateTime pointer to time of issuing CRL or 0 to use default
- * @param[in] revokedNumber number of certificate to revoke
- * @param[out] encodedCRL pointer to allocated memory for DER encoded certificate revocation list
- *          ( (CRL_MIN_SIZE + number of ALL revoked certificates *
- *           (sizeof(CertificateRevocationInfo_t) + 4)) bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CKMRevocateCertificate (const uint8_t *uint8ThisUpdateTime, const long revokedNumber,
-                                 ByteArray *encodedCRL);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* INCLUDE_MASTER_ISSUER_H_ */
diff --git a/resource/csdk/security/provisioning/ck_manager/include/ckm_info.h b/resource/csdk/security/provisioning/ck_manager/include/ckm_info.h
deleted file mode 100644 (file)
index d45be77..0000000
+++ /dev/null
@@ -1,322 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef INCLUDE_CA_STORAGE_H_
-#define INCLUDE_CA_STORAGE_H_
-
-#include "byte_array.h"
-#include <stdio.h>
-#include "pki_errors.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define CA_STORAGE_FILE         "ckminfo.dat"
-#define CA_STORAGE_CRT_FILE     "crt.der"
-#define ISSUER_MAX_NAME_SIZE    (100)
-#define PRIVATE_KEY_SIZE        (32)
-#define PUBLIC_KEY_SIZE         (64)
-#define ISSUER_MAX_CERT_SIZE    (1000)
-/**
- *  Certificate Authority storage
- */
-typedef struct /*CA private key, CA certificate, other CA-related info*/
-{
-    uint8_t     CKMInfoIsLoaded;
-
-    uint8_t     CAPrivateKeyIsSet;
-    uint8_t     CAPrivateKey[PRIVATE_KEY_SIZE];
-
-    uint8_t     CAPublicKeyIsSet;
-    uint8_t     CAPublicKey[PUBLIC_KEY_SIZE];
-
-    uint8_t     CAChainLength;
-
-    ByteArray  *CACertificateChain;
-
-    uint32_t    CANameSize;
-    uint8_t     CAName[ISSUER_MAX_NAME_SIZE];
-
-    long        nextSerialNumber;
-
-    long        CRLSerialNumber;
-
-    long        numberOfRevoked;
-} CKMInfo_t;
-
-//General functions
-
-/**
- * Initializes CA storage from CA_STORAGE_FILE.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError InitCKMInfo(void);
-
-/**
- * Saves CA storage into CA_STORAGE_FILE.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SaveCKMInfo(void);
-
-/**
- * Frees CA storage memory.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError CloseCKMInfo(void);
-
-/**
- * Sets CKM Info.
- *
- * @param[in] nextSN next serial number to set
- *                   or 0 to skip this parameter
- * @param[in] CRLSerialNumber next CRL serial number to set
- *                   or 0 to skip this parameter
- * @param[in] CAPrivateKey pointer to the CA's private key to set
- *                   or 0 to skip this parameter
- * @param[in] CAPublicKey pointer to the CA's public key to set
- *                   or 0 to skip this parameter
- * @param[in] CAName pointer to the CA's common name to set
- *                   or 0 to skip this parameter
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCKMInfo (long nextSN, long CRLSerialNumber,
-                     const ByteArray *CAPrivateKey, const ByteArray *CAPublicKey,
-                     const ByteArray *CAName);
-
-/**
- * Gets CKM Info.
- *
- * @param[out] nextSN pointer to the next serial number to get
- *                   (Memory should be allocated before call)
- *                   or 0 to skip this parameter
- * @param[out] CRLSerialNumber pointer to the next CRL serial number to get
- *                   (Memory should be allocated before call)
- *                   or 0 to skip this parameter
- * @param[out] CAPrivateKey pointer to the CA's private key to get
- *                   (PRIVATE_KEY_SIZE bytes should be allocated before call)
- *                   or 0 to skip this parameter
- * @param[out] CAPublicKey pointer to the CA's public key to get
- *                   (PUBLIC_KEY_SIZE bytes should be allocated before call)
- *                   or 0 to skip this parameter
- * @param[out] CAName pointer to the CA's common name to get
- *                   (ISSUER_MAX_NAME_SIZE bytes should be allocated before call)
- *                   or 0 to skip this parameter
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCKMInfo (long *nextSN, long *CRLSerialNumber,
-                     ByteArray *CAPrivateKey, ByteArray *CAPublicKey,
-                     ByteArray *CAName);
-
-/**
- * Sets CA's private key.
- *
- * @param[in] CAPrivateKey pointer to the CA's private key to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCAPrivateKey (const ByteArray *CAPrivateKey);
-
-/**
- * Gets CA's private key.
- *
- * @param[out] CAPrivateKey pointer to the CA's private key to get
- *             (PRIVATE_KEY_SIZE bytes should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCAPrivateKey (ByteArray *CAPrivateKey);
-
-/**
- * Sets CA's public key.
- *
- * @param[in] CAPublicKey pointer to the CA's public key to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCAPublicKey (const ByteArray *CAPublicKey);
-
-/**
- * Gets CA's public key.
- *
- * @param[out] CAPublicKey pointer to the CA's public key to get
- *            (PUBLIC_KEY_SIZE bytes should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCAPublicKey (ByteArray *CAPublicKey);
-
-/**
- * Sets CA's common name.
- *
- * @param[in] CAName pointer to the CA's common name to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCAName (const ByteArray *CAName);
-
-/**
- * Gets CA's common name.
- *
- * @param[out] CAName pointer to the CA's common name to get
- *            (ISSUER_MAX_NAME_SIZE bytes should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCAName (ByteArray *CAName);
-
-//Certificate-related functions
-
-/**
- * Initializes CA Certificate from CA_STORAGE_CRT_FILE.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError InitCRT(void);
-
-/**
- * Saves CA Certificate into CA_STORAGE_CRT_FILE.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SaveCRT(void);
-
-/**
- * Sets next serial number for certificate issuer.
- *
- * @param[in] nextSN next serial number to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetNextSerialNumber (const long nextSN);
-
-/**
- * Gets next serial number for certificate issuer.
- *
- * @param[out] nextSN pointer to the next serial number to get
- *            (Memory should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetNextSerialNumber (long *nextSN);
-
-/**
- * Sets DER encoded CA's certificate chain.
- *
- * @param[in] CAChain pointer to the CA's certificate to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCAChain (const uint8_t CAChainLength, const ByteArray *CAChain);
-
-/**
- * Gets DER encoded CA's certificate chain.
- *
- * @param[out] CAChain pointer to allocated memory to get the CA's certificate chain
- *            (ISSUER_MAX_CHAIN_SIZE bytes should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCAChain (uint8_t* CAChainLength, ByteArray *CAChain);
-
-/**
- * Sets DER encoded CA's certificate.
- *
- * @param[in] CACertificate pointer to the CA's certificate to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCACertificate (const ByteArray *CACertificate);
-
-/**
- * Gets DER encoded CA's certificate.
- *
- * @param[out] CACertificate pointer to the CA's certificate to get
- *            (ISSUER_MAX_CERT_SIZE bytes should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCACertificate (ByteArray *CACertificate);
-
-//CRL-related functions
-
-/**
- * Initializes CRL from CA_STORAGE_CRL_FILE.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError InitCRL(void);
-
-/**
- * Saves CRL into CA_STORAGE_CRL_FILE.
- *
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SaveCRL(void);
-
-/**
- * Sets next CRL serial number for certificate issuer.
- *
- * @param[in] CRLSerialNumber next CRL serial number to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCRLSerialNumber (const long CRLSerialNumber);
-
-/**
- * Gets next CRL serial number for certificate issuer.
- *
- * @param[out] CRLSerialNumber pointer to the next CRL serial number to get
- *            (Memory should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCRLSerialNumber (long *CRLSerialNumber);
-
-/**
- * Sets current certificate revocation list.
- *
- * @param[in] certificateRevocationList pointer to the certificate revocation list to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetCertificateRevocationList (const ByteArray *certificateRevocationList);
-
-/**
- * Gets current certificate revocation list.
- *
- * @param[out] certificateRevocationList pointer to the certificate revocation list to get
- *            (Memory should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetCertificateRevocationList (ByteArray *certificateRevocationList);
-
-/**
- * Sets number of revoked certificates.
- *
- * @param[in] numberOfRevoked number of revoked certificates to set
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SetNumberOfRevoked (const long numberOfRevoked);
-
-/**
- * Gets number of revoked certificates.
- *
- * @param[out] numberOfRevoked pointer to number of revoked certificates to get
- *            (Memory should be allocated before call)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GetNumberOfRevoked (long *numberOfRevoked);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* INCLUDE_CA_STORAGE_H_ */
diff --git a/resource/csdk/security/provisioning/ck_manager/include/crl_generator.h b/resource/csdk/security/provisioning/ck_manager/include/crl_generator.h
deleted file mode 100644 (file)
index dfdec1c..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef INCLUDE_MASTER_CRL_ENCODER_H_
-#define INCLUDE_MASTER_CRL_ENCODER_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include "CertificateRevocationList.h" /* CertificateList ASN.1 type */
-#include "pki.h"
-#include "pki_errors.h"
-
-// Minimal memory allocated for DER encoded CRL
-#define CRL_MIN_SIZE   250      //minimal size of CRL (issuer info + signature)
-
-#define CRL_MAX_NAME_SIZE 100   //maximal length of CRL issuer field
-
-/**
- * Encode certificate revocation list with specified parameters.
- *
- * @param[in] issuerName pointer to issuer's common name
- * @param[in] thisUpdateTime pointer to time of issuing CRL
- * @param[in] nuberOfRevoked number of revoked certificates
- * @param[in] certificateRevocationInfo array with certificate revocation info
- * @param[in] issuerPrivateKey pointer to issuer's private key to sign CRL
- * @param[out] encodedCRL pointer to allocated memory for DER encoded certificate revocation list
- *          ( (CRL_MIN_SIZE + nuberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)) bytes
- *          should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError GenerateCRL (const UTF8String_t *issuerName,
-                      const UTCTime_t *thisUpdateTime, const uint32_t nuberOfRevoked,
-                      const CertificateRevocationInfo_t *certificateRevocationInfo,
-                      const BIT_STRING_t *issuerPrivateKey, ByteArray *encodedCRL);
-
-/**
- * Sign certificate revocation list.
- *
- * @param[in] certificateRevocationList pointer to CRL for signing
- * @param[in] crlMaxSize max size of DER encoded CRL
- * @param[in] issuerPrivateKey pointer to issuer private key
- * @param[out] encodedCRL pointer to allocated memory for DER encoded certificate revocation list
- *          crlMaxSize bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError SignCRL(CertificateRevocationList_t *certificateRevocationList,
-                 const uint32_t crlMaxSize, const BIT_STRING_t *issuerPrivateKey,
-                 ByteArray *encodedCRL);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* INCLUDE_MASTER_CRL_ENCODER_H_ */
diff --git a/resource/csdk/security/provisioning/ck_manager/include/csr_generator.h b/resource/csdk/security/provisioning/ck_manager/include/csr_generator.h
deleted file mode 100644 (file)
index e1f0870..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      LICENSE-2.0" target="_blank">http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-
- ******************************************************************/
-
-
-#ifndef INCLUDE_MASTER_CSR_H_
-#define INCLUDE_MASTER_CSR_H_
-
-#include "CertificationRequest.h" /* CertificationRequest ASN.1 type */
-#include "pki.h"
-#include "pki_errors.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Memory allocated for DER encoded CSR
-#define CSR_MAX_SIZE   1000
-
-#define CSR_DEFAULT_VERSION 0
-#define CSR_MAX_NAME_SIZE 100
-
-/**
- * Encode certificate signing request with specified parameters.
- *
- * @param[in] subjectName pointer to subject's common name
- * @param[in] subjectPublicKey pointer to subject's public key to be signed
- * @param[in] subjectPrivateKey pointer to subject's private key to be signed
- * @param[out] encodedCSR pointer to allocated memory for DER encoded certificate signing request
- *          (CSR_MAX_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError EncodeCSR (const UTF8String_t *subjectName,
-                    const BIT_STRING_t *subjectPublicKey,
-                    const BIT_STRING_t *subjectPrivateKey,
-                    ByteArray *encodedCSR);
-
-/**
- * Decode certificate signing request, extracts its common name and public key.
- *
- * Return error if signature is not valid.
- *
- * @param[in] encodedCSR  pointer to array with DER encoded certificate signing request
- * @param[out] subjectName pointer to allocated memory for subject's common name extraction
- *          (CSR_MAX_NAME_SIZE bytes should be allocated)
- * @param[out] subjectPublicKey pointer to allocated memory for subject's public key extraction
- *          (PUBLIC_KEY_SIZE bytes should be allocated)
- * @return PKI_SUCCESS if success, error code otherwise
- */
-PKIError DecodeCSR (const ByteArray *encodedCSR,
-                       UTF8String_t *subjectName, BIT_STRING_t *subjectPublicKey);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* INCLUDE_MASTER_CSR_H_ */
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp b/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp
deleted file mode 100644 (file)
index 4f5db19..0000000
+++ /dev/null
@@ -1,580 +0,0 @@
-//******************************************************************
-//
-// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <signal.h>
-#include <pthread.h>
-#include <iostream>
-#include <sstream>
-#include "ocstack.h"
-#include "logger.h"
-#include "cJSON.h"
-#include "global.h"
-#include "cainterface.h"
-#include "cacommon.h"
-#include "payload_logging.h"
-#include "ocpayload.h"
-
-
-#define TAG "DEMO"
-#define DEFAULT_CONTEXT_VALUE 0x99
-#define STATE "state"
-#define OPEN_DURATION "openDuration"
-#define OPEN_DURATION_TIME "10min"
-#define OPEN_ALARM "openAlarm"
-
-static const char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
-
-volatile sig_atomic_t gQuitFlag = 0;
-OCPersistentStorage ps = {0, 0, 0, 0, 0};
-static const char *gResourceUri = "/a/door";
-uint8_t lightIpAddr[4] = {};
-uint16_t lightPortNu;
-static bool isUpdated = false;
-static std::string coapServerIP;
-static std::string coapServerPort;
-static std::string coapServerResource;
-static OCConnectivityType ocConnType;
-
-static std::string address;
-
-static int coapSecureResource;
-
-static const char CRED_FILE[] = "oic_svr_db_door.dat";
-
-CAEndpoint_t endpoint = {CA_DEFAULT_ADAPTER, CA_DEFAULT_FLAGS, 0, {0}, 0};
-
-// myDoorState_t variable to store resource's state .
-typedef enum
-{
-    STATE_OPEN,    /**< State is opened */
-    STATE_CLOSED        /**< State is closed*/
-} myDoorState_t;
-
-//Structure to represent a door resource  and its attributes
-typedef struct DOORRESOURCE
-{
-    OCResourceHandle handle;
-    myDoorState_t state; //ReadOnly, The state of the door (open or closed)"
-    char *openDuration;  //ReadOnly, The time duration the door has been open
-    bool openAlarm ; //The state of the door open alarm
-
-} DoorResource;
-
-static DoorResource Door;
-
-int parseClientResponse(OCClientResponse * clientResponse)
-{
-    if(!clientResponse)
-    {
-        return 0;
-    }
-
-    OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
-
-    // Initialize all global variables
-    coapServerResource.clear();
-    coapSecureResource = 0;
-
-    while (res)
-    {
-        coapServerResource.assign(res->uri);
-        OIC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
-
-        if (res->secure)
-        {
-            endpoint.port = res->port;
-            coapSecureResource = 1;
-        }
-
-        OIC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
-
-        // If we discovered a secure resource, exit from here
-        if (coapSecureResource)
-        {
-            break;
-        }
-
-        res = res->next;
-    }
-
-    return 0;
-}
-
-OCRepPayload* getPayload(const char* uri, int64_t state, char* openDuration, bool openAlarm)
-{
-    OCRepPayload* payload = OCRepPayloadCreate();
-    if (!payload)
-    {
-        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
-        return nullptr;
-    }
-
-    OCRepPayloadSetUri(payload, uri);
-    OCRepPayloadSetPropInt(payload, STATE, state);
-    OCRepPayloadSetPropString(payload, OPEN_DURATION, openDuration);
-    OCRepPayloadSetPropBool(payload, OPEN_ALARM, openAlarm);
-
-    return payload;
-}
-
-//This function takes the request as an input and returns the response
-OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
-{
-    if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
-    {
-        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
-        return nullptr;
-    }
-
-    DoorResource *currdoorResource = &Door;
-
-    return getPayload(gResourceUri, currdoorResource->state, currdoorResource->openDuration, currdoorResource->openAlarm);
-}
-
-OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
-        OCRepPayload **payload)
-{
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-
-    OCRepPayload *getResp = constructResponse(ehRequest);
-
-    if(getResp)
-    {
-        *payload = getResp;
-        ehResult = OC_EH_OK;
-    }
-
-    return ehResult;
-}
-
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest *entityHandlerRequest,
-                                        void* /*callbackParam*/)
-{
-    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
-
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    OCEntityHandlerResponse response;
-
-    // Validate pointer
-    if (!entityHandlerRequest)
-    {
-        OIC_LOG (ERROR, TAG, "Invalid request pointer");
-        return OC_EH_ERROR;
-    }
-
-    OCRepPayload* payload = nullptr;
-
-    if (flag & OC_REQUEST_FLAG)
-    {
-        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
-
-        if (entityHandlerRequest)
-        {
-            switch(entityHandlerRequest->method)
-            {
-            case OC_REST_GET:
-            {
-                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
-                ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
-            }
-            break;
-            default:
-            {
-                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
-                        entityHandlerRequest->method);
-                ehResult = OC_EH_ERROR;
-            }
-            break;
-            }
-
-            if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
-            {
-                // Format the response.  Note this requires some info about the request
-                response.requestHandle = entityHandlerRequest->requestHandle;
-                response.resourceHandle = entityHandlerRequest->resource;
-                response.ehResult = ehResult;
-                response.payload = reinterpret_cast<OCPayload*>(payload);
-                response.numSendVendorSpecificHeaderOptions = 0;
-                memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
-                memset(response.resourceUri, 0, sizeof(response.resourceUri));
-                // Indicate that response is NOT in a persistent buffer
-                response.persistentBufferFlag = 0;
-
-                // Send the response
-                if (OCDoResponse(&response) != OC_STACK_OK)
-                {
-                    OIC_LOG(ERROR, TAG, "Error sending response");
-                    ehResult = OC_EH_ERROR;
-                }
-            }
-        }
-    }
-
-    OCPayloadDestroy(response.payload);
-    return ehResult;
-}
-
-
-/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
-void handleSigInt(int signum)
-{
-    if (signum == SIGINT)
-    {
-        gQuitFlag = 1;
-    }
-}
-
-FILE *server_fopen(const char * /*path*/, const char *mode)
-{
-    return fopen(CRED_FILE, mode);
-}
-
-void SetPersistentHandler(OCPersistentStorage *ps)
-{
-    if (ps)
-    {
-        ps->open =  server_fopen;
-        ps->read = fread;
-        ps->write = fwrite;
-        ps->close = fclose;
-        ps->unlink = unlink;
-
-        OCRegisterPersistentStorageHandler(ps);
-    }
-}
-
-/**
- * GetResult is returned result to string.
- * @param   result             [IN] stack result
- * @return  converted OCStackResult as string for debugging
- */
-static const char *getResult(OCStackResult result)
-{
-    switch (result)
-    {
-        case OC_STACK_OK:
-            return "OC_STACK_OK";
-        case OC_STACK_RESOURCE_CREATED:
-            return "OC_STACK_RESOURCE_CREATED";
-        case OC_STACK_RESOURCE_DELETED:
-            return "OC_STACK_RESOURCE_DELETED";
-        case OC_STACK_INVALID_URI:
-            return "OC_STACK_INVALID_URI";
-        case OC_STACK_INVALID_QUERY:
-            return "OC_STACK_INVALID_QUERY";
-        case OC_STACK_INVALID_IP:
-            return "OC_STACK_INVALID_IP";
-        case OC_STACK_INVALID_PORT:
-            return "OC_STACK_INVALID_PORT";
-        case OC_STACK_INVALID_CALLBACK:
-            return "OC_STACK_INVALID_CALLBACK";
-        case OC_STACK_INVALID_METHOD:
-            return "OC_STACK_INVALID_METHOD";
-        case OC_STACK_NO_MEMORY:
-            return "OC_STACK_NO_MEMORY";
-        case OC_STACK_COMM_ERROR:
-            return "OC_STACK_COMM_ERROR";
-        case OC_STACK_INVALID_PARAM:
-            return "OC_STACK_INVALID_PARAM";
-        case OC_STACK_NOTIMPL:
-            return "OC_STACK_NOTIMPL";
-        case OC_STACK_NO_RESOURCE:
-            return "OC_STACK_NO_RESOURCE";
-        case OC_STACK_RESOURCE_ERROR:
-            return "OC_STACK_RESOURCE_ERROR";
-        case OC_STACK_SLOW_RESOURCE:
-            return "OC_STACK_SLOW_RESOURCE";
-        case OC_STACK_NO_OBSERVERS:
-            return "OC_STACK_NO_OBSERVERS";
-    case OC_STACK_UNAUTHORIZED_REQ:
-        return "OC_STACK_UNAUTHORIZED_REQ";
-    #ifdef WITH_PRESENCE
-    case OC_STACK_PRESENCE_STOPPED:
-        return "OC_STACK_PRESENCE_STOPPED";
-    #endif
-        case OC_STACK_ERROR:
-            return "OC_STACK_ERROR";
-        default:
-            return "UNKNOWN";
-    }
-}
-
-
-/**
- * CreateDoorResource creates a new door resource by calling the OCCreateResource() method.
- * @param   uri                   [IN] uri
- * @param   doorResource          [IN] info of resource
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-int  createDoorResource (const char *uri, DoorResource *doorResource)
-{
-    if (!uri)
-    {
-        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
-
-    }
-
-    doorResource->state = STATE_CLOSED; //1:closed , 0: open
-    doorResource->openDuration = OPEN_DURATION_TIME;
-    doorResource->openAlarm = false;
-    OCStackResult res = OCCreateResource(&(doorResource->handle),
-                                         "core.door",
-                                         OC_RSRVD_INTERFACE_DEFAULT,
-                                         uri,
-                                         OCEntityHandlerCb,
-                                         NULL,
-                                         OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
-
-    OIC_LOG_V(INFO, TAG, "Created Door resource with result: %s", getResult(res));
-    return 0;
-}
-
-OCStackApplicationResult putReqCB(void * ctx, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
-{
-    if (ctx == (void *)DEFAULT_CONTEXT_VALUE)
-    {
-        OIC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
-    }
-
-    if (clientResponse)
-    {
-        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        if ((OCSecurityPayload*)clientResponse->payload)
-        {
-            OIC_LOG_V(INFO, TAG, "=============> Put Response",
-                    ((OCSecurityPayload*)clientResponse->payload)->securityData);
-        }
-    }
-    return OC_STACK_DELETE_TRANSACTION;
-}
-
-OCStackApplicationResult getReqCB(void * /*ctx*/, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
-{
-    OIC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
-
-    if (clientResponse)
-    {
-        OIC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OIC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
-        if ((OCSecurityPayload*)clientResponse->payload)
-        {
-            OIC_LOG(INFO, TAG, PCF("=============> Get Response"));
-        }
-    }
-    return OC_STACK_DELETE_TRANSACTION;
-}
-
-// This is a function called back when a device is discovered
-OCStackApplicationResult discoveryReqCB(void* /*ctx*/, OCDoHandle /*handle*/,
-        OCClientResponse * clientResponse)
-{
-    OIC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
-
-    if (clientResponse)
-    {
-        OIC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-        OIC_LOG_V(INFO, TAG,
-                "Device =============> Discovered @ %s:%d",
-                clientResponse->devAddr.addr,
-                clientResponse->devAddr.port);
-
-        if (clientResponse->result == OC_STACK_OK)
-        {
-            OIC_LOG_PAYLOAD(INFO, clientResponse->payload);
-            ocConnType = clientResponse->connType;
-            parseClientResponse(clientResponse);
-        }
-    }
-
-    return OC_STACK_KEEP_TRANSACTION;
-
-}
-
-
-
-void initAddress()
-{
-    static bool initFlag = false;
-    if (!initFlag)
-    {
-        OIC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
-        OIC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
-        OIC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
-
-        std::cin >> address;
-    }
-    initFlag = true;
-}
-
-// Local function to send get request of light resource
-void SendGetRequest()
-{
-    OCStackResult ret;
-    OIC_LOG(INFO, TAG, "Send Get REQ to Light server");
-
-    //select ciphersuite for certificates
-    CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, CA_ADAPTER_IP);
-
-    initAddress();
-
-    char szQueryUri[MAX_QUERY_LENGTH] = { '\0'};
-    OCDoHandle handle;
-    OCCallbackData cbData;
-    cbData.cb = getReqCB;
-    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
-    cbData.cd = NULL;
-    OIC_LOG_V(INFO, TAG, "Get payload from Door sample = /a/light ");
-    snprintf(szQueryUri,  sizeof(szQueryUri), "coaps://%s/a/light", const_cast<char*> (address.c_str())); // lightPortNu);
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, NULL, ocConnType, OC_LOW_QOS,
-                 &cbData, NULL, 0);
-    if (ret != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "OCStack resource error");
-    }
-}
-
-
-void *input_function(void * /*data*/)
-{
-    char input;
-    char szQueryUri[MAX_QUERY_LENGTH] = { 0 };
-    OCDoHandle handle;
-    OCCallbackData cbData;
-    cbData.cb = discoveryReqCB;
-    cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
-    cbData.cd = NULL;
-
-    strncpy(szQueryUri, MULTICAST_DISCOVERY_QUERY, sizeof(szQueryUri));
-
-    while (1)
-    {
-        std::cin >> input;
-        switch (input)
-        {
-            case 'D':
-            case 'd':
-                if (isUpdated == false)
-                {
-                    OIC_LOG(INFO, TAG, "isUpdated is false...");
-                    if (OCDoResource(&handle, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT,
-                                     OC_LOW_QOS, &cbData, NULL, 0) != OC_STACK_OK)
-                    {
-                        OIC_LOG(ERROR, TAG, "OCDoResource error");
-                    }
-
-                }
-                break;
-            case 'G':
-            case 'g':
-                isUpdated = true;
-                if (isUpdated == true)
-                {
-                    OIC_LOG(INFO, TAG, "isUpdated is true...");
-                    SendGetRequest();
-                }
-                break;
-            case 'Q':
-            case 'q':
-                gQuitFlag = 1;
-                   return 0;
-            default: break;
-        }
-    }
-    return 0;
-}
-
-static void PrintUsage()
-{
-    OIC_LOG(INFO, TAG, "*******************************************");
-    OIC_LOG(INFO, TAG, "Input D or d to discover Resources");
-    OIC_LOG(INFO, TAG, "Input G or g to initiate Get Request");
-    OIC_LOG(INFO, TAG, "Input Q or q to exit");
-    OIC_LOG(INFO, TAG, "*******************************************");
-}
-
-int main()
-{
-
-    OIC_LOG(INFO, TAG, "OCServer is starting...");
-    SetPersistentHandler(&ps);
-    //PrintUsage();
-    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "OCStack init error");
-        return 0;
-    }
-
-    /*
-     * Declare and create the example resource: Door
-     */
-    createDoorResource(gResourceUri, &Door);
-    PrintUsage();
-
-    //select ciphersuite for certificates
-    CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, CA_ADAPTER_IP);
-
-    struct timespec timeout;
-    timeout.tv_sec  = 0;
-    timeout.tv_nsec = 100000000L;
-
-    // Break from loop with Ctrl-C
-    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
-    signal(SIGINT, handleSigInt);
-    int thr_id;
-    pthread_t p_thread;
-    thr_id = pthread_create(&p_thread, NULL, input_function, (void *)NULL);
-    if (thr_id < 0)
-    {
-        OIC_LOG(ERROR, TAG, "create thread error");
-        return 0;
-    }
-
-    while (!gQuitFlag)
-    {
-
-        if (OCProcess() != OC_STACK_OK)
-        {
-            OIC_LOG(ERROR, TAG, "OCStack process error");
-            return 0;
-        }
-
-
-        nanosleep(&timeout, NULL);
-    }
-
-    pthread_join(p_thread, NULL);
-
-    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
-
-    if (OCStop() != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "OCStack process error");
-    }
-
-    return 0;
-}
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/Light_sample.cpp b/resource/csdk/security/provisioning/ck_manager/sample/Light_sample.cpp
deleted file mode 100755 (executable)
index 2a9b176..0000000
+++ /dev/null
@@ -1,334 +0,0 @@
-//******************************************************************
-//
-// Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <signal.h>
-#include <iostream>
-#include <pthread.h>
-#include "ocstack.h"
-#include "logger.h"
-#include "cJSON.h"
-#include "global.h"
-#include "cainterface.h"
-#include "cacommon.h"
-#include "ocpayload.h"
-
-#define TAG "DEMO"
-
-volatile sig_atomic_t gQuitFlag = 0;
-OCPersistentStorage ps = {0, 0, 0, 0, 0};
-const char *gResourceUri = (char *)"/a/light";
-
-//Secure Virtual Resource database for Iotivity Server
-//It contains Server's Identity and the PSK credentials
-//of other devices which the server trusts
-static char CRED_FILE[] = "oic_svr_db_light.dat";
-
-
-//Structure to represent a light resource  and its attributes
-typedef struct LIGHTRESOURCE
-{
-    OCResourceHandle handle;
-    //Attributes
-    int brightness;   // 0-100
-} LightResource;
-
-// Structure to represent a light resource  and its attributes
-static LightResource Light;
-
-OCRepPayload* getPayload(const char* uri, int64_t brightness)
-{
-    OCRepPayload* payload = OCRepPayloadCreate();
-    if(!payload)
-    {
-        OIC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
-        return nullptr;
-    }
-
-    OCRepPayloadSetUri(payload, uri);
-    OCRepPayloadSetPropInt(payload, "brightness", brightness);
-
-    return payload;
-}
-
-//This function takes the request as an input and returns the response
-OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
-{
-    if(!ehRequest)
-    {
-        return nullptr;
-    }
-
-    if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
-    {
-        OIC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
-        return nullptr;
-    }
-
-    return getPayload(gResourceUri, Light.brightness);
-}
-
-OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
-        OCRepPayload **payload)
-{
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-
-    OCRepPayload *getResp = constructResponse(ehRequest);
-
-    if(getResp && payload)
-    {
-        *payload = getResp;
-        ehResult = OC_EH_OK;
-    }
-
-    return ehResult;
-}
-
-
-OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
-                                         OCEntityHandlerRequest *entityHandlerRequest,
-                                         void* /*callbackParam*/)
-{
-    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
-
-    OCEntityHandlerResult ehResult = OC_EH_ERROR;
-    OCEntityHandlerResponse response;
-
-    // Validate pointer
-    if (!entityHandlerRequest)
-    {
-        OIC_LOG (ERROR, TAG, "Invalid request pointer");
-        return OC_EH_ERROR;
-    }
-
-    OCRepPayload* payload = nullptr;
-
-    if (flag & OC_REQUEST_FLAG)
-    {
-        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
-        if (entityHandlerRequest)
-        {
-            switch(entityHandlerRequest->method)
-            {
-            case OC_REST_GET:
-            {
-                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
-                ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
-            }
-            break;
-            default:
-            {
-                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
-                        entityHandlerRequest->method);
-                ehResult = OC_EH_ERROR;
-            }
-            break;
-            }
-
-            if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
-            {
-                // Format the response.  Note this requires some info about the request
-                response.requestHandle = entityHandlerRequest->requestHandle;
-                response.resourceHandle = entityHandlerRequest->resource;
-                response.ehResult = ehResult;
-                response.payload = reinterpret_cast<OCPayload*>(payload);
-                response.numSendVendorSpecificHeaderOptions = 0;
-                memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
-                memset(response.resourceUri, 0, sizeof(response.resourceUri));
-                // Indicate that response is NOT in a persistent buffer
-                response.persistentBufferFlag = 0;
-
-                // Send the response
-                if (OCDoResponse(&response) != OC_STACK_OK)
-                {
-                    OIC_LOG(ERROR, TAG, "Error sending response");
-                    ehResult = OC_EH_ERROR;
-                }
-            }
-        }
-    }
-
-    OCPayloadDestroy(response.payload);
-    return ehResult;
-}
-
-/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
-void handleSigInt(int signum)
-{
-    if (signum == SIGINT)
-    {
-        gQuitFlag = 1;
-    }
-}
-
-FILE* server_fopen(const char * /*path*/, const char *mode)
-{
-    return fopen(CRED_FILE, mode);
-}
-
-void SetPersistentHandler(OCPersistentStorage *ps)
-
-{
-
-    if (ps)
-
-    {
-
-        ps->open =  server_fopen;
-
-        ps->read = fread;
-
-        ps->write = fwrite;
-
-        ps->close = fclose;
-
-        ps->unlink = unlink;
-
-
-        OCRegisterPersistentStorageHandler(ps);
-
-    }
-
-}
-/**
- * GetResult is returned result to string.
- * @param   result             [IN] stack result
- * @return  converted OCStackResult as string for debugging
- */
-static const char *getResult(OCStackResult result)
-{
-    switch (result)
-    {
-        case OC_STACK_OK:
-            return "OC_STACK_OK";
-        case OC_STACK_RESOURCE_CREATED:
-            return "OC_STACK_RESOURCE_CREATED";
-        case OC_STACK_RESOURCE_DELETED:
-            return "OC_STACK_RESOURCE_DELETED";
-        case OC_STACK_INVALID_URI:
-            return "OC_STACK_INVALID_URI";
-        case OC_STACK_INVALID_QUERY:
-            return "OC_STACK_INVALID_QUERY";
-        case OC_STACK_INVALID_IP:
-            return "OC_STACK_INVALID_IP";
-        case OC_STACK_INVALID_PORT:
-            return "OC_STACK_INVALID_PORT";
-        case OC_STACK_INVALID_CALLBACK:
-            return "OC_STACK_INVALID_CALLBACK";
-        case OC_STACK_INVALID_METHOD:
-            return "OC_STACK_INVALID_METHOD";
-        case OC_STACK_NO_MEMORY:
-            return "OC_STACK_NO_MEMORY";
-        case OC_STACK_COMM_ERROR:
-            return "OC_STACK_COMM_ERROR";
-        case OC_STACK_INVALID_PARAM:
-            return "OC_STACK_INVALID_PARAM";
-        case OC_STACK_NOTIMPL:
-            return "OC_STACK_NOTIMPL";
-        case OC_STACK_NO_RESOURCE:
-            return "OC_STACK_NO_RESOURCE";
-        case OC_STACK_RESOURCE_ERROR:
-            return "OC_STACK_RESOURCE_ERROR";
-        case OC_STACK_SLOW_RESOURCE:
-            return "OC_STACK_SLOW_RESOURCE";
-        case OC_STACK_NO_OBSERVERS:
-            return "OC_STACK_NO_OBSERVERS";
-        case OC_STACK_ERROR:
-            return "OC_STACK_ERROR";
-        default:
-            return "UNKNOWN";
-    }
-}
-
-/**
- * CreateLightResource creates a new light resource by calling the OCCreateResource() method.
- * @param   uri                    [IN] uri
- * @param   lightResource          [IN] info of resource
- * @return ::OC_STACK_OK on success, some other value upon failure.
- */
-int createLightResource (const char *uri, LightResource *lightResource)
-{
-    if (!uri)
-    {
-        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
-
-    }
-
-    lightResource->brightness = 0;
-    OCStackResult res = OCCreateResource(&(lightResource->handle),
-                                         "core.light",
-                                         OC_RSRVD_INTERFACE_DEFAULT,
-                                         uri,
-                                         OCEntityHandlerCb,
-                                         NULL,
-                                         OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
-
-    OIC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
-    return 0;
-}
-
-
-int main()
-{
-    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
-    SetPersistentHandler(&ps);
-    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "OCStack init error");
-        return 0;
-    }
-
-    /*
-     * Declare and create the example resource: Light
-     */
-    createLightResource(gResourceUri, &Light);
-
-    CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, CA_ADAPTER_IP);
-
-    struct timespec timeout;
-    timeout.tv_sec  = 0;
-    timeout.tv_nsec = 100000000L;
-
-    // Break from loop with Ctrl-C
-    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
-    signal(SIGINT, handleSigInt);
-    while (!gQuitFlag)
-    {
-        if (OCProcess() != OC_STACK_OK)
-        {
-            OIC_LOG(ERROR, TAG, "OCStack process error");
-            return 0;
-        }
-
-        nanosleep(&timeout, NULL);
-    }
-
-    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
-
-    if (OCStop() != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "OCStack process error");
-    }
-
-    return 0;
-}
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/README.txt b/resource/csdk/security/provisioning/ck_manager/sample/README.txt
deleted file mode 100644 (file)
index 6378d5e..0000000
+++ /dev/null
@@ -1,132 +0,0 @@
-# Open three terminal windows in linux
-# The first one use for start Light server
-# Note: Here and below $PROJ_DIR is root directory of iotivity project (e.g /path/to/iotivity)
-$ cd $PROJ_DIR/out/linux/x86_64/release/resource/csdk/security/provisioning/ck_manager/sample/Light_Resource
-$ cp $PROJ_DIR/resource/csdk/security/provisioning/ck_manager/sample/Light_Resource/*.json ./
-$ ./Light_server
-
-# Second terminal window use for start Door server
-$ cp $PROJ_DIR/resource/csdk/security/provisioning/ck_manager/sample/Door_Resource/*.json ./
-$ ./Door_server
-
-# And third terminal window use for start provisioning_client
-# provisioning_client ask for input ACL data:
-# 1. Controller device. Enter ID of the doorDeviceUUID00
-# 2. Controlee device. Enter ID of the lightDeviceUUID0
-# 3. Subject : doorDeviceUUID00
-# 4. Num. of Resource : 1
-# 5. [1]Resource : /a/light
-# 6. permissions: CRUDN
-# 7. Num. of Rowner : 1
-# 8. [1]Rowner : lightDeviceUUID0
-#
-# After successful sending acl provisioning_client will ask you for CRL data:
-# 1. Enter number of revoced certificates(1..9): 1
-# 2. Revoced certificate 0: Serial number (E. g.: 100): 3
-# And then you should see message about successful sending CRL
-#
-# Note: provisioning_client send ACL and CRL only to Light sever
-
-$ cd $PROJ_DIR/out/linux/x86_64/release/resource/csdk/security/provisioning/ck_manager/sample
-$ rm ckminfo.dat
-$ cp $PROJ_DIR/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json ./
-$ ./provisioningclient
-Provisioning device ID : doorDeviceUUID00
-Provisioning Success~!!
-Provisioning device ID : lightDeviceUUID0
-Provisioning Success~!!
-Sending credential is succeed~!!
-******************************************************************************
--Set ACL policy for target device
-******************************************************************************
--URN identifying the subject
-ex) doorDeviceUUID00 (16 Numbers except to '-')
-Subject : doorDeviceUUID00
-Num. of Resource : 1
--URI of resource
-ex) /a/light (Max_URI_Length: 256 Byte )
-[1]Resource : /a/light
--Set the permission(C,R,U,D,N)
-ex) CRUDN, CRU_N,..(5 Charaters)
-Permission : CRUDN
-Num. of Rowner : 1
--URN identifying the rowner
-ex) lightDeviceUUID0 (16 Numbers except to '-')
-[1]Rowner : lightDeviceUUID0
-Sending ACL is succeed~!!
-Enter number of revoced certificates (1..9)
-1
-Revoked certificate 0:
-Serial number (E. g.: 100):
-2
-Sending CRL is succeed~!!
-
-# Change window to terminal where Door server is running
-# Enter 'd' for  discovery. You should see output like this:
-21:56.283 INFO: DEMO: isUpdated is false...
-21:56.495 INFO: DEMO: Callback Context for DISCOVER query recvd successfully
-21:56.495 INFO: DEMO: StackResult: OC_STACK_OK
-21:56.495 INFO: DEMO: Device =============> Discovered @ 10.0.2.15:37942
-21:56.495 INFO: DEMO: Payload Type: Discovery
-21:56.495 INFO: DEMO:  Resource #1
-21:56.495 INFO: DEMO:  URI:/a/light
-21:56.495 INFO: DEMO:  SID:
-21:56.495 INFO: DEMO: F0 5A 6C 8B 59 66 48 89 BE 1E 4E EF FA 23 4E FD
-21:56.495 INFO: DEMO:  Resource Types:
-21:56.495 INFO: DEMO:          core.light
-21:56.495 INFO: DEMO:  Interfaces:
-21:56.495 INFO: DEMO:          oic.if.baseline
-21:56.495 INFO: DEMO:  Bitmap: 3
-21:56.495 INFO: DEMO:  Secure?: true
-21:56.495 INFO: DEMO:  Port: 43910
-21:56.495 INFO: DEMO:
-21:56.495 INFO: DEMO: Uri -- /a/light
-21:56.495 INFO: DEMO: Secure -- YES
-21:56.591 INFO: DEMO: Callback Context for DISCOVER query recvd successfully
-21:56.591 INFO: DEMO: StackResult: OC_STACK_OK
-21:56.591 INFO: DEMO: Device =============> Discovered @ 10.0.2.15:55808
-21:56.591 INFO: DEMO: Payload Type: Discovery
-21:56.591 INFO: DEMO:  Resource #1
-21:56.591 INFO: DEMO:  URI:/a/door
-21:56.591 INFO: DEMO:  SID:
-21:56.591 INFO: DEMO: E9 68 45 ED 5D E1 4A F3 86 31 FD 0E 5E 25 EB B3
-21:56.591 INFO: DEMO:  Resource Types:
-21:56.591 INFO: DEMO:          core.door
-21:56.591 INFO: DEMO:  Interfaces:
-21:56.591 INFO: DEMO:          oic.if.baseline
-21:56.591 INFO: DEMO:  Bitmap: 3
-21:56.591 INFO: DEMO:  Secure?: true
-21:56.591 INFO: DEMO:  Port: 41403
-21:56.591 INFO: DEMO:
-21:56.591 INFO: DEMO: Uri -- /a/door
-21:56.591 INFO: DEMO: Secure -- YES
-
-# If you can see /a/light discowered then this is success.
-# Next you should enter g to start get request
-# Enter address : 10.0.2.15:43910
-# Port you can find here
-21:56.495 INFO: DEMO:  URI:/a/light
-21:56.495 INFO: DEMO:  SID:
-21:56.495 INFO: DEMO: F0 5A 6C 8B 59 66 48 89 BE 1E 4E EF FA 23 4E FD
-21:56.495 INFO: DEMO:  Resource Types:
-21:56.495 INFO: DEMO:          core.light
-21:56.495 INFO: DEMO:  Interfaces:
-21:56.495 INFO: DEMO:          oic.if.baseline
-21:56.495 INFO: DEMO:  Bitmap: 3
-21:56.495 INFO: DEMO:  Secure?: true
-21:56.495 INFO: DEMO:  Port: 43910
-
-# If you see this lines in output:
-22:31.647 INFO: DEMO: Callback Context for GET query recvd successfully
-22:31.647 INFO: DEMO: StackResult: OC_STACK_OK
-22:31.647 INFO: DEMO: SEQUENCE NUMBER: 2
-22:31.647 INFO: DEMO: Payload Type: Representation
-22:31.647 INFO: DEMO:  Resource #1
-22:31.647 INFO: DEMO:  URI:/a/light
-22:31.647 INFO: DEMO:  Resource Types:
-22:31.647 INFO: DEMO:  Interfaces:
-22:31.647 INFO: DEMO:  Values:
-22:31.647 INFO: DEMO:          brightness(int):0
-22:31.647 INFO: DEMO: =============> Get Response
-# then certificate did not rejected with CRL
-# if not then it did.
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat
deleted file mode 100644 (file)
index fbe36db..0000000
Binary files a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat and /dev/null differ
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json
deleted file mode 100644 (file)
index 6dcbdbf..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-{\r
-    "acl": {\r
-        "aclist": {\r
-            "aces": [\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/res",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.res"],\r
-                            "if": ["oic.if.ll"]\r
-                        },{\r
-                            "href": "/oic/d",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.d"],\r
-                            "if": ["oic.if.baseline", "oic.if.r"]\r
-                        },{\r
-                            "href": "/oic/p",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.p"],\r
-                            "if": ["oic.if.baseline", "oic.if.r"]\r
-                        }\r
-                    ],\r
-                    "permission": 2\r
-                },\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/sec/doxm",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.doxm"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/pstat",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.pstat"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/acl",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.acl"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/cred",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.cred"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/crl",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.crl"],\r
-                            "if": ["oic.if.baseline"]\r
-                        }\r
-                    ],\r
-                    "permission": 6\r
-                }\r
-            ]\r
-        },\r
-        "rowneruuid" : "646F6F72-4465-7669-6365-555549443030"\r
-    },\r
-    "pstat": {\r
-        "isop": false,\r
-        "deviceuuid": "646F6F72-4465-7669-6365-555549443030",\r
-        "rowneruuid": "646F6F72-4465-7669-6365-555549443030",\r
-        "cm": 2,\r
-        "tm": 0,\r
-        "om": 3,\r
-        "sm": 3\r
-        },\r
-    "doxm": {\r
-        "oxms": [0],\r
-        "oxmsel": 0,\r
-        "sct": 1,\r
-        "owned": false,\r
-        "deviceuuid": "646F6F72-4465-7669-6365-555549443030",\r
-        "rowneruuid": "646F6F72-4465-7669-6365-555549443030",\r
-        "x.org.iotivity.dpc": false\r
-    }\r
-}
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat
deleted file mode 100644 (file)
index 46eed49..0000000
Binary files a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat and /dev/null differ
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json
deleted file mode 100644 (file)
index 0bf4375..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-{\r
-    "acl": {\r
-        "aclist": {\r
-            "aces": [\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/res",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.res"],\r
-                            "if": ["oic.if.ll"]\r
-                        },{\r
-                            "href": "/oic/d",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.d"],\r
-                            "if": ["oic.if.baseline", "oic.if.r"]\r
-                        },{\r
-                            "href": "/oic/p",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.p"],\r
-                            "if": ["oic.if.baseline", "oic.if.r"]\r
-                        }\r
-                    ],\r
-                    "permission": 2\r
-                },\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/sec/doxm",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.doxm"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/pstat",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.pstat"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/acl",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.acl"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/cred",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.cred"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/crl",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.crl"],\r
-                            "if": ["oic.if.baseline"]\r
-                        }\r
-                    ],\r
-                    "permission": 6\r
-                }\r
-            ]\r
-        },\r
-        "rowneruuid" : "6C696768-7444-6576-6963-655555494430"\r
-    },\r
-    "pstat": {\r
-        "isop": false,\r
-        "deviceuuid": "6C696768-7444-6576-6963-655555494430",\r
-        "rowneruuid": "6C696768-7444-6576-6963-655555494430",\r
-        "cm": 2,\r
-        "tm": 0,\r
-        "om": 3,\r
-        "sm": 3\r
-        },\r
-    "doxm": {\r
-        "oxms": [0],\r
-        "oxmsel": 0,\r
-        "sct": 1,\r
-        "owned": false,\r
-        "deviceuuid": "6C696768-7444-6576-6963-655555494430",\r
-        "rowneruuid": "6C696768-7444-6576-6963-655555494430",\r
-        "x.org.iotivity.dpc": false\r
-    }\r
-}
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat
deleted file mode 100644 (file)
index ea814fd..0000000
Binary files a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat and /dev/null differ
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json
deleted file mode 100644 (file)
index f13ed08..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-{\r
-    "acl": {\r
-        "aclist": {\r
-            "aces": [\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/res",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.res"],\r
-                            "if": ["oic.if.ll"]\r
-                        },{\r
-                            "href": "/oic/d",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.d"],\r
-                            "if": ["oic.if.baseline", "oic.if.r"]\r
-                        },{\r
-                            "href": "/oic/p",\r
-                            "rel": "",\r
-                            "rt": ["oic.wk.p"],\r
-                            "if": ["oic.if.baseline", "oic.if.r"]\r
-                        }\r
-                    ],\r
-                    "permission": 2\r
-                },\r
-                {\r
-                    "subjectuuid": "*",\r
-                    "resources": [\r
-                        {\r
-                            "href": "/oic/sec/doxm",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.doxm"],\r
-                            "if": ["oic.if.baseline"]\r
-                        },\r
-                        {\r
-                            "href": "/oic/sec/pstat",\r
-                            "rel": "",\r
-                            "rt": ["oic.r.pstat"],\r
-                            "if": ["oic.if.baseline"]\r
-                        }\r
-                    ],\r
-                    "permission": 2\r
-                }\r
-            ]\r
-        },\r
-        "rowneruuid" : "61646D69-6E44-6576-6963-655555494430"\r
-    },\r
-    "pstat": {\r
-        "isop": true,\r
-        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "rowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "cm": 2,\r
-        "tm": 0,\r
-        "om": 3,\r
-        "sm": 3\r
-        },\r
-    "doxm": {\r
-        "oxms": [0],\r
-        "oxmsel": 0,\r
-        "sct": 1,\r
-        "owned": true,\r
-        "deviceuuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "devowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "rowneruuid": "61646D69-6E44-6576-6963-655575696430",\r
-        "x.org.iotivity.dpc": false\r
-    }\r
-}
\ No newline at end of file
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c b/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c
deleted file mode 100644 (file)
index 7784088..0000000
+++ /dev/null
@@ -1,793 +0,0 @@
-/******************************************************************
-*
-* Copyright 2015 Samsung Electronics All Rights Reserved.
-*
-*
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-*      http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-******************************************************************/
-
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "logger.h"
-#include "oic_malloc.h"
-#include "utlist.h"
-#include "ocprovisioningmanager.h"
-#include "secureresourceprovider.h"
-#include "oxmjustworks.h"
-#include "oic_string.h"
-#include "securevirtualresourcetypes.h"
-#include "cacommon.h"
-#include "ck_manager.h"
-#include "ckm_info.h"
-#include "crlresource.h"
-
-#define MAX_PERMISSION_LENGTH (5)
-#define MAX_ACE_LENGTH (100)
-#define MAX_INTERFACE_LENGTH (10)
-#define MAX_RESOURCETYPE_LENGTH (10)
-#define MAX_STRING_INPUT_BUFFER_SIZE (256)
-
-#define CREATE (1)
-#define READ (2)
-#define UPDATE (4)
-#define DELETE (8)
-#define NOTIFY (16)
-#define DASH '-'
-#define PREDEFINED_TIMEOUT (10)
-#define MAX_OWNED_DEVICE (10)
-#define DATE_LENGTH      (14)
-#define TAG  "provisioningclient"
-
-static OicSecAcl_t        *gAcl = NULL;
-static OicSecCrl_t        *gCrl = NULL;
-static char PROV_TOOL_DB_FILE[] = "oic_svr_db_pt.dat";
-static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
-static int gOwnershipState = 0;
-
-typedef enum
-{
-    ownershipDone = 1 << 1,
-    finalizeDone = 1 << 2,
-    provisionAclDone = 1 << 3,
-    provisionCert1Done = 1 << 4,
-    provisionCert2Done = 1 << 5,
-    provisionCrlDone = 1 << 6
-} StateManager;
-
-void deleteCrl(OicSecCrl_t *crl)
-{
-    if (crl)
-    {
-        //Clean ThisUpdate
-        OICFree(crl->ThisUpdate.data);
-
-        //clean CrlData
-        OICFree(crl->CrlData.data);
-
-        //Clean crl itself
-        OICFree(crl);
-    }
-}
-
-/**
- * Calculate ACL permission from string to bit
- *
- * @param[in] temp_psm    Input data of ACL permission string
- * @param[in,out] pms    The pointer of ACL permission value
- * @return  0 on success otherwise -1.
- */
-static int CalculateAclPermission(const char *temp_pms, uint16_t *pms)
-{
-    int i = 0;
-
-    if (NULL == temp_pms || NULL == pms)
-    {
-        return -1;
-    }
-    *pms = 0;
-    while (temp_pms[i] != '\0')
-    {
-        switch (temp_pms[i])
-        {
-            case 'C':
-                {
-                    *pms += CREATE;
-                    i++;
-                    break;
-                }
-            case 'R':
-                {
-                    *pms += READ;
-                    i++;
-                    break;
-                }
-            case 'U':
-                {
-                    *pms += UPDATE;
-                    i++;
-                    break;
-                }
-            case 'D':
-                {
-                    *pms += DELETE;
-                    i++;
-                    break;
-                }
-            case 'N':
-                {
-                    *pms += NOTIFY;
-                    i++;
-                    break;
-                }
-            case '_':
-                {
-                    i++;
-                    break;
-                }
-            default:
-                {
-                    return -1;
-                }
-        }
-    }
-    return 0;
-}
-
-/**
- * Get the ACL property from user
- *
- * @param[in]    ACL Datastructure to save user inputs
- * @return  0 on success otherwise -1.
- */
-static int InputACL(OicSecAcl_t *acl)
-{
-    int ret;
-    char temp_id [UUID_LENGTH + 4] = {0,};
-    char temp_rsc[MAX_URI_LENGTH + 1] = {0,};
-    char temp_pms[MAX_PERMISSION_LENGTH + 1] = {0,};
-    char input_buffer[MAX_STRING_INPUT_BUFFER_SIZE] = {0};
-    OicSecAce_t* ace = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
-    if(!ace)
-    {
-        printf("Failed to memory allocation\n");
-        return -1;
-    }
-    LL_APPEND(acl->aces, ace);
-
-    printf("******************************************************************************\n");
-    printf("-Set ACL policy for target device\n");
-    printf("******************************************************************************\n");
-
-    //Set Subject.
-    printf("-URN identifying the subject\n");
-    printf("ex) doorDeviceUUID00 (16 Numbers except to '-')\n");
-    printf("Subject : ");
-    char *ptr = NULL;
-    ret = scanf("%19ms", &ptr);
-    if(1==ret)
-    {
-        OICStrcpy(temp_id, sizeof(temp_id), ptr);
-        OICFree(ptr);
-    }
-    else
-    {
-         printf("Error while input\n");
-         return -1;
-    }
-    int j = 0;
-    for (int i = 0; temp_id[i] != '\0'; i++)
-    {
-        if (DASH != temp_id[i])
-        {
-            if(j >= UUID_LENGTH)
-            {
-                printf("Invalid input\n");
-                return -1;
-            }
-            ace->subjectuuid.id[j++] = temp_id[i];
-        }
-    }
-
-    //Set Resource.
-    printf("Num. of Resource : \n");
-    size_t inputLen = 0;
-    ret = scanf("%zu", &inputLen);
-    if(-1 == ret || MAX_ACE_LENGTH < inputLen)
-    {
-        printf("Error while input\n");
-        return -1;
-    }
-    printf("-URI of resource\n");
-    printf("ex) /a/light (Max_URI_Length: %d Byte )\n", MAX_URI_LENGTH);
-
-    for(size_t i = 0; i < inputLen; i++)
-    {
-        OicSecRsrc_t* rsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
-        if(!rsrc)
-        {
-            printf("Failed to memory allocation\n");
-            return -1;
-        }
-        LL_APPEND(ace->resources, rsrc);
-
-        //Input the resource URI for each resource
-        printf("[%zu]Resource : ", i + 1);
-        ret = scanf("%s", input_buffer);
-        if (1==ret)
-        {
-            rsrc->href = OICStrdup(input_buffer);
-            if(!rsrc->href)
-            {
-                printf("Failed to OICStrdup\n");
-                return -1;
-            }
-        }
-        else
-        {
-            printf("Error while input\n");
-            return -1;
-        }
-
-        //Input the interface name of resource
-        printf("Num. of Interface of [%s] (Max value : %d) : \n", rsrc->href, MAX_INTERFACE_LENGTH);
-        ret = scanf("%zu", &rsrc->interfaceLen);
-        if(-1 == ret || MAX_INTERFACE_LENGTH < rsrc->interfaceLen)
-        {
-            printf("Error while input\n");
-            return -1;
-        }
-
-        printf("-Interface of [%s] resource\n", rsrc->href);
-        printf("ex) oic.if.baseline (Max Length: 64 Byte )\n");
-        rsrc->interfaces = (char**)OICCalloc(rsrc->interfaceLen, sizeof(char*));
-        if(!rsrc->interfaces)
-        {
-            printf("Failed to memory allocation\n");
-            return -1;
-        }
-        for(size_t j = 0; j < rsrc->interfaceLen; j++)
-        {
-            printf("Interface[%zu] : ", j + 1);
-            ret = scanf("%s", input_buffer);
-            if(1 == ret)
-            {
-                rsrc->interfaces[i] = OICStrdup(input_buffer);
-                if(!rsrc->interfaces[i])
-                {
-                    printf("Failed to OICStrdup\n");
-                    return -1;
-                }
-            }
-            else
-            {
-                printf("Error while input\n");
-                return -1;
-            }
-        }
-
-        //Input the resource type of resource
-        printf("Num. of ResourceType of [%s] (Max value : %d)  : \n", rsrc->href, MAX_RESOURCETYPE_LENGTH);
-        ret = scanf("%zu", &rsrc->typeLen);
-        if(-1 == ret || MAX_RESOURCETYPE_LENGTH < rsrc->typeLen)
-        {
-            printf("Error while input\n");
-            return -1;
-        }
-
-        printf("-Resource Type of [%s] resource\n", rsrc->href);
-        printf("ex) oic.core (Max Length: 64 Byte )\n");
-        rsrc->types = (char**)OICCalloc(rsrc->typeLen, sizeof(char*));
-        if(!rsrc->types)
-        {
-            printf("Failed to memory allocation\n");
-            return -1;
-        }
-        for(size_t j = 0; j < rsrc->typeLen; j++)
-        {
-            printf("Resource type[%zu] : ", j + 1);
-            ret = scanf("%s", input_buffer);
-            if(1 == ret)
-            {
-                rsrc->types[i] = OICStrdup(input_buffer);
-                if(!rsrc->types[i])
-                {
-                    printf("Failed to OICStrdup\n");
-                    return -1;
-                }
-            }
-            else
-            {
-                printf("Error while input\n");
-                return -1;
-            }
-        }
-    }
-
-    // Set Permission
-    do
-    {
-        printf("-Set the permission(C,R,U,D,N)\n");
-        printf("ex) CRUDN, CRU_N,..(5 Charaters)\n");
-        printf("Permission : ");
-        ret = scanf("%s", &input_buffer);
-        if(1 == ret)
-        {
-            OICStrcpy(temp_pms, sizeof(temp_pms), input_buffer);
-        }
-        else
-        {
-            printf("Error while input\n");
-            return -1;
-        }
-    }
-    while (0 != CalculateAclPermission(temp_pms, &(ace->permission)) );
-
-    return 0;
-}
-
-
-
-//FILE *client_fopen(const char *path, const char *mode)
-FILE *client_fopen(const char* UNUSED_PARAM , const char *mode)
-{
-    (void)UNUSED_PARAM;
-    return fopen(PROV_TOOL_DB_FILE, mode);
-}
-
-void PrintfResult(const char* procName, void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
-{
-    printf("-----------------------------------------------------------\n");
-    if(!hasError)
-    {
-        printf("%s was successfully done.\n", procName);
-    }
-    else
-    {
-        for(int i = 0; i < nOfRes; i++)
-        {
-            printf("UUID : ");
-            for(int j = 0; j < UUID_LENGTH; j++)
-            {
-                printf("%c", arr[i].deviceId.id[j]);
-            }
-            printf("\t");
-            printf("Result=%d\n", arr[i].res);
-        }
-    }
-
-    if(ctx)
-    {
-        printf("Context is %s\n", (char*)ctx);
-    }
-    printf("-----------------------------------------------------------\n");
-}
-
-void ProvisionCertCB(void* ctx, int nOfRes, OCProvisionResult_t&