From: Dmitriy Zhuravlev Date: Mon, 3 Oct 2016 13:22:11 +0000 (+0300) Subject: Common adapter for DTLS/TLS X-Git-Tag: 1.3.0~1055^2~99 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=e6fec04bd9a57d0a11b2e682b2cc65c0a5d187ae;p=platform%2Fupstream%2Fiotivity.git Common adapter for DTLS/TLS 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 X-Origin-Change-Id: I6b47f7b3439b923ec12f26b0e159e3b7a1144658 Signed-off-by: Philippe Coval Signed-off-by: Oleksii Beketov Signed-off-by: Dmitriy Zhuravlev Signed-off-by: Trevor Bramwell Reviewed-on: https://gerrit.iotivity.org/gerrit/12029 Tested-by: jenkins-iotivity Reviewed-by: Randeep Singh Reviewed-on: https://gerrit.iotivity.org/gerrit/13095 Reviewed-by: Kevin Kane --- diff --git a/build_common/SConscript b/build_common/SConscript index 3008842..b5203fb 100644 --- a/build_common/SConscript +++ b/build_common/SConscript @@ -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) diff --git a/build_common/android/SConscript b/build_common/android/SConscript index dcd6481..f24c038 100644 --- a/build_common/android/SConscript +++ b/build_common/android/SConscript @@ -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 diff --git a/examples/OICMiddle/SConscript b/examples/OICMiddle/SConscript index 4335a48..05b3aae 100644 --- a/examples/OICMiddle/SConscript +++ b/examples/OICMiddle/SConscript @@ -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 index 18fec68..0000000 --- a/extlibs/asn1cert/SConscript +++ /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 index c5053a9..0000000 --- a/extlibs/asn1cert/certificate.asn +++ /dev/null @@ -1,61 +0,0 @@ -CERTIFICATE DEFINITIONS ::= BEGIN - -Certificate ::= SEQUENCE { - tbsCertificate TBSCertificate, - signatureAlgorithm AlgorithmIdentifier, - signatureValue BIT STRING -} - -AlgorithmIdentifier ::= SEQUENCE { - algorithm OBJECT IDENTIFIER, - id-ecPublicKey OBJECT IDENTIFIER OPTIONAL, - nul NULL OPTIONAL -} - -TBSCertificate ::= SEQUENCE { - version [0] EXPLICIT Version DEFAULT v1, - serialNumber CertificateSerialNumber, - signature AlgorithmIdentifier, - issuer Name, - validity Validity, - subject Name, - subjectPublicKeyInfo SubjectPublicKeyInfo -} - -Version ::= INTEGER { v1(0), v2(1), v3(2) } - -CertificateSerialNumber ::= INTEGER - -Name ::= RDNSequence - -RDNSequence ::= SEQUENCE OF RelativeDistinguishedName - -RelativeDistinguishedName ::= SET OF AttributeTypeAndValue - -AttributeTypeAndValue ::= SEQUENCE { - type AttributeType, - value AttributeValue} - -AttributeType ::= OBJECT IDENTIFIER - -AttributeValue ::= UTF8String - -Validity ::= SEQUENCE { - notBefore Time, - notAfter Time -} - -Time ::= UTCTime - -SubjectPublicKeyInfo ::= SEQUENCE { - algorithm AlgorithmIdentifier, - subjectPublicKey BIT STRING -} - -ECDSA-Sig-Value ::= SEQUENCE { - r INTEGER, - s INTEGER -} - -END - diff --git a/extlibs/asn1cert/crl.asn b/extlibs/asn1cert/crl.asn deleted file mode 100644 index c73cb64..0000000 --- a/extlibs/asn1cert/crl.asn +++ /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 index f51fe2c..0000000 --- a/extlibs/asn1cert/csr.asn +++ /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 diff --git a/extlibs/mbedtls/SConscript b/extlibs/mbedtls/SConscript index 1b662b7..5ea4b2e 100644 --- a/extlibs/mbedtls/SConscript +++ b/extlibs/mbedtls/SConscript @@ -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) diff --git a/plugins/samples/linux/SConscript b/plugins/samples/linux/SConscript index bad07a3..1db50ba 100644 --- a/plugins/samples/linux/SConscript +++ b/plugins/samples/linux/SConscript @@ -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']) diff --git a/resource/csdk/connectivity/inc/pkix/byte_array.h b/resource/c_common/byte_array.h 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 --- a/resource/csdk/connectivity/inc/pkix/byte_array.h +++ b/resource/c_common/byte_array.h @@ -32,18 +32,18 @@ extern "C" { #include /** - * @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{ \ diff --git a/resource/c_common/ocrandom/test/SConscript b/resource/c_common/ocrandom/test/SConscript index 0f9d732..e3536c1 100644 --- a/resource/c_common/ocrandom/test/SConscript +++ b/resource/c_common/ocrandom/test/SConscript @@ -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']) diff --git a/resource/csdk/SConscript b/resource/csdk/SConscript index 13781fd..0de9e79 100644 --- a/resource/csdk/SConscript +++ b/resource/csdk/SConscript @@ -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']: diff --git a/resource/csdk/connectivity/api/casecurityinterface.h b/resource/csdk/connectivity/api/casecurityinterface.h index bae8653..fa3c2ef 100644 --- a/resource/csdk/connectivity/api/casecurityinterface.h +++ b/resource/csdk/connectivity/api/casecurityinterface.h @@ -27,23 +27,15 @@ #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" */ diff --git a/resource/csdk/connectivity/build/android/SConscript b/resource/csdk/connectivity/build/android/SConscript index b2f9297..654e6f3 100644 --- a/resource/csdk/connectivity/build/android/SConscript +++ b/resource/csdk/connectivity/build/android/SConscript @@ -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 diff --git a/resource/csdk/connectivity/build/tizen/gbsbuild.sh b/resource/csdk/connectivity/build/tizen/gbsbuild.sh index 2376dac..8ccc9b1 100755 --- a/resource/csdk/connectivity/build/tizen/gbsbuild.sh +++ b/resource/csdk/connectivity/build/tizen/gbsbuild.sh @@ -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 diff --git a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec index 11e7823..222cd4e 100644 --- a/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec +++ b/resource/csdk/connectivity/build/tizen/packaging/com.oic.ca.spec @@ -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}/ diff --git a/resource/csdk/connectivity/inc/ca_adapter_net_tls.h b/resource/csdk/connectivity/inc/ca_adapter_net_ssl.h similarity index 72% rename from resource/csdk/connectivity/inc/ca_adapter_net_tls.h rename to resource/csdk/connectivity/inc/ca_adapter_net_ssl.h index 130c126..a558137 100644 --- a/resource/csdk/connectivity/inc/ca_adapter_net_tls.h +++ b/resource/csdk/connectivity/inc/ca_adapter_net_ssl.h @@ -17,8 +17,12 @@ * 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 index 03c6f7c..0000000 --- a/resource/csdk/connectivity/inc/pkix/cert.h +++ /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 index 9f91e5a..0000000 --- a/resource/csdk/connectivity/inc/pkix/crl.h +++ /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 index bef054c..0000000 --- a/resource/csdk/connectivity/inc/pkix/crypto_adapter.h +++ /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 index b26938a..0000000 --- a/resource/csdk/connectivity/inc/pkix/der_dec.h +++ /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 index 221b6a9..0000000 --- a/resource/csdk/connectivity/inc/pkix/pki.h +++ /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 index 0d7477f..0000000 --- a/resource/csdk/connectivity/inc/pkix/pki_errors.h +++ /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 // -#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 index 50d8ff2..0000000 --- a/resource/csdk/connectivity/inc/pkix/sn_store.h +++ /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_ - diff --git a/resource/csdk/connectivity/src/SConscript b/resource/csdk/connectivity/src/SConscript index e944ce9..66b94f2 100644 --- a/resource/csdk/connectivity/src/SConscript +++ b/resource/csdk/connectivity/src/SConscript @@ -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 index 0000000..58b4633 --- /dev/null +++ b/resource/csdk/connectivity/src/adapter_util/ca_adapter_net_ssl.c @@ -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 +#include +#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 +#include +#include +#include +#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; +} diff --git a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c index 3e591fe..9e52db8 100644 --- a/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c +++ b/resource/csdk/connectivity/src/adapter_util/caadapternetdtls.c @@ -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 index 4a02949..0000000 --- a/resource/csdk/connectivity/src/adapter_util/pkix/cert.c +++ /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 index 91a7608..0000000 --- a/resource/csdk/connectivity/src/adapter_util/pkix/crl.c +++ /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 index b342918..0000000 --- a/resource/csdk/connectivity/src/adapter_util/pkix/der_const.c +++ /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 index 06e46b9..0000000 --- a/resource/csdk/connectivity/src/adapter_util/pkix/der_dec.c +++ /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 index 8d32cc9..0000000 --- a/resource/csdk/connectivity/src/adapter_util/pkix/pki.c +++ /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 -#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 index f3db429..0000000 --- a/resource/csdk/connectivity/src/adapter_util/pkix/sn_store.c +++ /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 -#include - -//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 diff --git a/resource/csdk/connectivity/src/caconnectivitymanager.c b/resource/csdk/connectivity/src/caconnectivitymanager.c index 0dc5a52..f430de2 100644 --- a/resource/csdk/connectivity/src/caconnectivitymanager.c +++ b/resource/csdk/connectivity/src/caconnectivitymanager.c @@ -31,15 +31,12 @@ #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; } diff --git a/resource/csdk/connectivity/src/ip_adapter/caipadapter.c b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c index 381b67c..42fe1a6 100644 --- a/resource/csdk/connectivity/src/ip_adapter/caipadapter.c +++ b/resource/csdk/connectivity/src/ip_adapter/caipadapter.c @@ -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 { diff --git a/resource/csdk/connectivity/src/ip_adapter/caipserver.c b/resource/csdk/connectivity/src/ip_adapter/caipserver.c index 281a618..1e2a1f9 100644 --- a/resource/csdk/connectivity/src/ip_adapter/caipserver.c +++ b/resource/csdk/connectivity/src/ip_adapter/caipserver.c @@ -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 diff --git a/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c b/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c index 082bd19..0be6df6 100644 --- a/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c +++ b/resource/csdk/connectivity/src/tcp_adapter/catcpadapter.c @@ -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) { diff --git a/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c b/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c index dfdf6a7..4cdcf9f 100644 --- a/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c +++ b/resource/csdk/connectivity/src/tcp_adapter/catcpserver.c @@ -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); diff --git a/resource/csdk/connectivity/test/SConscript b/resource/csdk/connectivity/test/SConscript index e0d4376..4baa1e8 100644 --- a/resource/csdk/connectivity/test/SConscript +++ b/resource/csdk/connectivity/test/SConscript @@ -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']) diff --git a/resource/csdk/connectivity/test/ca_api_unittest.cpp b/resource/csdk/connectivity/test/ca_api_unittest.cpp index f773e9c..c2e5fff 100644 --- a/resource/csdk/connectivity/test/ca_api_unittest.cpp +++ b/resource/csdk/connectivity/test/ca_api_unittest.cpp @@ -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 } diff --git a/resource/csdk/resource-directory/samples/SConscript b/resource/csdk/resource-directory/samples/SConscript index c3d3e5f..0e98a20 100644 --- a/resource/csdk/resource-directory/samples/SConscript +++ b/resource/csdk/resource-directory/samples/SConscript @@ -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']) diff --git a/resource/csdk/security/SConscript b/resource/csdk/security/SConscript index ca5714a..a1e5f11 100644 --- a/resource/csdk/security/SConscript +++ b/resource/csdk/security/SConscript @@ -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']) diff --git a/resource/csdk/security/include/internal/credresource.h b/resource/csdk/security/include/internal/credresource.h index 00708b1..0ba8041 100644 --- a/resource/csdk/security/include/internal/credresource.h +++ b/resource/csdk/security/include/internal/credresource.h @@ -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 * diff --git a/resource/csdk/security/include/internal/crlresource.h b/resource/csdk/security/include/internal/crlresource.h index 28ba5b1..97eb65e 100644 --- a/resource/csdk/security/include/internal/crlresource.h +++ b/resource/csdk/security/include/internal/crlresource.h @@ -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 diff --git a/resource/csdk/security/include/internal/dpairingresource.h b/resource/csdk/security/include/internal/dpairingresource.h index c69c5e6..ee158b4 100644 --- a/resource/csdk/security/include/internal/dpairingresource.h +++ b/resource/csdk/security/include/internal/dpairingresource.h @@ -76,7 +76,7 @@ OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **pay */ void DeleteDpairingBinData(OicSecDpairing_t* dpair); -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * Function to save PairingPSK. * @@ -88,7 +88,7 @@ void DeleteDpairingBinData(OicSecDpairing_t* dpair); */ OCStackResult SavePairingPSK(OCDevAddr *endpoint, OicUuid_t *peerDevID, OicUuid_t *owner, bool isPairingServer); -#endif // __WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ /** * Gets the OicUuid_t value for the rownerid of the Dpairing resource. diff --git a/resource/csdk/security/include/securevirtualresourcetypes.h b/resource/csdk/security/include/securevirtualresourcetypes.h index 2101381..de17cad 100644 --- a/resource/csdk/security/include/securevirtualresourcetypes.h +++ b/resource/csdk/security/include/securevirtualresourcetypes.h @@ -45,9 +45,9 @@ #include // for uint8_t typedef #include -#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 diff --git a/resource/csdk/security/provisioning/SConscript b/resource/csdk/security/provisioning/SConscript index e1739ec..4ef5a44 100644 --- a/resource/csdk/security/provisioning/SConscript +++ b/resource/csdk/security/provisioning/SConscript @@ -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 index a473e5e..0000000 --- a/resource/csdk/security/provisioning/ck_manager/SConscript +++ /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 index a21980f..0000000 --- a/resource/csdk/security/provisioning/ck_manager/include/cert_generator.h +++ /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 index 19b5081..0000000 --- a/resource/csdk/security/provisioning/ck_manager/include/ck_manager.h +++ /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 - -#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 index d45be77..0000000 --- a/resource/csdk/security/provisioning/ck_manager/include/ckm_info.h +++ /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 -#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 index dfdec1c..0000000 --- a/resource/csdk/security/provisioning/ck_manager/include/crl_generator.h +++ /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 index e1f0870..0000000 --- a/resource/csdk/security/provisioning/ck_manager/include/csr_generator.h +++ /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 index 4f5db19..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp +++ /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 -#include -#include -#include -#include -#include -#include -#include -#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(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 (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 index 2a9b176..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/Light_sample.cpp +++ /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 -#include -#include -#include -#include -#include -#include -#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(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 index 6378d5e..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/README.txt +++ /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 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 index 6dcbdbf..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "acl": { - "aclist": { - "aces": [ - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/res", - "rel": "", - "rt": ["oic.wk.res"], - "if": ["oic.if.ll"] - },{ - "href": "/oic/d", - "rel": "", - "rt": ["oic.wk.d"], - "if": ["oic.if.baseline", "oic.if.r"] - },{ - "href": "/oic/p", - "rel": "", - "rt": ["oic.wk.p"], - "if": ["oic.if.baseline", "oic.if.r"] - } - ], - "permission": 2 - }, - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/sec/doxm", - "rel": "", - "rt": ["oic.r.doxm"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/pstat", - "rel": "", - "rt": ["oic.r.pstat"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/acl", - "rel": "", - "rt": ["oic.r.acl"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/cred", - "rel": "", - "rt": ["oic.r.cred"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/crl", - "rel": "", - "rt": ["oic.r.crl"], - "if": ["oic.if.baseline"] - } - ], - "permission": 6 - } - ] - }, - "rowneruuid" : "646F6F72-4465-7669-6365-555549443030" - }, - "pstat": { - "isop": false, - "deviceuuid": "646F6F72-4465-7669-6365-555549443030", - "rowneruuid": "646F6F72-4465-7669-6365-555549443030", - "cm": 2, - "tm": 0, - "om": 3, - "sm": 3 - }, - "doxm": { - "oxms": [0], - "oxmsel": 0, - "sct": 1, - "owned": false, - "deviceuuid": "646F6F72-4465-7669-6365-555549443030", - "rowneruuid": "646F6F72-4465-7669-6365-555549443030", - "x.org.iotivity.dpc": false - } -} 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 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 index 0bf4375..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "acl": { - "aclist": { - "aces": [ - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/res", - "rel": "", - "rt": ["oic.wk.res"], - "if": ["oic.if.ll"] - },{ - "href": "/oic/d", - "rel": "", - "rt": ["oic.wk.d"], - "if": ["oic.if.baseline", "oic.if.r"] - },{ - "href": "/oic/p", - "rel": "", - "rt": ["oic.wk.p"], - "if": ["oic.if.baseline", "oic.if.r"] - } - ], - "permission": 2 - }, - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/sec/doxm", - "rel": "", - "rt": ["oic.r.doxm"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/pstat", - "rel": "", - "rt": ["oic.r.pstat"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/acl", - "rel": "", - "rt": ["oic.r.acl"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/cred", - "rel": "", - "rt": ["oic.r.cred"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/crl", - "rel": "", - "rt": ["oic.r.crl"], - "if": ["oic.if.baseline"] - } - ], - "permission": 6 - } - ] - }, - "rowneruuid" : "6C696768-7444-6576-6963-655555494430" - }, - "pstat": { - "isop": false, - "deviceuuid": "6C696768-7444-6576-6963-655555494430", - "rowneruuid": "6C696768-7444-6576-6963-655555494430", - "cm": 2, - "tm": 0, - "om": 3, - "sm": 3 - }, - "doxm": { - "oxms": [0], - "oxmsel": 0, - "sct": 1, - "owned": false, - "deviceuuid": "6C696768-7444-6576-6963-655555494430", - "rowneruuid": "6C696768-7444-6576-6963-655555494430", - "x.org.iotivity.dpc": false - } -} 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 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 index f13ed08..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "acl": { - "aclist": { - "aces": [ - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/res", - "rel": "", - "rt": ["oic.wk.res"], - "if": ["oic.if.ll"] - },{ - "href": "/oic/d", - "rel": "", - "rt": ["oic.wk.d"], - "if": ["oic.if.baseline", "oic.if.r"] - },{ - "href": "/oic/p", - "rel": "", - "rt": ["oic.wk.p"], - "if": ["oic.if.baseline", "oic.if.r"] - } - ], - "permission": 2 - }, - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/sec/doxm", - "rel": "", - "rt": ["oic.r.doxm"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/pstat", - "rel": "", - "rt": ["oic.r.pstat"], - "if": ["oic.if.baseline"] - } - ], - "permission": 2 - } - ] - }, - "rowneruuid" : "61646D69-6E44-6576-6963-655555494430" - }, - "pstat": { - "isop": true, - "deviceuuid": "61646D69-6E44-6576-6963-655575696430", - "rowneruuid": "61646D69-6E44-6576-6963-655575696430", - "cm": 2, - "tm": 0, - "om": 3, - "sm": 3 - }, - "doxm": { - "oxms": [0], - "oxmsel": 0, - "sct": 1, - "owned": true, - "deviceuuid": "61646D69-6E44-6576-6963-655575696430", - "devowneruuid": "61646D69-6E44-6576-6963-655575696430", - "rowneruuid": "61646D69-6E44-6576-6963-655575696430", - "x.org.iotivity.dpc": false - } -} \ 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 index 7784088..0000000 --- a/resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c +++ /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 -#include -#include - -#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 *arr, bool hasError) -{ - if(!hasError) - { - gOwnershipState = 1; - PrintfResult("Provision Credential", ctx, nOfRes, arr, hasError); - } - else printf("Cert provisioning error\n-----------------------------------------"); -} - -void ProvisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError) -{ - if(!hasError) - { - gOwnershipState = 1; - PrintfResult("Provision ACL", ctx, nOfRes, arr, hasError); - } -} - -void ProvisionCrlCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError) -{ - if(!hasError) - { - gOwnershipState = 1; - PrintfResult("Provision CRL", ctx, nOfRes, arr, hasError); - } -} - - - -void OwnershipTransferCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError) -{ - if(!hasError) - { - gOwnershipState = 1; - PrintfResult("Ownership transfer", ctx, nOfRes, arr, hasError); - } -} - -static short IsCKMInfoFileExists() -{ - FILE *ckmInf = fopen(CA_STORAGE_FILE, "r"); - if (NULL != ckmInf) - { - fclose(ckmInf); - return 1; - } - return 0; -} - -static PKIError InitCA() -{ - FUNCTION_INIT(); - - if (IsCKMInfoFileExists()) - { - CHECK_CALL(InitCKMInfo); - } - else - { - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - ByteArray CAPubKey = BYTE_ARRAY_INITIALIZER; - ByteArray CAPrivKey = BYTE_ARRAY_INITIALIZER; - ByteArray rootCert = BYTE_ARRAY_INITIALIZER; - - - uint8_t rootCertData[ISSUER_MAX_CERT_SIZE]; - uint8_t CAPubKeyData[PUBLIC_KEY_SIZE]; - uint8_t CAPrivKeyData[PRIVATE_KEY_SIZE]; - const char rootNameStr[] = "Sample_Root"; - - CAPubKey.data = CAPubKeyData; - CAPubKey.len = PUBLIC_KEY_SIZE; - CAPrivKey.data = CAPrivKeyData; - CAPrivKey.len = PRIVATE_KEY_SIZE; - rootCert.data = rootCertData; - rootCert.len = ISSUER_MAX_CERT_SIZE; - rootName.data = (uint8_t *)rootNameStr; - rootName.len = strlen(rootNameStr); - - CHECK_CALL(SetRootName, rootName); - CHECK_CALL(GenerateCAKeyPair, &CAPrivKey, &CAPubKey); - CHECK_CALL(SetSerialNumber, 1); - CHECK_CALL(CKMIssueRootCertificate, NULL, NULL, &rootCert); - CHECK_CALL(SetCACertificate, &rootCert); - } - - FUNCTION_CLEAR(); -} - -static int InputCRL(OicSecCrl_t *crlRes) -{ - FUNCTION_INIT( - ByteArray crl = BYTE_ARRAY_INITIALIZER; - ); - - const int MAX_Revoked_NUMBER = 9; - uint8_t uint8ThisUpdateTime[DATE_LENGTH] = "130101000005Z"; - uint32_t revokedNumbers[MAX_Revoked_NUMBER]; - const uint8_t* revocationDates[MAX_Revoked_NUMBER]; - // const uint8_t revocationDatesContent[MAX_Revoked_NUMBER][DATE_LENGTH]; - uint32_t nuberOfRevoked = 0; - printf("Enter number of Revoked certificates(1..%d)\n", MAX_Revoked_NUMBER); - int ret = 0; - ret = scanf("%u", &nuberOfRevoked); - if(-1 == ret) - { - printf("Error while input\n"); - return PKI_UNKNOWN_ERROR; - } - - if((uint32_t)MAX_Revoked_NUMBER < nuberOfRevoked) - { - OIC_LOG(ERROR, TAG, "Wrong revoked certificate number"); - return PKI_UNKNOWN_ERROR; - } - - for (size_t i = 0; i < nuberOfRevoked; ++i) - { - printf("Revoked certificate %d:", i); - printf("Serial number (E. g.: 100):"); - ret = scanf("%u", &revokedNumbers[i]); - if(-1 == ret) - { - printf("Error while input\n"); - return PKI_UNKNOWN_ERROR; - } - - revocationDates[i] = (const uint8_t*)"130101000005Z"; - } - - crl.len = CRL_MIN_SIZE + nuberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)/* + 1000*/; - crl.data = (uint8_t *)OICCalloc(1, crl.len); - - if (NULL == crl.data) - { - OIC_LOG(ERROR, TAG, "Error while memory allocation"); - return PKI_MEMORY_ALLOC_FAILED; - } - - CHECK_CALL(CKMIssueCRL, uint8ThisUpdateTime, nuberOfRevoked, revokedNumbers, - revocationDates, &crl); - PRINT_BYTE_ARRAY("CRL:\n",crl); - CHECK_CALL(SetCertificateRevocationList, &crl); - crlRes->CrlData = crl; - crlRes->ThisUpdate.data = OICStrdup(uint8ThisUpdateTime); - crlRes->ThisUpdate.len = DATE_LENGTH; - crlRes->CrlId = 1; - - if(NULL == crlRes->ThisUpdate.data) - { - printf("OICStrdup failed\n"); - return PKI_MEMORY_ALLOC_FAILED; - } - - FUNCTION_CLEAR( - //OICFree(crl.data); - ); -} - - -/** - * Provisioning client sample using ProvisioningAPI - */ -int main() -{ - OCStackResult res = OC_STACK_OK; - OCProvisionDev_t* pDeviceList = NULL; - OCProvisionDev_t *pOwnedList = NULL; - - // Initialize Persistent Storage for SVR database - OCPersistentStorage ps = { .open = client_fopen, - .read = fread, - .write = fwrite, - .close = fclose, - .unlink = unlink}; - - OCRegisterPersistentStorageHandler(&ps); - - if (OC_STACK_OK != OCInit(NULL, 0, OC_CLIENT_SERVER)) - { - OIC_LOG(ERROR, TAG, "OCStack init error"); - goto error; - } - if(OC_STACK_OK != OCInitPM(PRVN_DB_FILE_NAME)) - { - OIC_LOG(ERROR, TAG, "OC_PM init error"); - goto error; - } - - res = OCDiscoverUnownedDevices(PREDEFINED_TIMEOUT, &pDeviceList); - if(OC_STACK_OK != res) - { - OIC_LOG_V(ERROR, TAG, "Failed to PMDeviceDiscovery : %d", res); - goto error; - } - - OCProvisionDev_t* pCurDev = pDeviceList; - int i; - while(pCurDev !=NULL) - { - for(i = 0; i < UUID_LENGTH; i++) - { - printf("%c", pCurDev->doxm->deviceID.id[i]); - } - printf("\n"); - pCurDev = pCurDev->next; - } - - //Register callback function to each OxM - OTMCallbackData_t justWorksCBData = {.loadSecretCB=NULL, - .createSecureSessionCB=NULL, - .createSelectOxmPayloadCB=NULL, - .createOwnerTransferPayloadCB=NULL}; - justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback; - justWorksCBData.createSecureSessionCB = CreateSecureSessionJustWorksCallback; - justWorksCBData.createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload; - justWorksCBData.createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload; - OTMSetOwnershipTransferCallbackData(OIC_JUST_WORKS, &justWorksCBData); - - char* myContext = "OTM Context"; - //Perform ownership transfer - res = OCDoOwnershipTransfer((void*)myContext, pDeviceList, OwnershipTransferCB); - if(OC_STACK_OK == res) - { - OIC_LOG(INFO, TAG, "Request for ownership transfer is sent successfully."); - } - else - { - OIC_LOG_V(ERROR, TAG, "Failed to OCDoOwnershipTransfer : %d", res); - } - - gOwnershipState = 0; - while (gOwnershipState == 0) - { - if (OCProcess() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - goto error; - } - sleep(1); - } - -// Credential & ACL provisioning between two devices. - - OCProvisionDev_t *pOwnedDevices [MAX_OWNED_DEVICE] = {0,}; - int nOwnedDevice = 0; - - res = OCDiscoverOwnedDevices(PREDEFINED_TIMEOUT, &pOwnedList); - if (OC_STACK_OK == res) - { - printf("################## Owned Device List #######################\n"); - while (pOwnedList != NULL) - { - nOwnedDevice ++; - printf(" %d : ", nOwnedDevice); - for (int i = 0; i < UUID_LENGTH; i++) - { - printf("%c", pOwnedList->doxm->deviceID.id[i]); - } - printf("\n"); - pOwnedDevices[nOwnedDevice] = pOwnedList; - pOwnedList = pOwnedList->next; - } - } - else - { - OIC_LOG(ERROR, TAG, "Error while Owned Device Discovery"); - } - - int Device1 = 0; - int Device2 = 0; - int ret = 0; - - printf("Select 2 devices for Credential & ACL provisioning\n"); - printf("Device 1: "); - ret = scanf("%d", &Device1); - if(-1 == ret) - { - printf("Error while input\n"); - goto error; - } - - printf("Device 2: "); - ret = scanf("%d", &Device2); - if(-1 == ret) - { - printf("Error while input\n"); - goto error; - } - - if( 0 > Device1 || 0 > Device2 || Device1 > nOwnedDevice || Device2 > nOwnedDevice) - { - OIC_LOG(ERROR, TAG, "Wrong devices number"); - goto error; - } - - gAcl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t)); - if (NULL == gAcl) - { - OIC_LOG(ERROR, TAG, "Error while memory allocation"); - goto error; - } - - if (PKI_SUCCESS != InitCA()) - { - OIC_LOG(ERROR, TAG, "CA init error"); - goto error; - } - - - char *ctx = "DUMMY"; - - res = OCProvisionCredentials(ctx, SIGNED_ASYMMETRIC_KEY, 0, pOwnedDevices[Device1], - NULL, ProvisionCertCB); - if (OC_STACK_OK != res) OIC_LOG_V(ERROR, TAG, "Failed to provision Device 1 : %d", res); - gOwnershipState = 0; - while ( gOwnershipState == 0 ) - { - if (OCProcess() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - goto error; - } - sleep(1); - } - - res = OCProvisionCredentials(ctx, SIGNED_ASYMMETRIC_KEY, 0, pOwnedDevices[Device2], - NULL, ProvisionCertCB); - if (OC_STACK_OK != res) - { - OIC_LOG_V(ERROR, TAG, "Failed to provision Device 2 : %d", res); - } - - gOwnershipState = 0; - while (gOwnershipState == 0) - { - if (OCProcess() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - goto error; - } - sleep(1); - } - - printf("Input ACL for Device2\n"); - if (0 == InputACL(gAcl)) - { - printf("Success Input ACL\n"); - } - else - { - OIC_LOG(ERROR, TAG, "InputACL error"); - goto error; - } - res = OCProvisionACL(ctx, pOwnedDevices[Device2], gAcl, &ProvisionAclCB); - if (OC_STACK_OK != res) - { - OIC_LOG_V(ERROR, TAG, "Failed to ACL provision Device 2 : %d", res); - } - - gOwnershipState = 0; - while (gOwnershipState == 0) - { - if (OCProcess() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - goto error; - } - sleep(1); - } - gCrl = (OicSecCrl_t *)OICMalloc(sizeof(OicSecCrl_t)); - - if (NULL == gCrl) - { - OIC_LOG(ERROR, TAG, "Error while memory allocation"); - goto error; - } - - if (PKI_SUCCESS != InputCRL(gCrl)) - { - OIC_LOG(ERROR, TAG, "CA init error"); - goto error; - } - - PRINT_BYTE_ARRAY("gCrl = \n", gCrl->CrlData); - - res = OCProvisionCRL(ctx, pOwnedDevices[Device2], gCrl, &ProvisionCrlCB); - if (OC_STACK_OK != res) OIC_LOG_V(ERROR, TAG, "Failed to CRL provision Device 2 : %d", res); - - gOwnershipState = 0; - while (gOwnershipState == 0) - { - if (OCProcess() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - goto error; - } - sleep(1); - } - - if (OCStop() != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack process error"); - goto error; - } - -error: - DeleteACLList(gAcl); - deleteCrl(gCrl); - OCDeleteDiscoveredDevices(pDeviceList); - OCDeleteDiscoveredDevices(pOwnedList); - - return 0; -} diff --git a/resource/csdk/security/provisioning/ck_manager/src/cert_generator.c b/resource/csdk/security/provisioning/ck_manager/src/cert_generator.c deleted file mode 100644 index dd02862..0000000 --- a/resource/csdk/security/provisioning/ck_manager/src/cert_generator.c +++ /dev/null @@ -1,246 +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 "cert_generator.h" -#include "ckm_info.h" -#include "pki.h" -#include "oic_malloc.h" - -//ecdsa-with-SHA256 1.2.840.10045.4.3.2 [RFC5759] -static const uint8_t g_ECDSA_WITH_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02}; - -//Elliptic Curve Digital Signature Algorithm (ECDSA) 1.2.840.10045.2.1 [RFC7250] -static const uint8_t g_EC_PUBLIC_KEY_OID[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01}; - -//secp256r1 1.2.840.10045.3.1.7 [RFC5656] -static const uint8_t g_PRIME_256_V1_OID[] = {0x2A, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}; - -//commonName 2.5.4.3 [RFC2256] -static const uint8_t g_COMMON_NAME_OID[] = {0x55, 0x04, 0x03}; - - -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) -{ - FUNCTION_INIT(); - asn_enc_rval_t ec; /* Encoder return value */ - Certificate_t *certificate = NULL; /* Type to encode */ - AttributeTypeAndValue_t *issuerTypeAndValue = NULL; - AttributeTypeAndValue_t *subjectTypeAndValue = NULL; - RelativeDistinguishedName_t *issuerRDN = NULL; - RelativeDistinguishedName_t *subjectRDN = NULL; - uint8_t *uint8Pointer = NULL; - ByteArray tbs = BYTE_ARRAY_INITIALIZER; - uint8_t signature[SIGN_FULL_SIZE]; - uint8_t sha256[SHA_256_HASH_LEN]; - uint8_t tbsDer[ISSUER_MAX_CERT_SIZE]; - long serialNumber = 0; - - CHECK_NULL(subjectName, ISSUER_X509_NULL_PASSED); - CHECK_NULL(issuerName, ISSUER_X509_NULL_PASSED); - CHECK_NULL(notBefore, ISSUER_X509_NULL_PASSED); - CHECK_NULL(notAfter, ISSUER_X509_NULL_PASSED); - CHECK_NULL(subjectPublicKey, ISSUER_X509_NULL_PASSED); - CHECK_NULL(issuerPrivateKey, ISSUER_X509_NULL_PASSED); - CHECK_NULL_BYTE_ARRAY_PTR(encodedCertificate, ISSUER_X509_NULL_PASSED); - CHECK_LESS_EQUAL(ISSUER_MAX_CERT_SIZE, encodedCertificate->len, - ISSUER_X509_WRONG_BYTE_ARRAY_LEN); - - /* Allocate the memory */ - certificate = OICCalloc(1, sizeof(Certificate_t)); // not malloc! - CHECK_NULL(certificate, ISSUER_X509_MEMORY_ALLOC_FAILED); - - issuerTypeAndValue = OICCalloc(1, sizeof(AttributeTypeAndValue_t)); - CHECK_NULL(issuerTypeAndValue, ISSUER_X509_MEMORY_ALLOC_FAILED); - - issuerRDN = OICCalloc(1, sizeof(RelativeDistinguishedName_t)); - CHECK_NULL(issuerRDN, ISSUER_X509_MEMORY_ALLOC_FAILED); - - subjectTypeAndValue = OICCalloc(1, sizeof(AttributeTypeAndValue_t)); - CHECK_NULL(subjectTypeAndValue, ISSUER_X509_MEMORY_ALLOC_FAILED); - - subjectRDN = OICCalloc(1, sizeof(RelativeDistinguishedName_t)); - CHECK_NULL(subjectRDN, ISSUER_X509_MEMORY_ALLOC_FAILED); - - //set issuer name - issuerTypeAndValue->value = *issuerName; - issuerTypeAndValue->type.buf = (uint8_t *)g_COMMON_NAME_OID; //2.5.4.3 - issuerTypeAndValue->type.size = sizeof(g_COMMON_NAME_OID) / sizeof(g_COMMON_NAME_OID[0]); - ASN_SET_ADD(issuerRDN, issuerTypeAndValue); - ASN_SEQUENCE_ADD(&(certificate->tbsCertificate.issuer), issuerRDN); - - //set subject name - subjectTypeAndValue->value = *subjectName; - subjectTypeAndValue->type.buf = (uint8_t *)g_COMMON_NAME_OID; //2.5.4.3 - subjectTypeAndValue->type.size = sizeof(g_COMMON_NAME_OID) / sizeof(g_COMMON_NAME_OID[0]); - ASN_SET_ADD(subjectRDN, subjectTypeAndValue); - ASN_SEQUENCE_ADD(&(certificate->tbsCertificate.subject), subjectRDN); - - //set validity - certificate->tbsCertificate.validity.notBefore = *notBefore; - certificate->tbsCertificate.validity.notAfter = *notAfter; - - //set X.509 certificate version - certificate->tbsCertificate.version = X509_V2; - - //set serial number - certificate->tbsCertificate.serialNumber = 0; - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetNextSerialNumber, &serialNumber); - certificate->tbsCertificate.serialNumber = serialNumber; - serialNumber++; - CHECK_CALL(SetNextSerialNumber, serialNumber); - CHECK_CALL(SaveCKMInfo); - - //set signature algorithm in TBS - certificate->tbsCertificate.signature.algorithm.buf = - (uint8_t *)g_ECDSA_WITH_SHA256_OID; //1.2.840.10045.4.3.2 - certificate->tbsCertificate.signature.algorithm.size = - sizeof(g_ECDSA_WITH_SHA256_OID) / sizeof(g_ECDSA_WITH_SHA256_OID[0]); - certificate->tbsCertificate.signature.nul = OICCalloc(1, sizeof(NULL_t)); - CHECK_NULL(certificate->tbsCertificate.signature.nul, ISSUER_X509_MEMORY_ALLOC_FAILED); - - //set subject Public Key algorithm - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm.buf = - (uint8_t *)g_EC_PUBLIC_KEY_OID; //1.2.840.10045.2.1 - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm.size = - sizeof(g_EC_PUBLIC_KEY_OID) / sizeof(g_EC_PUBLIC_KEY_OID[0]); - - //set subject Public Key curve - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey = - OICCalloc(1, sizeof(OBJECT_IDENTIFIER_t)); - CHECK_NULL(certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey, - ISSUER_X509_MEMORY_ALLOC_FAILED); - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey->buf = - (uint8_t *)g_PRIME_256_V1_OID; //1.2.840.10045.3.1.7 - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey->size = - sizeof(g_PRIME_256_V1_OID) / sizeof(g_PRIME_256_V1_OID[0]); - - //set subject Public Key - certificate->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey = *subjectPublicKey; - - //set signature algorithm - certificate->signatureAlgorithm.algorithm.buf = (uint8_t *)g_ECDSA_WITH_SHA256_OID; - certificate->signatureAlgorithm.algorithm.size = - sizeof(g_ECDSA_WITH_SHA256_OID) / sizeof(g_ECDSA_WITH_SHA256_OID[0]); - certificate->signatureAlgorithm.nul = OICCalloc(1, sizeof(NULL_t)); - CHECK_NULL(certificate->signatureAlgorithm.nul, ISSUER_X509_MEMORY_ALLOC_FAILED); - - //encode TBS to DER - ec = der_encode_to_buffer(&asn_DEF_TBSCertificate, &(certificate->tbsCertificate), - tbsDer, ISSUER_MAX_CERT_SIZE); - CHECK_COND(ec.encoded > 0, ISSUER_X509_DER_ENCODE_FAIL); - tbs.len = ec.encoded; - tbs.data = tbsDer; - GET_SHA_256(tbs, sha256); - CHECK_COND(uECC_sign((issuerPrivateKey->buf) + 1, sha256, signature), - ISSUER_X509_SIGNATURE_FAIL); - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - - // ECDSA-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } (RFC 5480) - certificate->signatureValue.size = SIGN_FULL_SIZE + 6;// size for SEQUENCE ID + 2 * INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[0] > 127) - { - certificate->signatureValue.size ++; - } - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[SIGN_R_LEN] > 127) - { - certificate->signatureValue.size ++; - } - certificate->signatureValue.buf = OICCalloc(certificate->signatureValue.size, sizeof(uint8_t)); - CHECK_NULL(certificate->signatureValue.buf, ISSUER_X509_MEMORY_ALLOC_FAILED); - *(certificate->signatureValue.buf) = (12 << 2); //ASN.1 SEQUENCE ID - *(certificate->signatureValue.buf + 1) = certificate->signatureValue.size - 2; - //ASN.1 SEQUENCE size - - uint8Pointer = certificate->signatureValue.buf + 2; //skip SEQUENCE ID and size - *uint8Pointer = (2 << 0); //ASN.1 INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[0] > 127) - { - *(uint8Pointer + 1) = SIGN_R_LEN + 1; //ASN.1 INTEGER size - uint8Pointer += 3; //skip INTEGER ID and size - } - else - { - *(uint8Pointer + 1) = SIGN_R_LEN; //ASN.1 INTEGER SIZE - uint8Pointer += 2; //skip INTEGER ID and size - } - memcpy(uint8Pointer, signature, SIGN_R_LEN); - - uint8Pointer += SIGN_R_LEN; //skip first part of signature - *uint8Pointer = (2 << 0); //ASN.1 INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature [SIGN_R_LEN] > 127) - { - *(uint8Pointer + 1) = SIGN_S_LEN + 1; //ASN.1 INTEGER size - uint8Pointer += 3; //skip INTEGER ID and size - } - else - { - *(uint8Pointer + 1) = SIGN_S_LEN; //ASN.1 INTEGER size - uint8Pointer += 2; //skip INTEGER ID and size - } - memcpy(uint8Pointer, signature + SIGN_R_LEN, SIGN_S_LEN); - - ec = der_encode_to_buffer(&asn_DEF_Certificate, certificate, - encodedCertificate->data, ISSUER_MAX_CERT_SIZE); - CHECK_COND(ec.encoded > 0, ISSUER_X509_DER_ENCODE_FAIL); - encodedCertificate->len = ec.encoded; - - FUNCTION_CLEAR( - if (issuerTypeAndValue) - { - issuerTypeAndValue->value.buf = NULL; - issuerTypeAndValue->type.buf = NULL; - } - if (subjectTypeAndValue) - { - subjectTypeAndValue->value.buf = NULL; - subjectTypeAndValue->type.buf = NULL; - } - if (certificate) - { - certificate->tbsCertificate.validity.notBefore.buf = NULL; - certificate->tbsCertificate.validity.notAfter.buf = NULL; - certificate->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.buf = NULL; - certificate->tbsCertificate.signature.algorithm.buf = NULL; - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm.buf = NULL; - if (certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey) - { - certificate->tbsCertificate.subjectPublicKeyInfo.algorithm.id_ecPublicKey->buf = NULL; - } - certificate->signatureAlgorithm.algorithm.buf = NULL; - } - ASN_STRUCT_FREE(asn_DEF_Certificate, certificate); - certificate = NULL; - ); -} diff --git a/resource/csdk/security/provisioning/ck_manager/src/ck_manager.c b/resource/csdk/security/provisioning/ck_manager/src/ck_manager.c deleted file mode 100644 index ade8815..0000000 --- a/resource/csdk/security/provisioning/ck_manager/src/ck_manager.c +++ /dev/null @@ -1,702 +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 "ck_manager.h" -#include "crlresource.h" -#include "oic_malloc.h" - -#ifdef __unix__ -#include -#include -#include -#endif // __unix__ - -/* 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_ID (0x04) - -PKIError GenerateCAKeyPair (ByteArray *caPrivateKey, ByteArray *caPublicKey) -{ - FUNCTION_INIT(); - - CHECK_NULL(caPrivateKey, ISSUER_NULL_PASSED); - CHECK_NULL(caPrivateKey->data, ISSUER_NULL_PASSED); - CHECK_NULL(caPublicKey, ISSUER_NULL_PASSED); - CHECK_NULL(caPublicKey->data, ISSUER_NULL_PASSED); - - CHECK_COND(uECC_make_key(caPublicKey->data, caPrivateKey->data), ISSUER_MAKE_KEY_ERROR); - caPublicKey->len = PUBLIC_KEY_SIZE; - caPrivateKey->len = PRIVATE_KEY_SIZE; - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(SetCAPrivateKey, caPrivateKey); - CHECK_CALL(SetCAPublicKey, caPublicKey); - CHECK_CALL(SaveCKMInfo); - FUNCTION_CLEAR(); -} - -PKIError CKMIssueRootCertificate (const uint8_t *uint8NotBefore, const uint8_t *uint8NotAfter, - ByteArray *issuedRootCertificate) -{ - FUNCTION_INIT(); - - UTF8String_t *rootName = NULL; - UTCTime_t *notBefore = NULL; - UTCTime_t *notAfter = NULL; - BIT_STRING_t *subjectPublicKey = NULL; - BIT_STRING_t *issuerPrivateKey = NULL; - - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray caName = BYTE_ARRAY_INITIALIZER; - - uint8_t caPublicKey[PUBLIC_KEY_SIZE]; - uint8_t caPrivateKey[PRIVATE_KEY_SIZE]; - uint8_t uint8caName[ISSUER_MAX_NAME_SIZE]; - - CHECK_NULL(issuedRootCertificate, ISSUER_NULL_PASSED); - CHECK_NULL(issuedRootCertificate->data, ISSUER_NULL_PASSED); - CHECK_LESS_EQUAL(ISSUER_MAX_CERT_SIZE, issuedRootCertificate->len, ISSUER_WRONG_BYTE_ARRAY_LEN); - - pubKeyIss.data = caPublicKey; - pubKeyIss.len = PUBLIC_KEY_SIZE; - privKeyIss.data = caPrivateKey; - privKeyIss.len = PRIVATE_KEY_SIZE; - caName.data = uint8caName; - caName.len = ISSUER_MAX_NAME_SIZE; - - rootName = (UTF8String_t *)OICCalloc(1, sizeof(UTF8String_t)); - CHECK_NULL(rootName, ISSUER_MEMORY_ALLOC_FAILED); - - notBefore = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t)); - CHECK_NULL(notBefore, ISSUER_MEMORY_ALLOC_FAILED); - - notAfter = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t)); - CHECK_NULL(notAfter, ISSUER_MEMORY_ALLOC_FAILED); - - subjectPublicKey = (BIT_STRING_t *)OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(subjectPublicKey, ISSUER_MEMORY_ALLOC_FAILED); - - issuerPrivateKey = (BIT_STRING_t *)OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(issuerPrivateKey, ISSUER_MEMORY_ALLOC_FAILED); - - //RootName - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAName, &caName); - rootName->buf = caName.data; - rootName->size = caName.len; - - //notBefore - if (uint8NotBefore) - { - notBefore->buf = (uint8_t *)uint8NotBefore; - } - else - { - notBefore->buf = (uint8_t *)ISSUER_DEFAULT_NOT_BEFORE; - } - notBefore->size = strlen((const char *)notBefore->buf); - - //notAfter - if (uint8NotAfter) - { - notAfter->buf = (uint8_t *)uint8NotAfter; - } - else - { - notAfter->buf = (uint8_t *)ISSUER_DEFAULT_NOT_AFTER; - } - notAfter->size = strlen((const char *)notAfter->buf); - - //common keys - issuerPrivateKey->size = PRIVATE_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - issuerPrivateKey->buf = (uint8_t *)OICCalloc((issuerPrivateKey->size), sizeof(uint8_t)); - CHECK_NULL(issuerPrivateKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(issuerPrivateKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - - subjectPublicKey->size = PUBLIC_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - subjectPublicKey->buf = (uint8_t *)OICCalloc(subjectPublicKey->size, sizeof(uint8_t)); - CHECK_NULL(subjectPublicKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(subjectPublicKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - //common keys - - //read CA key pair from the CA storage - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAPrivateKey, &privKeyIss); - - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((issuerPrivateKey->buf) + 1, privKeyIss.data, PRIVATE_KEY_SIZE); - CHECK_CALL(GetCAPublicKey, &pubKeyIss); - - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((subjectPublicKey->buf) + 1, pubKeyIss.data, PUBLIC_KEY_SIZE); - - CHECK_CALL(GenerateCertificate, rootName, rootName, notBefore, notAfter, - subjectPublicKey, issuerPrivateKey, issuedRootCertificate); - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(SetCACertificate, issuedRootCertificate); - CHECK_CALL(SaveCKMInfo); - - FUNCTION_CLEAR( - OICFree(rootName); - OICFree(notBefore); - OICFree(notAfter); - ASN_STRUCT_FREE(asn_DEF_BIT_STRING, subjectPublicKey); - ASN_STRUCT_FREE(asn_DEF_BIT_STRING, issuerPrivateKey); - ); -} - -PKIError GenerateKeyPair (ByteArray *privateKey, ByteArray *publicKey) -{ - FUNCTION_INIT(); - CHECK_NULL(privateKey, ISSUER_NULL_PASSED); - CHECK_NULL(privateKey->data, ISSUER_NULL_PASSED); - CHECK_NULL(publicKey, ISSUER_NULL_PASSED); - CHECK_NULL(publicKey->data, ISSUER_NULL_PASSED); - CHECK_COND(uECC_make_key(publicKey->data, privateKey->data), ISSUER_MAKE_KEY_ERROR); - publicKey->len = PUBLIC_KEY_SIZE; - privateKey->len = PRIVATE_KEY_SIZE; - FUNCTION_CLEAR(); -} - -PKIError CKMIssueDeviceCertificate (const uint8_t *uint8SubjectName, - const uint8_t *uint8NotBefore, const uint8_t *uint8NotAfter, - const uint8_t *uint8SubjectPublicKey, - ByteArray *issuedCertificate) -{ - FUNCTION_INIT(); - - UTF8String_t *subjectName = NULL; - UTF8String_t *issuerName = NULL; - UTCTime_t *notBefore = NULL; - UTCTime_t *notAfter = NULL; - BIT_STRING_t *subjectPublicKey = NULL; - BIT_STRING_t *issuerPrivateKey = NULL; - - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray caName = BYTE_ARRAY_INITIALIZER; - - uint8_t subjPubKey[PUBLIC_KEY_SIZE]; - uint8_t subjPrivKey[PRIVATE_KEY_SIZE]; - uint8_t caPrivateKey[PRIVATE_KEY_SIZE]; - uint8_t uint8caName[ISSUER_MAX_NAME_SIZE]; - - CHECK_NULL(issuedCertificate, ISSUER_NULL_PASSED); - CHECK_NULL(issuedCertificate->data, ISSUER_NULL_PASSED); - CHECK_LESS_EQUAL(ISSUER_MAX_CERT_SIZE, issuedCertificate->len, ISSUER_WRONG_BYTE_ARRAY_LEN); - - privKeyIss.data = caPrivateKey; - privKeyIss.len = PRIVATE_KEY_SIZE; - pubKeySubj.data = subjPubKey; - pubKeySubj.len = PUBLIC_KEY_SIZE; - privKeySubj.data = subjPrivKey; - privKeySubj.len = PRIVATE_KEY_SIZE; - caName.data = uint8caName; - caName.len = ISSUER_MAX_NAME_SIZE; - - subjectName = (UTF8String_t *)OICCalloc(1, sizeof(UTF8String_t)); - CHECK_NULL(subjectName, ISSUER_MEMORY_ALLOC_FAILED); - - issuerName = (UTF8String_t *)OICCalloc(1, sizeof(UTF8String_t)); - CHECK_NULL(issuerName, ISSUER_MEMORY_ALLOC_FAILED); - - notBefore = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t)); - CHECK_NULL(notBefore, ISSUER_MEMORY_ALLOC_FAILED); - - notAfter = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t)); - CHECK_NULL(notAfter, ISSUER_MEMORY_ALLOC_FAILED); - - subjectPublicKey = (BIT_STRING_t *)OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(subjectPublicKey, ISSUER_MEMORY_ALLOC_FAILED); - - issuerPrivateKey = (BIT_STRING_t *)OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(issuerPrivateKey, ISSUER_MEMORY_ALLOC_FAILED); - - //SubjectName - if (uint8SubjectName) - { - subjectName->buf = (uint8_t *)uint8SubjectName; - } - else - { - subjectName->buf = (uint8_t *)ISSUER_DEFAULT_SUBJECT_NAME; - } - subjectName->size = strlen((const char *)subjectName->buf); - - //IssuerName - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAName, &caName); - issuerName->buf = caName.data; - issuerName->size = caName.len; - - //notBefore - if (uint8NotBefore) - { - notBefore->buf = (uint8_t *)uint8NotBefore; - } - else - { - notBefore->buf = (uint8_t *)ISSUER_DEFAULT_NOT_BEFORE; - } - notBefore->size = strlen((const char *)notBefore->buf); - - //notAfter - if (uint8NotAfter) - { - notAfter->buf = (uint8_t *)uint8NotAfter; - } - else - { - notAfter->buf = (uint8_t *)ISSUER_DEFAULT_NOT_AFTER; - } - notAfter->size = strlen((const char *)notAfter->buf); - - //common keys - issuerPrivateKey->size = PRIVATE_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - issuerPrivateKey->buf = (uint8_t *)OICCalloc((issuerPrivateKey->size), sizeof(uint8_t)); - CHECK_NULL(issuerPrivateKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(issuerPrivateKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - - subjectPublicKey->size = PUBLIC_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - subjectPublicKey->buf = (uint8_t *)OICCalloc(subjectPublicKey->size, sizeof(uint8_t)); - CHECK_NULL(subjectPublicKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(subjectPublicKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - //common keys - - //read CA private key from the CA storage - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAPrivateKey, &privKeyIss); - - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((issuerPrivateKey->buf) + 1, privKeyIss.data, PRIVATE_KEY_SIZE); - - if (!uint8SubjectPublicKey) - { - //GenerateKeyPair - GenerateKeyPair(&privKeySubj, &pubKeySubj); - } - else - { - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((subjectPublicKey->buf) + 1, uint8SubjectPublicKey, PUBLIC_KEY_SIZE); - } - - CHECK_CALL(GenerateCertificate, subjectName, issuerName, notBefore, notAfter, - subjectPublicKey, issuerPrivateKey, issuedCertificate); - - FUNCTION_CLEAR( - OICFree(subjectName); - OICFree(issuerName); - OICFree(notBefore); - OICFree(notAfter); - ASN_STRUCT_FREE(asn_DEF_BIT_STRING, subjectPublicKey); - ASN_STRUCT_FREE(asn_DEF_BIT_STRING, issuerPrivateKey); - ); -} - -PKIError GenerateDERCertificateFile (const ByteArray *certificate, const char * const certFileName) -{ - FUNCTION_INIT(); - -#ifdef __unix__ - struct stat st; - int fd = -1; -#else - FILE *filePointer = NULL; -#endif - - CHECK_NULL(certFileName, ISSUER_NULL_PASSED); - CHECK_NULL(certificate, ISSUER_NULL_PASSED); - CHECK_NULL(certificate->data, ISSUER_NULL_PASSED); - -#ifdef __unix__ - fd = open(certFileName, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); - CHECK_NOT_EQUAL(fd, -1, ISSUER_NULL_PASSED); - CHECK_EQUAL(fstat(fd, &st), 0, ISSUER_NULL_PASSED); - CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR); - CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR); - CHECK_EQUAL(write(fd, certificate->data, certificate->len), (ssize_t) certificate->len, - ISSUER_FILE_WRITE_ERROR); - - FUNCTION_CLEAR( - if(-1 != fd) - { - close(fd); - } - ); -#else - filePointer = fopen(certFileName, "wb"); - CHECK_NULL(filePointer, ISSUER_FILE_WRITE_ERROR); - CHECK_EQUAL(fwrite(certificate->data, 1, certificate->len, filePointer), certificate->len, - ISSUER_FILE_WRITE_ERROR); - - FUNCTION_CLEAR( - if(filePointer) - { - fclose(filePointer); - } - filePointer = NULL; - ); -#endif - -} - -PKIError SetSerialNumber (const long serNum) -{ - FUNCTION_INIT(); - - CHECK_LESS_EQUAL(0, serNum, ISSUER_WRONG_SERIAL_NUMBER); - CHECK_CALL(InitCKMInfo); - CHECK_CALL(SetNextSerialNumber, serNum); - CHECK_CALL(SaveCKMInfo); - - FUNCTION_CLEAR(); -} - -PKIError SetRootName (const ByteArray rootName) -{ - FUNCTION_INIT(); - - CHECK_NULL(rootName.data, ISSUER_NULL_PASSED); - CHECK_LESS(0, rootName.len, ISSUER_WRONG_ROOT_NAME_LEN); - CHECK_LESS(rootName.len, ISSUER_MAX_NAME_SIZE, ISSUER_WRONG_ROOT_NAME_LEN); - CHECK_CALL(InitCKMInfo); - CHECK_CALL(SetCAName, &rootName); - CHECK_CALL(SaveCKMInfo); - - FUNCTION_CLEAR(); -} - -PKIError CKMSetCAInfo (const long serNum, const ByteArray rootName) -{ - FUNCTION_INIT(); - CHECK_CALL(SetSerialNumber, serNum); - CHECK_CALL(SetRootName, rootName); - - FUNCTION_CLEAR(); -} - -PKIError GenerateCSR (const uint8_t *uint8SubjectName, - const uint8_t *uint8SubjectPublicKey, - const uint8_t *uint8SubjectPrivateKey, - ByteArray *encodedCSR) -{ - FUNCTION_INIT(); - UTF8String_t *subjectName = NULL; - BIT_STRING_t *subjectPublicKey = NULL; - BIT_STRING_t *subjectPrivateKey = NULL; - - CHECK_NULL(uint8SubjectPublicKey, ISSUER_NULL_PASSED); - CHECK_NULL(uint8SubjectPrivateKey, ISSUER_NULL_PASSED); - CHECK_NULL(encodedCSR, ISSUER_NULL_PASSED); - CHECK_NULL(encodedCSR->data, ISSUER_NULL_PASSED); - CHECK_LESS_EQUAL(CSR_MAX_SIZE, encodedCSR->len, ISSUER_WRONG_BYTE_ARRAY_LEN); - - subjectName = OICCalloc(1, sizeof(UTF8String_t)); - CHECK_NULL(subjectName, ISSUER_MEMORY_ALLOC_FAILED); - - subjectPublicKey = OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(subjectPublicKey, ISSUER_MEMORY_ALLOC_FAILED); - - subjectPrivateKey = OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(subjectPrivateKey, ISSUER_MEMORY_ALLOC_FAILED); - - //SubjectName - if (uint8SubjectName) - { - subjectName->buf = (uint8_t *)uint8SubjectName; - } - else - { - subjectName->buf = (uint8_t *)ISSUER_DEFAULT_SUBJECT_NAME; - } - subjectName->size = strlen((const char *)subjectName->buf); - - //common keys - subjectPrivateKey->size = PRIVATE_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - subjectPrivateKey->buf = (uint8_t *)OICCalloc((subjectPrivateKey->size), sizeof(uint8_t)); - CHECK_NULL(subjectPrivateKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(subjectPrivateKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - - subjectPublicKey->size = PUBLIC_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - subjectPublicKey->buf = (uint8_t *)OICCalloc(subjectPublicKey->size, sizeof(uint8_t)); - CHECK_NULL(subjectPublicKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(subjectPublicKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - //common keys - - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((subjectPrivateKey->buf) + 1, uint8SubjectPrivateKey, PRIVATE_KEY_SIZE); - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((subjectPublicKey->buf) + 1, uint8SubjectPublicKey, PUBLIC_KEY_SIZE); - - CHECK_CALL(EncodeCSR, subjectName, subjectPublicKey, subjectPrivateKey, encodedCSR); - - FUNCTION_CLEAR( - OICFree(subjectName); - OICFree(subjectPublicKey); - if (subjectPrivateKey) - { - OICFree(subjectPrivateKey->buf); - OICFree(subjectPrivateKey); - } - ); -} - -PKIError GenerateCertificateByCSR (const ByteArray *encodedCSR, ByteArray *issuedCertificate) -{ - FUNCTION_INIT(); - UTF8String_t *subjectName = NULL; - BIT_STRING_t *subjectPublicKey = NULL; - uint8_t uint8SubjectName[ISSUER_MAX_NAME_SIZE]; - uint8_t uint8SubjectPublicKey[PUBLIC_KEY_SIZE + 1]; - - CHECK_NULL(encodedCSR, ISSUER_NULL_PASSED); - CHECK_NULL(encodedCSR->data, ISSUER_NULL_PASSED); - CHECK_NULL(issuedCertificate, ISSUER_NULL_PASSED); - CHECK_NULL(issuedCertificate->data, ISSUER_NULL_PASSED); - CHECK_LESS_EQUAL(ISSUER_MAX_CERT_SIZE, issuedCertificate->len, ISSUER_WRONG_BYTE_ARRAY_LEN); - - subjectName = OICCalloc(1, sizeof(UTF8String_t)); - CHECK_NULL(subjectName, ISSUER_MEMORY_ALLOC_FAILED); - - subjectPublicKey = OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(subjectPublicKey, ISSUER_MEMORY_ALLOC_FAILED); - - subjectName->buf = uint8SubjectName; - subjectPublicKey->buf = uint8SubjectPublicKey; - - CHECK_CALL(DecodeCSR, encodedCSR, subjectName, subjectPublicKey); - - uint8SubjectName[subjectName->size] = '\0'; - CHECK_CALL(CKMIssueDeviceCertificate, uint8SubjectName, 0, 0, uint8SubjectPublicKey + 1, - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - issuedCertificate); - - FUNCTION_CLEAR( - OICFree(subjectPublicKey); - OICFree(subjectName); - ); -} - -PKIError CKMIssueCRL (const uint8_t *uint8ThisUpdateTime, const uint32_t numberOfRevoked, - const uint32_t *revokedNumbers, const uint8_t **revocationDates, - ByteArray *encodedCRL) -{ - FUNCTION_INIT(); - BIT_STRING_t *issuerPrivateKey = NULL; - UTCTime_t *thisUpdateTime = NULL; - CertificateRevocationInfo_t *certificateRevocationInfo = NULL; - UTF8String_t *issuerName = NULL; - uint32_t i; - - uint8_t caPrivateKey[PRIVATE_KEY_SIZE]; - uint8_t uint8caName[ISSUER_MAX_NAME_SIZE]; - - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray caName = BYTE_ARRAY_INITIALIZER; - - CHECK_NULL(numberOfRevoked, ISSUER_NULL_PASSED); - CHECK_NULL(revokedNumbers, ISSUER_NULL_PASSED); - CHECK_NULL(revocationDates, ISSUER_NULL_PASSED); - CHECK_NULL(encodedCRL, ISSUER_NULL_PASSED); - CHECK_NULL(encodedCRL->data, ISSUER_NULL_PASSED); - CHECK_LESS_EQUAL((CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)), - encodedCRL->len, ISSUER_WRONG_BYTE_ARRAY_LEN); - - issuerPrivateKey = (BIT_STRING_t *)OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(issuerPrivateKey, ISSUER_MEMORY_ALLOC_FAILED); - - thisUpdateTime = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t)); - CHECK_NULL(thisUpdateTime, ISSUER_MEMORY_ALLOC_FAILED); - - issuerName = (UTF8String_t *)OICCalloc(1, sizeof(UTF8String_t)); - CHECK_NULL(issuerName, ISSUER_MEMORY_ALLOC_FAILED); - - certificateRevocationInfo = (CertificateRevocationInfo_t *)OICCalloc(numberOfRevoked, - sizeof(CertificateRevocationInfo_t)); - CHECK_NULL(certificateRevocationInfo, ISSUER_MEMORY_ALLOC_FAILED); - - privKeyIss.data = caPrivateKey; - privKeyIss.len = PRIVATE_KEY_SIZE; - caName.data = uint8caName; - caName.len = ISSUER_MAX_NAME_SIZE; - - //allocate issuerPrivateKey - issuerPrivateKey->size = PRIVATE_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - issuerPrivateKey->buf = (uint8_t *)OICCalloc((issuerPrivateKey->size), sizeof(uint8_t)); - CHECK_NULL(issuerPrivateKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(issuerPrivateKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - - //read CA private key from the CA storage - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAPrivateKey, &privKeyIss); - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((issuerPrivateKey->buf) + 1, privKeyIss.data, PRIVATE_KEY_SIZE); - - //thisUpdateTime - if (uint8ThisUpdateTime) - { - thisUpdateTime->buf = (uint8_t *)uint8ThisUpdateTime; - } - else - { - thisUpdateTime->buf = (uint8_t *)ISSUER_DEFAULT_THIS_UPDATE; - } - thisUpdateTime->size = strlen((const char *)thisUpdateTime->buf); - - //RootName - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAName, &caName); - issuerName->buf = caName.data; - issuerName->size = caName.len; - - // CRI - for ( i = 0; i < numberOfRevoked; i++ ) - { - certificateRevocationInfo[i].userCertificate = revokedNumbers[i]; - certificateRevocationInfo[i].revocationDate.buf = (uint8_t *)revocationDates[i]; - certificateRevocationInfo[i].revocationDate.size = - strlen((const char *)revocationDates[i]); - } - - CHECK_CALL(GenerateCRL, issuerName, thisUpdateTime, numberOfRevoked, certificateRevocationInfo, - issuerPrivateKey, encodedCRL); - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(SetCertificateRevocationList, encodedCRL); - CHECK_CALL(SaveCKMInfo); - - FUNCTION_CLEAR( - OICFree(issuerName); - OICFree(thisUpdateTime); - OICFree(certificateRevocationInfo); - ASN_STRUCT_FREE(asn_DEF_BIT_STRING, issuerPrivateKey); - ); -} - -PKIError CKMRevocateCertificate (const uint8_t *uint8ThisUpdateTime, const long revokedNumber, - ByteArray *encodedCRL) -{ - FUNCTION_INIT(); - ByteArray oldCRL = BYTE_ARRAY_INITIALIZER; - asn_dec_rval_t rval; /* Decoder return value */ - CertificateRevocationList_t *certificateRevocationList = NULL; // Type to decode - CertificateRevocationInfo_t *CRI = NULL; - long serialNumber = 0; - long numberOfRevoked = 0; - uint32_t crlMaxSize = 0; - - BIT_STRING_t *issuerPrivateKey = NULL; - uint8_t caPrivateKey[PRIVATE_KEY_SIZE]; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetNumberOfRevoked, &numberOfRevoked); - - crlMaxSize = (uint32_t)(CRL_MIN_SIZE + - (numberOfRevoked + 1) * (sizeof(CertificateRevocationInfo_t) + 4)); - - CHECK_NULL(encodedCRL, ISSUER_NULL_PASSED); - CHECK_NULL(encodedCRL->data, ISSUER_NULL_PASSED); - CHECK_LESS_EQUAL(crlMaxSize, encodedCRL->len, ISSUER_WRONG_BYTE_ARRAY_LEN); - - //obtain CRL - oldCRL.data = (uint8_t *)OICMalloc(crlMaxSize); - CHECK_NULL(oldCRL.data, ISSUER_MEMORY_ALLOC_FAILED); - oldCRL.len = crlMaxSize; - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCertificateRevocationList, &oldCRL); - CHECK_CALL(CloseCKMInfo); - - //decode CRL - rval = ber_decode(0, &asn_DEF_CertificateRevocationList, (void **)&certificateRevocationList, - oldCRL.data, oldCRL.len); - CHECK_EQUAL(rval.code, RC_OK, ISSUER_CSR_DER_DECODE_FAIL); - - //add one certificate into CRL - CRI = (CertificateRevocationInfo_t *)OICCalloc(1, sizeof(CertificateRevocationInfo_t)); - CHECK_NULL(CRI, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - CRI->revocationDate.size = (int)strlen((const char *)uint8ThisUpdateTime); - CRI->revocationDate.buf = OICCalloc((CRI->revocationDate.size) + 1, sizeof(char)); - //additional byte for \0 at the end - CHECK_NULL(CRI->revocationDate.buf, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - memcpy(CRI->revocationDate.buf, uint8ThisUpdateTime, CRI->revocationDate.size + 1); - //additional byte for \0 at the end - - CRI->userCertificate = revokedNumber; - ASN_SEQUENCE_ADD((void *)(&(certificateRevocationList-> - tbsCertList.revokedCertificates.list)), (void *)(CRI)); - - //prepare memory for issuerPrivateKey - issuerPrivateKey = (BIT_STRING_t *)OICCalloc(1, sizeof(BIT_STRING_t)); - CHECK_NULL(issuerPrivateKey, ISSUER_MEMORY_ALLOC_FAILED); - privKeyIss.data = caPrivateKey; - privKeyIss.len = PRIVATE_KEY_SIZE; - //allocate issuerPrivateKey - issuerPrivateKey->size = PRIVATE_KEY_SIZE + 1; //additional byte for ASN1_UNCOMPRESSED_KEY_ID - issuerPrivateKey->buf = (uint8_t *)OICCalloc((issuerPrivateKey->size), sizeof(uint8_t)); - CHECK_NULL(issuerPrivateKey->buf, ISSUER_MEMORY_ALLOC_FAILED); - *(issuerPrivateKey->buf) = (uint8_t)ASN1_UNCOMPRESSED_KEY_ID; - - //read CA private key from the CA storage - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCAPrivateKey, &privKeyIss); - - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - memcpy((issuerPrivateKey->buf) + 1, privKeyIss.data, PRIVATE_KEY_SIZE); - - //SignCRL - CHECK_CALL(SignCRL, certificateRevocationList, crlMaxSize, issuerPrivateKey, encodedCRL); - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCRLSerialNumber, &serialNumber); - serialNumber++; - CHECK_CALL(SetCRLSerialNumber, serialNumber); - numberOfRevoked++; - CHECK_CALL(SetNumberOfRevoked, numberOfRevoked); - CHECK_CALL(SetCertificateRevocationList, encodedCRL); - CHECK_CALL(SaveCKMInfo); - - FUNCTION_CLEAR( - ASN_STRUCT_FREE(asn_DEF_CertificateRevocationList, certificateRevocationList); - certificateRevocationList = NULL; - - ); -} - -PKIError CKMGetCRL (ByteArray *certificateRevocationList) -{ - FUNCTION_INIT(); - CHECK_NULL(certificateRevocationList, ISSUER_NULL_PASSED); - CHECK_NULL(certificateRevocationList->data, ISSUER_NULL_PASSED); - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCertificateRevocationList, certificateRevocationList); - CHECK_CALL(CloseCKMInfo); - - FUNCTION_CLEAR(); -} diff --git a/resource/csdk/security/provisioning/ck_manager/src/ckm_info.c b/resource/csdk/security/provisioning/ck_manager/src/ckm_info.c deleted file mode 100644 index 2aea365..0000000 --- a/resource/csdk/security/provisioning/ck_manager/src/ckm_info.c +++ /dev/null @@ -1,565 +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 "ckm_info.h" -#include "ocstack.h" -#include "oic_malloc.h" -#include "cJSON.h" -#include "base64.h" -#include "psinterface.h" -#include "srmresourcestrings.h" -#include "crlresource.h" -#include "crl_generator.h" - -#ifdef __unix__ -#include -#endif // __unix__ - -//constants used in ckmInfo -#define CKM_INFO_IS_NOT_LOADED (0) -#define CKM_INFO_IS_LOADED (1) -#define CA_PRIVATE_KEY_IS_NOT_SET (0) -#define CA_PRIVATE_KEY_IS_SET (1) -#define CA_PRIVATE_KEY_DEFAULT_VALUE (0) -#define CA_PUBLIC_KEY_IS_NOT_SET (0) -#define CA_PUBLIC_KEY_IS_SET (1) -#define CA_PUBLIC_KEY_DEFAULT_VALUE (0) -#define CA_CERTIFICATE_CHAIN_IS_NOT_SET (0) -#define CA_CERTIFICATE_CHAIN_MEMORY_IS_NOT_ALLOCATED (0) -#define CA_NAME_IS_NOT_SET (0) -#define CA_NAME_DEFAULT_VALUE (0) -#define CERTIFICATE_SN_INITIAL_VALUE (1) -#define CRL_SN_INITIAL_VALUE (1) -#define NUMBER_OF_REVOKED_CERTIFICATES_INITIAL_VALUE (0) - -//constants used in crlInfo -#define CRL_IS_NOT_SET (0) -#define CRL_MEMORY_IS_NOT_ALLOCATED (0) - -static CKMInfo_t g_ckmInfo = {CKM_INFO_IS_NOT_LOADED, - CA_PRIVATE_KEY_IS_NOT_SET, {CA_PRIVATE_KEY_DEFAULT_VALUE}, - CA_PUBLIC_KEY_IS_NOT_SET, {CA_PUBLIC_KEY_DEFAULT_VALUE}, - CA_CERTIFICATE_CHAIN_IS_NOT_SET, - CA_CERTIFICATE_CHAIN_MEMORY_IS_NOT_ALLOCATED, - CA_NAME_IS_NOT_SET, {CA_NAME_DEFAULT_VALUE}, - CERTIFICATE_SN_INITIAL_VALUE, CRL_SN_INITIAL_VALUE, - NUMBER_OF_REVOKED_CERTIFICATES_INITIAL_VALUE}; - -static OicSecCrl_t g_crlInfo = {CRL_IS_NOT_SET, - BYTE_ARRAY_INITIALIZER, BYTE_ARRAY_INITIALIZER}; - -//General functions - -PKIError InitCKMInfo(void) -{ - FUNCTION_INIT(); - FILE *filePointer = NULL; - int count = 1; - int objectsRead = 0; - int objectsWrote = 0; - - if (!g_ckmInfo.CKMInfoIsLoaded) - { - filePointer = fopen(CA_STORAGE_FILE, "rb"); - if (filePointer) //read existing storage - { - objectsRead = fread(&g_ckmInfo, sizeof(CKMInfo_t), count, filePointer); - g_ckmInfo.CACertificateChain = CA_CERTIFICATE_CHAIN_MEMORY_IS_NOT_ALLOCATED; - CHECK_EQUAL(objectsRead, count, ISSUER_CA_STORAGE_FILE_READ_ERROR); - } - else ////create new storage - { -#ifdef __unix__ - struct stat st; - if (0 == lstat(CA_STORAGE_FILE, &st)) - { - CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR); - CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR); - } -#endif - filePointer = fopen(CA_STORAGE_FILE, "wb"); - CHECK_NULL(filePointer, ISSUER_CA_STORAGE_FILE_WRITE_ERROR); - objectsWrote = fwrite(&g_ckmInfo, sizeof(CKMInfo_t), count, filePointer); - CHECK_EQUAL(objectsWrote, count, ISSUER_CA_STORAGE_FILE_WRITE_ERROR); - } - CHECK_CALL(InitCRL); - CHECK_CALL(InitCRT); - g_ckmInfo.CKMInfoIsLoaded = CKM_INFO_IS_LOADED; - } - FUNCTION_CLEAR( - if (filePointer) - { - fclose(filePointer); - filePointer = NULL; - } - ); -} - -PKIError SaveCKMInfo(void) -{ - FUNCTION_INIT(); - FILE *filePointer = NULL; - int count = 1; - int objectsWrote = 0; -#ifdef __unix__ - struct stat st; -#endif - - CHECK_COND(g_ckmInfo.CKMInfoIsLoaded, CKM_INFO_IS_NOT_INIT); -#ifdef __unix__ - if (0 == lstat(CA_STORAGE_FILE, &st)) - { - CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR); - CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR); - } -#endif - filePointer = fopen(CA_STORAGE_FILE, "wb"); - CHECK_NULL(filePointer, ISSUER_CA_STORAGE_FILE_WRITE_ERROR); - objectsWrote = fwrite(&g_ckmInfo, sizeof(CKMInfo_t), count, filePointer); - CHECK_EQUAL(objectsWrote, count, ISSUER_CA_STORAGE_FILE_WRITE_ERROR); - if ((g_crlInfo.CrlData.data)&&(g_crlInfo.CrlData.len)) - { - CHECK_CALL(SaveCRL); - } - if (g_ckmInfo.CAChainLength) - { - CHECK_CALL(SaveCRT); - } - FUNCTION_CLEAR( - if (filePointer) - { - fclose(filePointer); - filePointer = NULL; - } - ); -} - -PKIError CloseCKMInfo(void) -{ - FUNCTION_INIT(); - CHECK_CALL(SaveCKMInfo); - OICFree(g_crlInfo.CrlData.data); - g_crlInfo.CrlData.data = CRL_MEMORY_IS_NOT_ALLOCATED; - OICFree(g_crlInfo.ThisUpdate.data); - g_crlInfo.ThisUpdate.data = CRL_MEMORY_IS_NOT_ALLOCATED; - OICFree(g_ckmInfo.CACertificateChain); - g_ckmInfo.CACertificateChain = CA_CERTIFICATE_CHAIN_MEMORY_IS_NOT_ALLOCATED; - g_ckmInfo.CKMInfoIsLoaded = CKM_INFO_IS_NOT_LOADED; - g_crlInfo.CrlId = CRL_IS_NOT_SET; - FUNCTION_CLEAR(); -} - -PKIError SetCKMInfo (const long nextSN, const long CRLSerialNumber, - const ByteArray *CAPrivateKey, const ByteArray *CAPublicKey, - const ByteArray *CAName) -{ - FUNCTION_INIT(); - if (nextSN) - CHECK_CALL(SetNextSerialNumber, nextSN); - if (CRLSerialNumber) - CHECK_CALL(SetCRLSerialNumber, CRLSerialNumber); - if (CAPrivateKey) - CHECK_CALL(SetCAPrivateKey, CAPrivateKey); - if (CAPublicKey) - CHECK_CALL(SetCAPublicKey, CAPublicKey); - if (CAName) - CHECK_CALL(SetCAName, CAName); - - FUNCTION_CLEAR(); -} - -PKIError GetCKMInfo (long *nextSN, long *CRLSerialNumber, - ByteArray *CAPrivateKey, ByteArray *CAPublicKey, - ByteArray *CAName) -{ - FUNCTION_INIT(); - if (nextSN) - CHECK_CALL(GetNextSerialNumber, nextSN); - if (CRLSerialNumber) - CHECK_CALL(GetCRLSerialNumber, CRLSerialNumber); - if (CAPrivateKey) - CHECK_CALL(GetCAPrivateKey, CAPrivateKey); - if (CAPublicKey) - CHECK_CALL(GetCAPublicKey, CAPublicKey); - if (CAName) - CHECK_CALL(GetCAName, CAName); - - FUNCTION_CLEAR(); -} - -/*Private Key*/ -PKIError SetCAPrivateKey (const ByteArray *CAPrivateKey) -{ - FUNCTION_INIT(); - CHECK_NULL_BYTE_ARRAY_PTR(CAPrivateKey, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_EQUAL(CAPrivateKey->len, PRIVATE_KEY_SIZE, ISSUER_CA_STORAGE_WRONG_PRIVATE_KEY_LEN); - memcpy(g_ckmInfo.CAPrivateKey, CAPrivateKey->data, PRIVATE_KEY_SIZE); - g_ckmInfo.CAPrivateKeyIsSet = CA_PRIVATE_KEY_IS_SET; - - FUNCTION_CLEAR(); -} - -PKIError GetCAPrivateKey (ByteArray *CAPrivateKey) -{ - FUNCTION_INIT(); - CHECK_COND(g_ckmInfo.CAPrivateKeyIsSet, ISSUER_CA_STORAGE_PRIVATE_KEY_UNDEFINED); - CHECK_NULL_BYTE_ARRAY_PTR(CAPrivateKey, ISSUER_CA_STORAGE_NULL_PASSED); - memcpy(CAPrivateKey->data, g_ckmInfo.CAPrivateKey, PRIVATE_KEY_SIZE); - CAPrivateKey->len = PRIVATE_KEY_SIZE; - - FUNCTION_CLEAR(); -} - -/*Public Key*/ -PKIError SetCAPublicKey (const ByteArray *CAPublicKey) -{ - FUNCTION_INIT(); - CHECK_NULL_BYTE_ARRAY_PTR(CAPublicKey, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_EQUAL(CAPublicKey->len, PUBLIC_KEY_SIZE, ISSUER_CA_STORAGE_WRONG_PUBLIC_KEY_LEN); - memcpy(g_ckmInfo.CAPublicKey, CAPublicKey->data, PUBLIC_KEY_SIZE); - g_ckmInfo.CAPublicKeyIsSet = CA_PUBLIC_KEY_IS_SET; - - FUNCTION_CLEAR(); -} - -PKIError GetCAPublicKey (ByteArray *CAPublicKey) -{ - FUNCTION_INIT(); - CHECK_COND(g_ckmInfo.CAPublicKeyIsSet, ISSUER_CA_STORAGE_PUBLIC_KEY_UNDEFINED); - CHECK_NULL_BYTE_ARRAY_PTR(CAPublicKey, ISSUER_CA_STORAGE_NULL_PASSED); - memcpy(CAPublicKey->data, g_ckmInfo.CAPublicKey, PUBLIC_KEY_SIZE); - CAPublicKey->len = PUBLIC_KEY_SIZE; - - FUNCTION_CLEAR(); -} - -/*CAName*/ -PKIError SetCAName (const ByteArray *CAName) -{ - FUNCTION_INIT(); - CHECK_NULL_BYTE_ARRAY_PTR(CAName, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_LESS_EQUAL(CAName->len, ISSUER_MAX_NAME_SIZE, ISSUER_CA_STORAGE_WRONG_CA_NAME_LEN); - memcpy(g_ckmInfo.CAName, CAName->data, CAName->len); - g_ckmInfo.CANameSize = (uint32_t)CAName->len; - - FUNCTION_CLEAR(); -} - -PKIError GetCAName (ByteArray *CAName) -{ - FUNCTION_INIT(); - CHECK_COND(g_ckmInfo.CANameSize, ISSUER_CA_STORAGE_CA_NAME_UNDEFINED); - CHECK_NULL_BYTE_ARRAY_PTR(CAName, ISSUER_CA_STORAGE_NULL_PASSED); - memcpy(CAName->data, g_ckmInfo.CAName, g_ckmInfo.CANameSize); - CAName->len = g_ckmInfo.CANameSize; - - FUNCTION_CLEAR(); -} - -//Certificate-related functions - -#define CERT_LEN_PREFIX (3) -#define BYTE_SIZE (8) //bits - -static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen) -{ - for (size_t i = 0; i < CERT_LEN_PREFIX; ++i) - { - prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF; - } -} - -static uint32_t ParseCertPrefix(uint8_t *prefix) -{ - uint32_t res = 0; - if(NULL != prefix) - { - for(int i=0; i < CERT_LEN_PREFIX; ++i) - { - res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE)); - } - } - return res; -} - -PKIError InitCRT(void) -{ - FUNCTION_INIT(); - FILE *filePointer = NULL; - uint32_t objectsRead = 0; - uint8_t prefix[CERT_LEN_PREFIX] = {0}; - - if (g_ckmInfo.CAChainLength) - { - filePointer = fopen(CA_STORAGE_CRT_FILE, "rb"); - CHECK_NULL(filePointer, ISSUER_CA_STORAGE_CRT_READ_ERROR); - - g_ckmInfo.CACertificateChain = - (ByteArray *)OICMalloc(sizeof(ByteArray) * g_ckmInfo.CAChainLength); - CHECK_NULL(g_ckmInfo.CACertificateChain, ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED); - - for (int i = 0; i < g_ckmInfo.CAChainLength; i++) - { - objectsRead = (uint32_t)fread(prefix, sizeof(uint8_t), CERT_LEN_PREFIX, filePointer); - CHECK_EQUAL(objectsRead, CERT_LEN_PREFIX, ISSUER_CA_STORAGE_CRT_READ_ERROR); - g_ckmInfo.CACertificateChain[i].len = ParseCertPrefix(prefix); - - g_ckmInfo.CACertificateChain[i].data = - (uint8_t *)OICMalloc(g_ckmInfo.CACertificateChain[i].len); - CHECK_NULL(g_ckmInfo.CACertificateChain[i].data, - ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED); - objectsRead = (uint32_t)fread(g_ckmInfo.CACertificateChain[i].data, sizeof(uint8_t), - g_ckmInfo.CACertificateChain[i].len, filePointer); - CHECK_EQUAL(objectsRead, g_ckmInfo.CACertificateChain[i].len, - ISSUER_CA_STORAGE_CRT_READ_ERROR); - } - } - FUNCTION_CLEAR( - if (filePointer) - { - fclose(filePointer); - filePointer = NULL; - } - ); -} - -PKIError SaveCRT(void) -{ - FUNCTION_INIT(); - FILE *filePointer = NULL; - uint32_t objectsWrote = 0; - uint8_t prefix[CERT_LEN_PREFIX] = {0}; -#ifdef __unix__ - struct stat st; - if (0 == lstat(CA_STORAGE_CRT_FILE, &st)) - { - CHECK_COND(S_ISREG(st.st_mode), ISSUER_FILE_WRITE_ERROR); - CHECK_COND(!S_ISLNK(st.st_mode), ISSUER_FILE_WRITE_ERROR); - } -#endif - filePointer = fopen(CA_STORAGE_CRT_FILE, "wb"); - CHECK_NULL(filePointer, ISSUER_CA_STORAGE_CRT_WRITE_ERROR); - - for (int i = 0; i < g_ckmInfo.CAChainLength; i++) - { - WriteCertPrefix(prefix, g_ckmInfo.CACertificateChain[i].len); - objectsWrote = (uint32_t)fwrite(prefix, sizeof(uint8_t), CERT_LEN_PREFIX, filePointer); - CHECK_EQUAL(objectsWrote, CERT_LEN_PREFIX, ISSUER_CA_STORAGE_CRT_WRITE_ERROR); - objectsWrote = (uint32_t)fwrite(g_ckmInfo.CACertificateChain[i].data, sizeof(uint8_t), - g_ckmInfo.CACertificateChain[i].len, filePointer); - CHECK_EQUAL(objectsWrote, g_ckmInfo.CACertificateChain[i].len, - ISSUER_CA_STORAGE_CRT_WRITE_ERROR); - } - - FUNCTION_CLEAR( - if (filePointer) - { - fclose(filePointer); - filePointer = NULL; - } - ); -} - -/*Serial Number*/ -PKIError SetNextSerialNumber (const long nextSN) -{ - FUNCTION_INIT(); - CHECK_LESS_EQUAL(0, nextSN, ISSUER_CA_STORAGE_WRONG_SERIAL_NUMBER); - g_ckmInfo.nextSerialNumber = nextSN; - - FUNCTION_CLEAR(); -} - -PKIError GetNextSerialNumber (long *nextSN) -{ - FUNCTION_INIT(); - CHECK_NULL(nextSN, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_NULL(g_ckmInfo.nextSerialNumber, ISSUER_CA_STORAGE_SN_UNDEFINED); - *nextSN = g_ckmInfo.nextSerialNumber; - - FUNCTION_CLEAR(); -} - -/*CA Certificate Chain*/ -PKIError SetCAChain (const uint8_t CAChainLength, const ByteArray *CAChain) -{ - FUNCTION_INIT(); - CHECK_NULL_BYTE_ARRAY_PTR(CAChain, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_NULL(CAChainLength, ISSUER_CA_STORAGE_NULL_PASSED); - - OICFree(g_ckmInfo.CACertificateChain); - g_ckmInfo.CACertificateChain = NULL; - g_ckmInfo.CACertificateChain = (ByteArray *)OICMalloc(sizeof(ByteArray) * CAChainLength); - CHECK_NULL(g_ckmInfo.CACertificateChain, ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED); - - for (int i = 0; i < CAChainLength; i++) - { - g_ckmInfo.CACertificateChain[i].data = (uint8_t *)OICMalloc(CAChain[i].len); - CHECK_NULL(g_ckmInfo.CACertificateChain[i].data, ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED); - memcpy(g_ckmInfo.CACertificateChain[i].data, CAChain[i].data, CAChain[i].len); - g_ckmInfo.CACertificateChain[i].len = CAChain[i].len; - } - g_ckmInfo.CAChainLength = CAChainLength; - - FUNCTION_CLEAR(); -} - -PKIError GetCAChain (uint8_t* CAChainLength, ByteArray *CAChain) -{ - FUNCTION_INIT(); - CHECK_COND(g_ckmInfo.CAChainLength, ISSUER_CA_STORAGE_CA_CHAIN_LENGTH_UNDEFINED); - CHECK_NULL_BYTE_ARRAY_PTR(CAChain, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_NULL(CAChainLength, PKI_NULL_PASSED); - - for (int i = 0; i < g_ckmInfo.CAChainLength; i++) - { - CHECK_LESS_EQUAL(g_ckmInfo.CACertificateChain[i].len, CAChain[i].len, - ISSUER_CA_STORAGE_WRONG_BYTE_ARRAY_LEN); - memcpy(CAChain[i].data, g_ckmInfo.CACertificateChain[i].data, - g_ckmInfo.CACertificateChain[i].len); - CAChain[i].len = g_ckmInfo.CACertificateChain[i].len; - } - - *CAChainLength = g_ckmInfo.CAChainLength; - - FUNCTION_CLEAR(); -} - -/*Certificate*/ -PKIError SetCACertificate (const ByteArray *CACertificate) -{ - FUNCTION_INIT(); - CHECK_NULL_BYTE_ARRAY_PTR(CACertificate, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_CALL(SetCAChain, 1, CACertificate); - - FUNCTION_CLEAR(); -} - -PKIError GetCACertificate (ByteArray *CACertificate) -{ - FUNCTION_INIT(); - uint8_t i; - CHECK_NULL_BYTE_ARRAY_PTR(CACertificate, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_CALL(GetCAChain, &i, CACertificate); - - FUNCTION_CLEAR(); -} -//CRL-related functions - -PKIError InitCRL(void) -{ - FUNCTION_INIT(); - g_crlInfo = *(OicSecCrl_t *)GetCRLResource(); - CHECK_NULL(g_crlInfo.CrlData.data, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_NULL(g_crlInfo.ThisUpdate.data, ISSUER_CA_STORAGE_NULL_PASSED); - - FUNCTION_CLEAR(); -} - -PKIError SaveCRL(void) -{ - FUNCTION_INIT(); - - CHECK_EQUAL(UpdateCRLResource(&g_crlInfo), - OC_STACK_OK, ISSUER_CA_STORAGE_CRL_WRITE_ERROR); - FUNCTION_CLEAR(); -} - -/*CRL Serial Number*/ -PKIError SetCRLSerialNumber (const long CRLSerialNumber) -{ - FUNCTION_INIT(); - CHECK_LESS_EQUAL(0, CRLSerialNumber, ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER); - g_ckmInfo.CRLSerialNumber = CRLSerialNumber; - - FUNCTION_CLEAR(); -} - -PKIError GetCRLSerialNumber (long *CRLSerialNumber) -{ - FUNCTION_INIT(); - CHECK_NULL(CRLSerialNumber, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_NULL(g_ckmInfo.CRLSerialNumber, ISSUER_CA_STORAGE_CRL_SN_UNDEFINED); - *CRLSerialNumber = g_ckmInfo.CRLSerialNumber; - - FUNCTION_CLEAR(); -} - -/*Revocation List*/ -PKIError SetCertificateRevocationList (const ByteArray *certificateRevocationList) -{ - FUNCTION_INIT(); - CHECK_NULL_BYTE_ARRAY_PTR(certificateRevocationList, ISSUER_CA_STORAGE_NULL_PASSED); - - OICFree(g_crlInfo.CrlData.data); - g_crlInfo.CrlData.data = CRL_MEMORY_IS_NOT_ALLOCATED; - g_crlInfo.CrlData.data = (uint8_t *)OICMalloc(certificateRevocationList->len + 1); - CHECK_NULL(g_crlInfo.CrlData.data, ISSUER_CA_STORAGE_MEMORY_ALLOC_FAILED); - memcpy(g_crlInfo.CrlData.data, certificateRevocationList->data, certificateRevocationList->len); - g_crlInfo.CrlData.len = certificateRevocationList->len; - - g_crlInfo.CrlId ++; - CHECK_CALL(SaveCRL); - - FUNCTION_CLEAR(); -} - -PKIError GetCertificateRevocationList (ByteArray *certificateRevocationList) -{ - FUNCTION_INIT( - OicSecCrl_t *tmpCRL = NULL; - ); - CHECK_COND(g_crlInfo.CrlData.data, ISSUER_CA_STORAGE_CRL_UNDEFINED); - CHECK_NULL_BYTE_ARRAY_PTR(certificateRevocationList, ISSUER_CA_STORAGE_NULL_PASSED); - tmpCRL = (OicSecCrl_t *)GetCRLResource(); - CHECK_NULL(tmpCRL, ISSUER_CA_STORAGE_NULL_PASSED); - g_crlInfo.CrlId = tmpCRL->CrlId; - g_crlInfo.CrlData = tmpCRL->CrlData; - g_crlInfo.ThisUpdate = tmpCRL->ThisUpdate; - - CHECK_LESS_EQUAL(g_crlInfo.CrlData.len, certificateRevocationList->len, - ISSUER_WRONG_BYTE_ARRAY_LEN); - memcpy(certificateRevocationList->data, g_crlInfo.CrlData.data, g_crlInfo.CrlData.len); - certificateRevocationList->len = g_crlInfo.CrlData.len; - - FUNCTION_CLEAR( - OICFree(tmpCRL); - ); -} - -PKIError SetNumberOfRevoked (const long numberOfRevoked) -{ - FUNCTION_INIT(); - CHECK_LESS_EQUAL(0, numberOfRevoked, ISSUER_CA_STORAGE_WRONG_CRL_SERIAL_NUMBER); - g_ckmInfo.numberOfRevoked = numberOfRevoked; - - FUNCTION_CLEAR(); -} -PKIError GetNumberOfRevoked (long *numberOfRevoked) -{ - FUNCTION_INIT(); - CHECK_NULL(numberOfRevoked, ISSUER_CA_STORAGE_NULL_PASSED); - CHECK_NULL(g_ckmInfo.numberOfRevoked, ISSUER_CA_STORAGE_CRL_SN_UNDEFINED); - *numberOfRevoked = g_ckmInfo.numberOfRevoked; - - FUNCTION_CLEAR(); -} diff --git a/resource/csdk/security/provisioning/ck_manager/src/crl_generator.c b/resource/csdk/security/provisioning/ck_manager/src/crl_generator.c deleted file mode 100644 index e6b0666..0000000 --- a/resource/csdk/security/provisioning/ck_manager/src/crl_generator.c +++ /dev/null @@ -1,241 +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_generator.h" -#include "pki.h" -#include "oic_malloc.h" -#include "ckm_info.h" - -//ecdsa-with-SHA256 1.2.840.10045.4.3.2 [RFC5759] -static const uint8_t g_ECDSA_WITH_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02}; - -//commonName 2.5.4.3 [RFC2256] -static const uint8_t g_COMMON_NAME_OID[] = {0x55, 0x04, 0x03}; - -PKIError GenerateCRL (const UTF8String_t *issuerName, - const UTCTime_t *thisUpdateTime, const uint32_t numberOfRevoked, - const CertificateRevocationInfo_t *certificateRevocationInfo, - const BIT_STRING_t *issuerPrivateKey, ByteArray *encodedCRL) -{ - FUNCTION_INIT(); - - CertificateRevocationList_t *certificateRevocationList = NULL; /* Type to encode */ - AttributeTypeAndValue_t *issuerTypeAndValue = NULL; - RelativeDistinguishedName_t *issuerRDN = NULL; - CertificateRevocationInfo_t *cri = NULL; - - uint32_t crlMaxSize = (uint32_t)(CRL_MIN_SIZE + - numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)); - - uint32_t i; - long serialNumber = 0; - - CHECK_NULL(issuerName, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(thisUpdateTime, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(certificateRevocationInfo, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(issuerPrivateKey, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(encodedCRL, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(encodedCRL->data, ISSUER_CRL_NULL_PASSED); - CHECK_LESS_EQUAL(crlMaxSize, encodedCRL->len, ISSUER_CRL_WRONG_BYTE_ARRAY_LEN); - - /* Allocate the memory */ - certificateRevocationList = OICCalloc(1, sizeof(CertificateRevocationList_t));//not malloc! - CHECK_NULL(certificateRevocationList, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - issuerTypeAndValue = OICCalloc(1, sizeof(AttributeTypeAndValue_t)); - CHECK_NULL(issuerTypeAndValue, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - issuerRDN = OICCalloc(1, sizeof(RelativeDistinguishedName_t)); - CHECK_NULL(issuerRDN, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - //set subject name - issuerTypeAndValue->value = *issuerName; - issuerTypeAndValue->type.buf = (uint8_t *)g_COMMON_NAME_OID; //2.5.4.3 - issuerTypeAndValue->type.size = sizeof(g_COMMON_NAME_OID) / sizeof(g_COMMON_NAME_OID[0]); - ASN_SET_ADD(issuerRDN, issuerTypeAndValue); - ASN_SEQUENCE_ADD(&(certificateRevocationList->tbsCertList.issuer), issuerRDN); - - //set signature algorithm - certificateRevocationList->signatureAlgorithm.algorithm.buf = - (uint8_t *)g_ECDSA_WITH_SHA256_OID; //1.2.840.10045.4.3.2 - certificateRevocationList->signatureAlgorithm.algorithm.size = - sizeof(g_ECDSA_WITH_SHA256_OID) / sizeof(g_ECDSA_WITH_SHA256_OID[0]); - certificateRevocationList->signatureAlgorithm.nul = OICCalloc(1, sizeof(NULL_t)); - CHECK_NULL(certificateRevocationList->signatureAlgorithm.nul, - ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - //set signature algorithm in TBS part - certificateRevocationList->tbsCertList.signature.algorithm.buf = - (uint8_t *)g_ECDSA_WITH_SHA256_OID; //1.2.840.10045.4.3.2 - certificateRevocationList->tbsCertList.signature.algorithm.size = - sizeof(g_ECDSA_WITH_SHA256_OID) / sizeof(g_ECDSA_WITH_SHA256_OID[0]); - certificateRevocationList->tbsCertList.signature.nul = OICCalloc(1, sizeof(NULL_t)); - CHECK_NULL(certificateRevocationList->tbsCertList.signature.nul, - ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - //set thisUpdateTime - certificateRevocationList->tbsCertList.thisUpdate = *thisUpdateTime; - - //add revoked info - for ( i = 0; i < numberOfRevoked; i++) - { - cri = OICCalloc(1, sizeof(CertificateRevocationInfo_t)); - CHECK_NULL(cri, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - cri->revocationDate.size = (certificateRevocationInfo + i)->revocationDate.size; - cri->revocationDate.buf = OICCalloc((cri->revocationDate.size) + 1, sizeof(char)); - CHECK_NULL(cri->revocationDate.buf, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - memcpy(cri->revocationDate.buf, (certificateRevocationInfo + i)->revocationDate.buf, - cri->revocationDate.size + 1); - cri->userCertificate = (certificateRevocationInfo + i)->userCertificate; - ASN_SEQUENCE_ADD((void *)(&(certificateRevocationList-> - tbsCertList.revokedCertificates.list)), (void *)(cri)); - } - - CHECK_CALL(SignCRL, certificateRevocationList, crlMaxSize, issuerPrivateKey, encodedCRL); - - CHECK_CALL(InitCKMInfo); - CHECK_CALL(GetCRLSerialNumber, &serialNumber); - serialNumber++; - CHECK_CALL(SetCRLSerialNumber, serialNumber); - CHECK_CALL(SetNumberOfRevoked, numberOfRevoked); - CHECK_CALL(SaveCKMInfo); - - FUNCTION_CLEAR( - if (issuerTypeAndValue) - { - issuerTypeAndValue->value.buf = NULL; - issuerTypeAndValue->type.buf = NULL; - } - if (certificateRevocationList) - { - certificateRevocationList->tbsCertList.signature.algorithm.buf = NULL; - certificateRevocationList->signatureAlgorithm.algorithm.buf = NULL; - certificateRevocationList->tbsCertList.thisUpdate.buf = NULL; - } - - ASN_STRUCT_FREE(asn_DEF_CertificateRevocationList, certificateRevocationList); - certificateRevocationList = NULL; - ); -} - -PKIError SignCRL(CertificateRevocationList_t *certificateRevocationList, - const uint32_t crlMaxSize, const BIT_STRING_t *issuerPrivateKey, - ByteArray *encodedCRL) -{ - FUNCTION_INIT(); - uint8_t *crlInfoInDER = NULL; - asn_enc_rval_t ec; /* Encoder return value */ - uint8_t *uint8Pointer = NULL; - ByteArray tbs = BYTE_ARRAY_INITIALIZER; - uint8_t signature[SIGN_FULL_SIZE]; - uint8_t sha256[SHA_256_HASH_LEN]; - - CHECK_NULL(certificateRevocationList, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(crlMaxSize, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(issuerPrivateKey, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(encodedCRL, ISSUER_CRL_NULL_PASSED); - CHECK_NULL(encodedCRL->data, ISSUER_CRL_NULL_PASSED); - CHECK_LESS_EQUAL(crlMaxSize, encodedCRL->len, ISSUER_CRL_WRONG_BYTE_ARRAY_LEN); - - //encode TBS to DER - crlInfoInDER = OICCalloc(1, crlMaxSize); - CHECK_NULL(crlInfoInDER, ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - - ec = der_encode_to_buffer(&asn_DEF_TBSCertList, &(certificateRevocationList->tbsCertList), - crlInfoInDER, crlMaxSize); - - //sign CRL - CHECK_COND(ec.encoded > 0, ISSUER_CRL_ENCODER_DER_ENCODE_FAIL); - tbs.len = ec.encoded; - tbs.data = crlInfoInDER; - GET_SHA_256(tbs, sha256); - CHECK_COND(uECC_sign((issuerPrivateKey->buf) + 1, sha256, signature), - ISSUER_CRL_ENCODER_SIGNATURE_FAIL); - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - - // ECDSA-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } (RFC 5480) - certificateRevocationList->signatureValue.size = SIGN_FULL_SIZE + 6; - // size for SEQUENCE ID + 2 * INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[0] > 127) - { - certificateRevocationList->signatureValue.size ++; - } - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[SIGN_R_LEN] > 127) - { - certificateRevocationList->signatureValue.size ++; - } - OICFree(certificateRevocationList->signatureValue.buf); - certificateRevocationList->signatureValue.buf = (uint8_t *)OICCalloc( - certificateRevocationList->signatureValue.size, sizeof(uint8_t)); - CHECK_NULL(certificateRevocationList->signatureValue.buf, - ISSUER_CRL_ENCODER_MEMORY_ALLOC_FAILED); - *(certificateRevocationList->signatureValue.buf) = (12 << 2); //ASN.1 SEQUENCE ID - *(certificateRevocationList->signatureValue.buf + 1) = - certificateRevocationList->signatureValue.size - 2; //ASN.1 SEQUENCE size - - uint8Pointer = certificateRevocationList->signatureValue.buf + 2; //skip SEQUENCE ID and size - *uint8Pointer = (2 << 0); //ASN.1 INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[0] > 127) - { - *(uint8Pointer + 1) = SIGN_R_LEN + 1; //ASN.1 INTEGER size - uint8Pointer += 3; //skip INTEGER ID and size - } - else - { - *(uint8Pointer + 1) = SIGN_R_LEN; //ASN.1 INTEGER size - uint8Pointer += 2; //skip INTEGER ID and size - } - memcpy(uint8Pointer, signature, SIGN_R_LEN); - - uint8Pointer += SIGN_R_LEN; - *uint8Pointer = (2 << 0); //ASN.1 INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature [SIGN_R_LEN] > 127) - { - *(uint8Pointer + 1) = SIGN_S_LEN + 1; //ASN.1 INTEGER size - uint8Pointer += 3; //skip INTEGER ID and size - } - else - { - *(uint8Pointer + 1) = SIGN_S_LEN; //ASN.1 INTEGER size - uint8Pointer += 2; //skip INTEGER ID and size - } - memcpy(uint8Pointer, signature + SIGN_R_LEN, SIGN_S_LEN); - - ec = der_encode_to_buffer(&asn_DEF_CertificateRevocationList, certificateRevocationList, - encodedCRL->data, crlMaxSize); - CHECK_COND(ec.encoded > 0, ISSUER_CRL_ENCODER_DER_ENCODE_FAIL); - encodedCRL->len = ec.encoded; - - FUNCTION_CLEAR( - OICFree(crlInfoInDER); - crlInfoInDER = NULL; - ); -} diff --git a/resource/csdk/security/provisioning/ck_manager/src/csr_generator.c b/resource/csdk/security/provisioning/ck_manager/src/csr_generator.c deleted file mode 100644 index 95662e7..0000000 --- a/resource/csdk/security/provisioning/ck_manager/src/csr_generator.c +++ /dev/null @@ -1,278 +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 "csr_generator.h" -#include "pki.h" -#include "oic_malloc.h" - -//ecdsa-with-SHA256 1.2.840.10045.4.3.2 [RFC5759] -static const uint8_t g_ECDSA_WITH_SHA256_OID[] = {0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02}; - -//Elliptic Curve Digital Signature Algorithm (ECDSA) 1.2.840.10045.2.1 [RFC7250] -static const uint8_t g_EC_PUBLIC_KEY_OID[] = {0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01}; - -//secp256r1 1.2.840.10045.3.1.7 [RFC5656] -static const uint8_t g_PRIME_256_V1_OID[] = {0x2A, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}; - -//commonName 2.5.4.3 [RFC2256] -static const uint8_t g_COMMON_NAME_OID[] = {0x55, 0x04, 0x03}; - -PKIError EncodeCSR (const UTF8String_t *subjectName, - const BIT_STRING_t *subjectPublicKey, - const BIT_STRING_t *subjectPrivateKey, - ByteArray *encodedCSR) -{ - FUNCTION_INIT(); - asn_enc_rval_t ec; /* Encoder return value */ - CertificationRequest_t *certificationRequest = NULL; /* Type to encode */ - AttributeTypeAndValue_t *subjTypeAndValue = NULL; - RelativeDistinguishedName_t *subjRDN = NULL; - uint8_t *uint8Pointer = NULL; - ByteArray tbs = BYTE_ARRAY_INITIALIZER; - uint8_t signature[SIGN_FULL_SIZE]; - uint8_t sha256[SHA_256_HASH_LEN]; - uint8_t ReqInfoInDER[CSR_MAX_SIZE]; - - CHECK_NULL(subjectName, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(subjectPublicKey, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(subjectPrivateKey, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(encodedCSR, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(encodedCSR->data, ISSUER_CSR_NULL_PASSED); - CHECK_LESS_EQUAL(CSR_MAX_SIZE, encodedCSR->len, ISSUER_CSR_WRONG_BYTE_ARRAY_LEN); - - /* Allocate the memory */ - certificationRequest = OICCalloc(1, sizeof(CertificationRequest_t)); // not malloc! - CHECK_NULL(certificationRequest, ISSUER_CSR_MEMORY_ALLOC_FAILED); - - subjTypeAndValue = OICCalloc(1, sizeof(AttributeTypeAndValue_t)); - CHECK_NULL(subjTypeAndValue, ISSUER_CSR_MEMORY_ALLOC_FAILED); - - subjRDN = OICCalloc(1, sizeof(RelativeDistinguishedName_t)); - CHECK_NULL(subjRDN, ISSUER_CSR_MEMORY_ALLOC_FAILED); - - //set subject name - subjTypeAndValue->value = *subjectName; - subjTypeAndValue->type.buf = (uint8_t *)g_COMMON_NAME_OID; //2.5.4.3 - subjTypeAndValue->type.size = sizeof(g_COMMON_NAME_OID) / sizeof(g_COMMON_NAME_OID[0]); - ASN_SET_ADD(subjRDN, subjTypeAndValue); - ASN_SEQUENCE_ADD(&(certificationRequest->certificationRequestInfo.subject), subjRDN); - - //set version 0 - certificationRequest->certificationRequestInfo.version = CSR_DEFAULT_VERSION; - - //set signature algorithm - certificationRequest->signatureAlgorithm.algorithm.buf = - (uint8_t *)g_ECDSA_WITH_SHA256_OID; //1.2.840.10045.4.3.2 - certificationRequest->signatureAlgorithm.algorithm.size = - sizeof(g_ECDSA_WITH_SHA256_OID) / sizeof(g_ECDSA_WITH_SHA256_OID[0]); - certificationRequest->signatureAlgorithm.nul = OICCalloc(1, sizeof(NULL_t)); - CHECK_NULL(certificationRequest->signatureAlgorithm.nul, ISSUER_CSR_MEMORY_ALLOC_FAILED); - - //set subject Public Key algorithm - certificationRequest->certificationRequestInfo.subjectPKInfo.algorithm.algorithm.buf = - (uint8_t *)g_EC_PUBLIC_KEY_OID; //1.2.840.10045.2.1 - certificationRequest->certificationRequestInfo.subjectPKInfo.algorithm.algorithm.size = - sizeof(g_EC_PUBLIC_KEY_OID) / sizeof(g_EC_PUBLIC_KEY_OID[0]); - - //set subject Public Key curve - certificationRequest->certificationRequestInfo.subjectPKInfo.algorithm.id_ecPublicKey = - OICCalloc(1, sizeof(OBJECT_IDENTIFIER_t)); - CHECK_NULL(certificationRequest-> - certificationRequestInfo.subjectPKInfo.algorithm.id_ecPublicKey, - ISSUER_CSR_MEMORY_ALLOC_FAILED); - - certificationRequest->certificationRequestInfo.subjectPKInfo.algorithm.id_ecPublicKey->buf = - (uint8_t *)g_PRIME_256_V1_OID; //1.2.840.10045.3.1.7 - certificationRequest->certificationRequestInfo.subjectPKInfo.algorithm.id_ecPublicKey->size = - sizeof(g_PRIME_256_V1_OID) / sizeof(g_PRIME_256_V1_OID[0]); - - //set subject Public Key - certificationRequest->certificationRequestInfo.subjectPKInfo.subjectPublicKey = - *subjectPublicKey; - - //encode TBS to DER - ec = der_encode_to_buffer(&asn_DEF_CertificationRequestInfo, - &(certificationRequest->certificationRequestInfo), - ReqInfoInDER, CSR_MAX_SIZE); - CHECK_COND(ec.encoded > 0, ISSUER_CSR_DER_ENCODE_FAIL); - tbs.len = ec.encoded; - tbs.data = ReqInfoInDER; - GET_SHA_256(tbs, sha256); - CHECK_COND(uECC_sign((subjectPrivateKey->buf) + 1, sha256, signature), - ISSUER_CSR_SIGNATURE_FAIL); - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - - // ECDSA-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } (RFC 5480) - certificationRequest->signature.size = SIGN_FULL_SIZE + 6; - // size for SEQUENCE ID + 2 * INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[0] > 127) - { - certificationRequest->signature.size ++; - } - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[SIGN_R_LEN] > 127) - { - certificationRequest->signature.size ++; - } - certificationRequest->signature.buf = OICCalloc(certificationRequest->signature.size, - sizeof(uint8_t)); - CHECK_NULL(certificationRequest->signature.buf, ISSUER_CSR_MEMORY_ALLOC_FAILED); - *(certificationRequest->signature.buf) = (12 << 2); //ASN.1 SEQUENCE ID - *(certificationRequest->signature.buf + 1) = certificationRequest->signature.size - 2; - //ASN.1 SEQUENCE size - - uint8Pointer = certificationRequest->signature.buf + 2; //skip SEQUENCE ID and size - *uint8Pointer = (2 << 0); //ASN.1 INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature[0] > 127) - { - *(uint8Pointer + 1) = SIGN_R_LEN + 1; //ASN.1 INTEGER size - uint8Pointer += 3; //skip INTEGER ID and size - } - else - { - *(uint8Pointer + 1) = SIGN_R_LEN; //ASN.1 INTEGER size - uint8Pointer += 2; //skip INTEGER ID and size - } - memcpy(uint8Pointer, signature, SIGN_R_LEN); - - uint8Pointer += SIGN_R_LEN; - *uint8Pointer = (2 << 0); //ASN.1 INTEGER ID - - // if first byte of positive INTEGER exceed 127 add 0 byte before - if (signature [SIGN_R_LEN] > 127) - { - *(uint8Pointer + 1) = SIGN_R_LEN + 1; //ASN.1 INTEGER size - uint8Pointer += 3; //skip INTEGER ID and size - } - else - { - *(uint8Pointer + 1) = SIGN_S_LEN; //ASN.1 INTEGER size - uint8Pointer += 2; //skip INTEGER ID and size - } - memcpy(uint8Pointer, signature + SIGN_R_LEN, SIGN_S_LEN); - - ec = der_encode_to_buffer(&asn_DEF_CertificationRequest, certificationRequest, - encodedCSR->data, CSR_MAX_SIZE); - CHECK_COND(ec.encoded > 0, ISSUER_CSR_DER_ENCODE_FAIL); - encodedCSR->len = ec.encoded; - - FUNCTION_CLEAR( - if (subjTypeAndValue) - { - subjTypeAndValue->value.buf = NULL; - subjTypeAndValue->type.buf = NULL; - } - if (certificationRequest) - { - certificationRequest-> - certificationRequestInfo.subjectPKInfo.algorithm.algorithm.buf = NULL; - - certificationRequest->signatureAlgorithm.algorithm.buf = NULL; - - if (certificationRequest-> - certificationRequestInfo.subjectPKInfo.algorithm.id_ecPublicKey) - { - certificationRequest-> - certificationRequestInfo.subjectPKInfo.algorithm.id_ecPublicKey->buf = NULL; - } - } - ASN_STRUCT_FREE(asn_DEF_CertificationRequest, certificationRequest); - certificationRequest = NULL; - ); -} - -PKIError DecodeCSR (const ByteArray *encodedCSR, - UTF8String_t *subjectName, BIT_STRING_t *subjectPublicKey) -{ - FUNCTION_INIT(); - asn_dec_rval_t rval; /* Decoder return value */ - asn_enc_rval_t ec; /* Encoder return value */ - CertificationRequest_t *certificationRequest = NULL; // Type to decode - ByteArray tbs = BYTE_ARRAY_INITIALIZER; - uint8_t sha256[SHA_256_HASH_LEN]; - uint8_t ReqInfoInDER[CSR_MAX_SIZE]; - uint8_t signature[SIGN_FULL_SIZE]; - - CHECK_NULL(encodedCSR, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(encodedCSR->data, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(subjectName, ISSUER_CSR_NULL_PASSED); - CHECK_NULL(subjectPublicKey, ISSUER_CSR_NULL_PASSED); - - rval = ber_decode(0, &asn_DEF_CertificationRequest, (void **)&certificationRequest, - encodedCSR->data, encodedCSR->len); - CHECK_EQUAL(rval.code, RC_OK, ISSUER_CSR_DER_DECODE_FAIL); - - //encode TBS to DER - ec = der_encode_to_buffer(&asn_DEF_CertificationRequestInfo, - &(certificationRequest->certificationRequestInfo), - ReqInfoInDER, CSR_MAX_SIZE); - CHECK_COND(ec.encoded > 0, ISSUER_CSR_DER_ENCODE_FAIL); - tbs.len = ec.encoded; - tbs.data = ReqInfoInDER; - GET_SHA_256(tbs, sha256); - - // ECDSA-Sig-Value ::= SEQUENCE { r INTEGER, s INTEGER } (RFC 5480) - if (*(certificationRequest->signature.buf + 3) > SIGN_R_LEN) //check length of first INTEGER (r) - { - //move to start of second INTEGER (s) - memcpy(signature, certificationRequest->signature.buf + 5, SIGN_R_LEN); - } - else - { - //move to start of second INTEGER (s) - memcpy(signature, certificationRequest->signature.buf + 4, SIGN_R_LEN); - } - memcpy((signature + SIGN_R_LEN), - (certificationRequest->signature.buf + - certificationRequest->signature.size - SIGN_S_LEN), SIGN_S_LEN); - //verify signature - CHECK_COND(uECC_verify(certificationRequest-> - certificationRequestInfo.subjectPKInfo.subjectPublicKey.buf + 1, - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - sha256, signature), ISSUER_CSR_INVALID_SIGNATURE); - - subjectName->size = - certificationRequest->certificationRequestInfo.subject.list.array[0]-> - list.array[0]->value.size; - CHECK_LESS_EQUAL(subjectName->size, CSR_MAX_NAME_SIZE, ISSUER_CSR_TOO_LONG_NAME); - memcpy(subjectName->buf, - certificationRequest->certificationRequestInfo.subject.list.array[0]-> - list.array[0]->value.buf, subjectName->size); - - subjectPublicKey->size = - certificationRequest->certificationRequestInfo.subjectPKInfo.subjectPublicKey.size; - CHECK_EQUAL(subjectPublicKey->size, PUBLIC_KEY_SIZE + 1, ISSUER_CSR_INVALID_KEY_FORMAT); - //additional byte for ASN1_UNCOMPRESSED_KEY_ID - - memcpy(subjectPublicKey->buf, - certificationRequest->certificationRequestInfo.subjectPKInfo.subjectPublicKey.buf, - subjectPublicKey->size); - - FUNCTION_CLEAR( - ASN_STRUCT_FREE(asn_DEF_CertificationRequest, certificationRequest); - ); -} diff --git a/resource/csdk/security/provisioning/ck_manager/tools/SConscript b/resource/csdk/security/provisioning/ck_manager/tools/SConscript deleted file mode 100644 index 1d98120..0000000 --- a/resource/csdk/security/provisioning/ck_manager/tools/SConscript +++ /dev/null @@ -1,59 +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. -# // -# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= -# -# SConscript file for Local PKI google tests - -Import('env') - -import os -import os.path -tools_env = env.Clone() - -src_dir = tools_env.get('SRC_DIR') - -###################################################################### -# Build flags -###################################################################### -tools_env.PrependUnique(CPPPATH = [ - '../include/', - '../../../../../../extlibs/asn1cert', - '../../../../../../extlibs/tinydtls/ecc', - '../../../../../../extlibs/tinydtls/sha2', - '../../../../connectivity/inc/pkix/' - ]) -tools_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) - -tools_env.AppendUnique(LIBS = ['CKManager']) -tools_env.AppendUnique(LIBS = ['asn1']) -tools_env.AppendUnique(LIBS = ['octbstack']) -tools_env.AppendUnique(LIBS = ['tinydtls']) -tools_env.AppendUnique(LIBS = ['connectivity_abstraction']) - -if not env.get('RELEASE'): - tools_env.AppendUnique(CPPDEFINES = ['X509_DEBUG']) - -###################################################################### -# Source files and Targets -###################################################################### -x509_check = tools_env.Program('x509_check', ['x509_check.c']) -x509_issue = tools_env.Program('x509_issue', ['x509_issue.c']) - - - diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/SConscript b/resource/csdk/security/provisioning/ck_manager/unittest/SConscript deleted file mode 100644 index 88f33de..0000000 --- a/resource/csdk/security/provisioning/ck_manager/unittest/SConscript +++ /dev/null @@ -1,98 +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. -# // -# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= - -import os -import os.path - -# SConscript file for Local PKI google tests -gtest_env = SConscript('#extlibs/gtest/SConscript') -pki_test_env = gtest_env.Clone() -src_dir = pki_test_env.get('SRC_DIR') -build_dir = pki_test_env.get('BUILD_DIR') -target_os = pki_test_env.get('TARGET_OS') - -###################################################################### -# Build flags -###################################################################### -pki_test_env.PrependUnique(CPPPATH = ['../include/', - '../include/internal', - '../../include', - '../../include/internal', - '../../../include', - '../../../include/internal', - '../../../../connectivity/inc', - '../../../../connectivity/api', - '../../../../logger/include', - '../../../../stack/include', - '../../../../../oc_logger/include', - '../../../../../../extlibs/asn1cert', - '../../../../../../extlibs/tinydtls', - '../../../../../../extlibs/tinydtls/ecc', - '../../../../../../extlibs/tinydtls/sha2' - ]) - -pki_test_env.AppendUnique(LIBPATH = [pki_test_env.get('BUILD_DIR')]) - -pki_test_env.AppendUnique(LIBS = ['octbstack']) -pki_test_env.AppendUnique(LIBS = ['CKManager']) -pki_test_env.AppendUnique(LIBS = ['asn1']) - -if pki_test_env.get('SECURED') == '1': - pki_test_env.AppendUnique(LIBS = ['tinydtls']) - -if not pki_test_env.get('RELEASE'): - pki_test_env.AppendUnique(CPPDEFINES = ['TB_LOG']) - -###################################################################### -# Source files and Targets -###################################################################### -unittest = pki_test_env.Program('unittest', ['pki_test.cpp', - 'ckm_info_test.cpp', - 'crl_generator_test.cpp', - 'csr_generator_test.cpp']) - -Alias("test", [unittest]) - - - -unittest_src_dir = src_dir + '/resource/csdk/security/provisioning/ck_manager/unittest/test_data/' - -unittest_build_dir = os.path.join(build_dir, 'resource', 'csdk', 'security', 'provisioning', 'ck_manager', 'unittest') -unittest_build_dir = unittest_build_dir.encode('string_escape') -pki_test_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir]) -pki_test_env.Alias("install", pki_test_env.Install( unittest_build_dir, [ unittest_src_dir + '01.der', - unittest_src_dir + 'cacert.der', - unittest_src_dir + 'capub.der', - unittest_src_dir + 'cert_chain.dat', - unittest_src_dir + 'chain.der', - unittest_src_dir + 'CKMInfo.dat' ])) - -pki_test_env.AppendTarget('test') -if pki_test_env.get('TEST') == '1': - if target_os in ['linux']: - out_dir = pki_test_env.get('BUILD_DIR') - result_dir = os.path.join(pki_test_env.get('BUILD_DIR'), 'test_out') + os.sep - if not os.path.isdir(result_dir): - os.makedirs(result_dir) - pki_test_env.AppendENVPath('GTEST_OUTPUT', ['xml:'+ result_dir]) - pki_test_env.AppendENVPath('LD_LIBRARY_PATH', [out_dir]) - ut = pki_test_env.Command ('ut', None, out_dir + '/resource/csdk/security/provisioning/ck_manager/unittest/unittest') -AlwaysBuild ('ut') - diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp deleted file mode 100644 index 66d6cb1..0000000 --- a/resource/csdk/security/provisioning/ck_manager/unittest/ckm_info_test.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/****************************************************************** - * - * 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 - * - * 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 -#include "ckm_info.h" - -#define ISSUER_NAME_SIZE (16) -#define CERT_LEN 469 - -class CKMInfoTest : public ::testing::Test -{ -public: - static void SetUpTestCase() - { - } - - static void TearDownTestCase() - { - } - - static const ByteArray publicKey; - static const ByteArray privateKey; - static const ByteArray derCode ; - static const long nextSN; - static const long crlSerialNum; - static const ByteArray caName; -}; - -const ByteArray CKMInfoTest::publicKey = {(uint8_t[]) -{ - 0x8c, 0xc8, 0x92, 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f, - 0x1a, 0x09, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3, - 0x75, 0x5c, 0xdd, 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36, - 0x8f, 0xc5, 0x7b, 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1 -}, PUBLIC_KEY_SIZE }; - -const ByteArray CKMInfoTest::privateKey = {(uint8_t[]) -{ - 0xd6, 0xc8, 0x92, 0x16, 0x36, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0x3f, 0x14, 0x30, - 0x1a, 0x69, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0xae, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0x36 -}, PRIVATE_KEY_SIZE }; - -const ByteArray CKMInfoTest::derCode = {(uint8_t[]) - { - 0x30, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, - 0xd7, 0x56, 0x8c, 0xfc, 0x53, 0x18, 0xb0, 0xab, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x03, 0x02, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, - 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, - 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, - 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, - 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x1e, 0x17, 0x0d, 0x31, - 0x35, 0x30, 0x33, 0x31, 0x32, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x17, 0x0d, 0x31, 0x37, - 0x30, 0x33, 0x31, 0x31, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30, - 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, - 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, - 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, - 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, - 0x74, 0x64, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, - 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x8c, 0xc8, 0x92, - 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f, 0x1a, 0x09, 0xc5, - 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3, 0x75, 0x5c, 0xdd, - 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36, 0x8f, 0xc5, 0x7b, - 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1, 0xa3, 0x50, 0x30, - 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x5c, 0x0e, 0x30, 0xa8, - 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a, 0x59, - 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x5c, 0x0e, 0x30, - 0xa8, 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a, - 0x59, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, - 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, - 0x02, 0x21, 0x00, 0xf6, 0x79, 0xed, 0x69, 0xd5, 0xe5, 0xba, 0x42, 0x14, 0xfc, 0xce, 0x47, 0xf1, - 0x61, 0x1c, 0x51, 0x11, 0x2b, 0xba, 0x04, 0x70, 0x56, 0x78, 0xaf, 0xa9, 0xa6, 0x98, 0x8f, 0x4b, - 0xa8, 0x11, 0x67, 0x02, 0x20, 0x3a, 0xdf, 0xf1, 0x74, 0xc9, 0x2f, 0xfb, 0x84, 0x46, 0xde, 0xbc, - 0x2d, 0xda, 0xe3, 0x05, 0xb4, 0x81, 0x31, 0x45, 0xf7, 0x3d, 0x71, 0x46, 0x07, 0xa7, 0xd8, 0xcb, - 0xae, 0x1e, 0x1b, 0x1c, 0x5a - }, CERT_LEN }; - -const long CKMInfoTest::nextSN = 0x111111; - -const long CKMInfoTest::crlSerialNum = 0x22222; - -const ByteArray CKMInfoTest::caName = {(uint8_t[]) -{ - 0x1a, 0x1a, 0x1a, 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f -}, ISSUER_NAME_SIZE }; - -//InitCRT test -TEST(CKMInfoTest, InitCRT) -{ - ASSERT_EQ(PKI_SUCCESS, InitCRT()); -} - -//SaveCRT test -TEST(CKMInfoTest, SaveCRT) -{ - ASSERT_EQ(PKI_SUCCESS, SaveCRT()); -} - -//InitCRL test -TEST(CKMInfoTest, InitCRL) -{ - ASSERT_EQ(PKI_SUCCESS, InitCRL()); -} - -//SaveCRL test -TEST(CKMInfoTest, SaveCRL) -{ - ASSERT_EQ(PKI_SUCCESS, SaveCRL()); -} - -//InitCKMInfo test -TEST(CKMInfoTest, InitCKMInfo) -{ - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); -} - -//SaveCKMInfo test -TEST(CKMInfoTest, SaveCKMInfo) -{ - ASSERT_EQ(PKI_SUCCESS, SaveCKMInfo()); -} - -//SetGetNextSerialNumber test -TEST(CKMInfoTest, SetGetNextSerialNumber) -{ - ASSERT_EQ(PKI_SUCCESS, SetNextSerialNumber(CKMInfoTest::nextSN)); - long nSn = 0; - ASSERT_EQ(PKI_SUCCESS, GetNextSerialNumber(&nSn)); - EXPECT_TRUE(nSn == CKMInfoTest::nextSN); -} - -//SetGetCAPrivateKey test -TEST(CKMInfoTest, SetGetCAPrivateKey) -{ - ASSERT_EQ(PKI_SUCCESS, SetCAPrivateKey(&CKMInfoTest::privateKey)); - - ByteArray privateKey = {0,0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - privateKey.data = caPrivKey; - privateKey.len = PRIVATE_KEY_SIZE; - - EXPECT_EQ(PKI_SUCCESS, GetCAPrivateKey(&privateKey)); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::privateKey.data, privateKey.data, PRIVATE_KEY_SIZE)); -} - -//SetGetCAPublicKey test -TEST(CKMInfoTest, SetGetCAPublicKey) -{ - ASSERT_EQ(PKI_SUCCESS, SetCAPublicKey(&CKMInfoTest::publicKey)); - - ByteArray publicKey = {0,0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - - publicKey.data = caPubKey; - publicKey.len = PUBLIC_KEY_SIZE; - - EXPECT_EQ(PKI_SUCCESS, GetCAPublicKey(&publicKey)); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::publicKey.data, publicKey.data, PUBLIC_KEY_SIZE)); -} - -//SetGetCAName test -TEST(CKMInfoTest, SetGetCAName) -{ - ASSERT_EQ(PKI_SUCCESS, SetCAName(&CKMInfoTest::caName)); - - ByteArray caName = {0,0}; - uint8_t caIssName[PUBLIC_KEY_SIZE] = {0}; - - caName.data = caIssName; - caName.len = ISSUER_NAME_SIZE; - - EXPECT_EQ(PKI_SUCCESS, GetCAName(&caName)); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::caName.data, caName.data, ISSUER_NAME_SIZE)); -} - -//SetGetCKMInfo test -TEST(CKMInfoTest, SetGetCKMInfo) -{ - ASSERT_EQ(PKI_SUCCESS, SetCKMInfo(CKMInfoTest::nextSN, CKMInfoTest::crlSerialNum, - &CKMInfoTest::privateKey, &CKMInfoTest::publicKey, &CKMInfoTest::caName)); - - long nSn = 0; - long serialNum = 0; - - ByteArray publicKey = {0,0}; - uint8_t caIssName[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - publicKey.data = caPubKey; - publicKey.len = PUBLIC_KEY_SIZE; - - ByteArray privateKey = {0,0}; - privateKey.data = caPrivKey; - privateKey.len = PRIVATE_KEY_SIZE; - - ByteArray caName = {0,0}; - caName.data = caIssName; - caName.len = ISSUER_NAME_SIZE; - - EXPECT_EQ(PKI_SUCCESS, GetCKMInfo(&nSn, &serialNum, - &privateKey, &publicKey, &caName)); - - EXPECT_TRUE(nSn == CKMInfoTest::nextSN); - EXPECT_TRUE(serialNum == CKMInfoTest::crlSerialNum); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::privateKey.data, privateKey.data, PRIVATE_KEY_SIZE)); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::publicKey.data, publicKey.data, PUBLIC_KEY_SIZE)); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::caName.data, caName.data, ISSUER_NAME_SIZE)); -} - -//SetGetCACertificate test -TEST(CKMInfoTest, SetGetCACertificate) -{ - ASSERT_EQ(PKI_SUCCESS, SetCACertificate(&CKMInfoTest::derCode)); - - ByteArray der = {0,0}; - uint8_t caCert[CERT_LEN] = {0}; - der.data = caCert; - der.len = CERT_LEN; - EXPECT_TRUE(NULL != der.data); - EXPECT_EQ(PKI_SUCCESS, GetCACertificate(&der)); - EXPECT_TRUE(0 == memcmp(CKMInfoTest::derCode.data, der.data, CERT_LEN)); -} - -//SetGetCRLSerialNumber test -TEST(CKMInfoTest, SetGetCRLSerialNumber) -{ - ASSERT_EQ(PKI_SUCCESS, SetCRLSerialNumber(CKMInfoTest::crlSerialNum)); - long serialNum = 0; - ASSERT_EQ(PKI_SUCCESS, GetCRLSerialNumber(&serialNum)); - EXPECT_TRUE(serialNum == CKMInfoTest::crlSerialNum); -} - -//SetGetNumberOfRevoked test -TEST(CKMInfoTest, SetGetNumberOfRevoked) -{ - const long NUM_OF_REVOKED = 5; - ASSERT_EQ(PKI_SUCCESS, SetNumberOfRevoked(NUM_OF_REVOKED)); - long numRev = 0; - ASSERT_EQ(PKI_SUCCESS, GetNumberOfRevoked(&numRev)); - EXPECT_TRUE(numRev == NUM_OF_REVOKED); -} - -//SetCertificateRevocationList test -TEST(CKMInfoTest, SetCertificateRevocationList) -{ - ASSERT_EQ(PKI_SUCCESS, SetCertificateRevocationList(&CKMInfoTest::derCode)); -} - -//CloseCKMInfo test -TEST(CKMInfoTest, CloseCKMInfo) -{ - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp deleted file mode 100644 index 93d0343..0000000 --- a/resource/csdk/security/provisioning/ck_manager/unittest/crl_generator_test.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/****************************************************************** - * - * 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 - * - * 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 -#include -#include "crl_generator.h" - -static const ByteArray privateKey = {(uint8_t[]) -{ - 0xd6, 0xc8, 0x92, 0x16, 0x36, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0x3f, 0x14, 0x30, - 0x1a, 0x69, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0xae, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0x36 -}, PRIVATE_KEY_SIZE }; - -//GenerateCRL test -TEST(CRLGeneratorTest, GenerateCRL) -{ - uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z"; - uint32_t numberOfRevoked = 2; - uint32_t revokedNumbers[2]; - const uint8_t *revocationDates[2]; - CertificateRevocationInfo_t *certificateRevocationInfo = NULL; - UTF8String_t *issuerName = NULL; - UTCTime_t *thisUpdateTime = NULL; - ByteArray encodedCRL = BYTE_ARRAY_INITIALIZER; - BIT_STRING_t issuerPrivateKey; - - revokedNumbers[0] = 100; // serial number of first revoked certificate - revokedNumbers[1] = 200; // serial number of second revoked certificate - - revocationDates[0] = (const uint8_t *)"130101000001Z"; - revocationDates[1] = (const uint8_t *)"130101000002Z"; - - certificateRevocationInfo = (CertificateRevocationInfo_t *)OICCalloc(numberOfRevoked, - sizeof(CertificateRevocationInfo_t)); - EXPECT_TRUE(NULL != certificateRevocationInfo); - - issuerName = (UTF8String_t *)OICCalloc(1, sizeof(UTF8String_t)); - EXPECT_TRUE(NULL != issuerName); - - thisUpdateTime = (UTCTime_t *)OICCalloc(1, sizeof(UTCTime_t)); - EXPECT_TRUE(NULL != thisUpdateTime); - - encodedCRL.data = (uint8_t *)OICCalloc(1, - (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4))); - EXPECT_TRUE(NULL != encodedCRL.data); - encodedCRL.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)); - - issuerPrivateKey.size = PRIVATE_KEY_SIZE + 1; - issuerPrivateKey.buf = (uint8_t *)OICCalloc((issuerPrivateKey.size), sizeof(uint8_t)); - EXPECT_TRUE(NULL != issuerPrivateKey.buf); - - if(NULL != certificateRevocationInfo && NULL != issuerName && - NULL != thisUpdateTime && NULL != encodedCRL.data && NULL != issuerPrivateKey.buf) - { - ByteArray issName = BYTE_ARRAY_INITIALIZER; - issName.data = (uint8_t *)"Issuer"; - issName.len = strlen((char *)issName.data); - - issuerName->buf = issName.data; - issuerName->size = issName.len; - - for (size_t i = 0; i < numberOfRevoked; i++ ) - { - certificateRevocationInfo[i].userCertificate = revokedNumbers[i]; - certificateRevocationInfo[i].revocationDate.buf = (uint8_t *)revocationDates[i]; - certificateRevocationInfo[i].revocationDate.size = - strlen((const char *)revocationDates[i]); - } - - memcpy((issuerPrivateKey.buf) + 1, privateKey.data, PRIVATE_KEY_SIZE); - - EXPECT_EQ(PKI_SUCCESS, GenerateCRL(issuerName, thisUpdateTime, numberOfRevoked, - certificateRevocationInfo, &issuerPrivateKey, &encodedCRL)); - } - - OICFree(certificateRevocationInfo); - OICFree(issuerName); - OICFree(thisUpdateTime); -} - diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp deleted file mode 100644 index c94f3c5..0000000 --- a/resource/csdk/security/provisioning/ck_manager/unittest/csr_generator_test.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/****************************************************************** - * - * 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 - * - * 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 -#include "ck_manager.h" -#include "crl_generator.h" -#include "pki.h" -#include "oic_malloc.h" -#include "ckm_info.h" -#define ASN1_UNCOMPRESSED_KEY_ID (0x04) - -//EncodeDecodeCSR test -TEST(CSRGeneratorTest, EncodeDecodeCSR) -{ - uint8_t csrData[CSR_MAX_SIZE] = {0}; - uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0}; - ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER; - uint8_t *subjName = (uint8_t *)"Subject05"; - UTF8String_t* subjectName = NULL; - BIT_STRING_t* subjectPublicKey = NULL; - BIT_STRING_t* subjectPrivateKey = NULL; - ByteArray csrDer = BYTE_ARRAY_INITIALIZER; - BIT_STRING_t* subjectPublicKeyOut = NULL; - UTF8String_t* subjectNameOut = NULL; - uint8_t uint8SubjectName[ISSUER_MAX_NAME_SIZE]; - uint8_t uint8SubjectPublicKey[PUBLIC_KEY_SIZE + 1]; - - csrDer.data = csrData; - csrDer.len = CSR_MAX_SIZE; - - pubKeySubj.data = subjPubKey; - pubKeySubj.len = sizeof(subjPubKey); - privKeySubj.data = subjPrivKey; - privKeySubj.len = sizeof(subjPrivKey); - - ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeySubj, &pubKeySubj)); - - subjectName = (UTF8String_t*)OICCalloc(1, sizeof(UTF8String_t)); - EXPECT_TRUE(NULL != subjectName); - - subjectPublicKey = (BIT_STRING_t*)OICCalloc(1, sizeof(BIT_STRING_t)); - EXPECT_TRUE(NULL != subjectPublicKey); - - subjectPrivateKey = (BIT_STRING_t*)OICCalloc(1, sizeof(BIT_STRING_t)); - EXPECT_TRUE(NULL != subjectPrivateKey); - - if(NULL != subjectName && NULL != subjectPublicKey && NULL != subjectPrivateKey) - { - subjectName->buf = (uint8_t *)subjName; - subjectName->size = strlen((const char *)subjectName->buf); - - subjectPrivateKey->size = PRIVATE_KEY_SIZE + 1; - subjectPrivateKey->buf = (uint8_t *)OICCalloc((subjectPrivateKey->size), sizeof(uint8_t)); - EXPECT_TRUE(NULL != subjectPrivateKey->buf); - - subjectPublicKey->size = PUBLIC_KEY_SIZE + 1; - subjectPublicKey->buf = (uint8_t *)OICCalloc(subjectPublicKey->size, sizeof(uint8_t)); - EXPECT_TRUE(NULL != subjectPublicKey->buf); - - if(NULL!= subjectPublicKey->buf && NULL != subjectPrivateKey->buf) - { - memcpy((subjectPrivateKey->buf) + 1, subjPrivKey, PRIVATE_KEY_SIZE); - memcpy((subjectPublicKey->buf) + 1, subjPubKey, PUBLIC_KEY_SIZE); - - EXPECT_EQ(PKI_SUCCESS, EncodeCSR(subjectName, subjectPublicKey, subjectPrivateKey, &csrDer)); - } - } - - subjectPublicKeyOut = (BIT_STRING_t*)OICCalloc(1, sizeof(BIT_STRING_t)); - EXPECT_TRUE(NULL != subjectPublicKey); - - subjectNameOut = (UTF8String_t*)OICCalloc(1, sizeof(UTF8String_t)); - EXPECT_TRUE(NULL != subjectNameOut); - - if(NULL != subjectNameOut && NULL != subjectPublicKeyOut) - { - subjectNameOut->buf = uint8SubjectName; - subjectPublicKeyOut->buf = uint8SubjectPublicKey; - EXPECT_EQ(PKI_SUCCESS, DecodeCSR(&csrDer, subjectNameOut, subjectPublicKeyOut)); - } - - OICFree(subjectName); - OICFree(subjectPublicKey); - OICFree(subjectNameOut); - OICFree(subjectPublicKeyOut); - if (subjectPrivateKey) - { - OICFree(subjectPrivateKey->buf); - OICFree(subjectPrivateKey); - } -} diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp b/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp deleted file mode 100644 index 649888a..0000000 --- a/resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp +++ /dev/null @@ -1,1059 +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 -#include -#include -#include -#include -#include "ocstack.h" - -#include "cert_generator.h" -#include "ck_manager.h" -#include "pki.h" -#include "sn_store.h" -#include "der_dec.h" -#include "crl.h" -#include "crl_generator.h" -#include "crlresource.h" -#include "ckm_info.h" - - -#define RUNS 1 -#define MAX_LEN 1000 -#define TEST_SN 50 -#define READ_WRITE_BLOCK_N 1ul -#define N_LENGTH_BYTES 3 - -const char *CKMI_PS_FILE_NAME = "CKMInfo.dat"; - -#define CRL_DEFAULT_CRL_ID 1 -#define CRL_DEFAULT_THIS_UPDATE "150101000000Z" -#define CRL_DEFAULT_CRL_DATA "-" - -#define NUMBER_OF_REVOKED 2 - -OCPersistentStorage ps = { NULL, NULL, NULL, NULL, NULL}; - -//#define NUM_ACE_FOR_WILDCARD_IN_CKM1_JSON (2) - -FILE* ckm_fopen(const char * /*path*/, const char *mode) -{ - return fopen(CKMI_PS_FILE_NAME, mode); -} - -#define STRINGIZE2(x) #x -#define STRINGIZE(x) STRINGIZE2(x) - -static char* resolve_file_path(const char* filename ) -{ - int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(filename) + 1; - char *filepath = (char *)OICCalloc(1, len); - - if (!filepath) - { - printf("filepath memory allocation failed. \n"); - return NULL; - } - int ret = snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), filename); - return filepath; -} - -void SetPersistentHandler(OCPersistentStorage *ps) -{ - if(ps) - { - ps->open = ckm_fopen; - ps->read = fread; - ps->write = fwrite; - ps->close = fclose; - ps->unlink = unlink; - } -} - -// Length of test certificate -#define SIMPLE_CRT_LEN 469 - -class PKITest : public ::testing::Test -{ -public: - static void SetUpTestCase() - { - SetPersistentHandler(&ps); - OCStackResult res = OCRegisterPersistentStorageHandler(&ps); - ASSERT_TRUE(res == OC_STACK_OK); - } - - static void TearDownTestCase() - { - } - - static CertificateX509 g_certificate; - - static const ByteArray g_caPublicKey; - - static const ByteArray g_derCode ; - - static ByteArray g_serNum; -}; - -CertificateX509 PKITest::g_certificate; - -const ByteArray PKITest::g_derCode = {(uint8_t[]) - { - 0x30, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, - 0xd7, 0x56, 0x8c, 0xfc, 0x53, 0x18, 0xb0, 0xab, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, - 0x3d, 0x04, 0x03, 0x02, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, - 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, - 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, - 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, - 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x1e, 0x17, 0x0d, 0x31, - 0x35, 0x30, 0x33, 0x31, 0x32, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x17, 0x0d, 0x31, 0x37, - 0x30, 0x33, 0x31, 0x31, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30, - 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, - 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, - 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, - 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, - 0x74, 0x64, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, - 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x8c, 0xc8, 0x92, - 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f, 0x1a, 0x09, 0xc5, - 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3, 0x75, 0x5c, 0xdd, - 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36, 0x8f, 0xc5, 0x7b, - 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1, 0xa3, 0x50, 0x30, - 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x5c, 0x0e, 0x30, 0xa8, - 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a, 0x59, - 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x5c, 0x0e, 0x30, - 0xa8, 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a, - 0x59, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, - 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, - 0x02, 0x21, 0x00, 0xf6, 0x79, 0xed, 0x69, 0xd5, 0xe5, 0xba, 0x42, 0x14, 0xfc, 0xce, 0x47, 0xf1, - 0x61, 0x1c, 0x51, 0x11, 0x2b, 0xba, 0x04, 0x70, 0x56, 0x78, 0xaf, 0xa9, 0xa6, 0x98, 0x8f, 0x4b, - 0xa8, 0x11, 0x67, 0x02, 0x20, 0x3a, 0xdf, 0xf1, 0x74, 0xc9, 0x2f, 0xfb, 0x84, 0x46, 0xde, 0xbc, - 0x2d, 0xda, 0xe3, 0x05, 0xb4, 0x81, 0x31, 0x45, 0xf7, 0x3d, 0x71, 0x46, 0x07, 0xa7, 0xd8, 0xcb, - 0xae, 0x1e, 0x1b, 0x1c, 0x5a - }, SIMPLE_CRT_LEN }; - - -const ByteArray PKITest::g_caPublicKey = {(uint8_t[]) -{ - 0x8c, 0xc8, 0x92, 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f, - 0x1a, 0x09, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3, - 0x75, 0x5c, 0xdd, 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36, - 0x8f, 0xc5, 0x7b, 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1 -}, PUBLIC_KEY_SIZE }; - - -ByteArray PKITest::g_serNum = {(uint8_t[SERIAL_NUMBER_MAX_LEN]) {0}, SERIAL_NUMBER_MAX_LEN}; - -//registering persistent storage test -TEST(CKManager, RegisterPersistentStorage) -{ - SetPersistentHandler(&ps); - ASSERT_EQ(OC_STACK_OK, OCRegisterPersistentStorageHandler(&ps)); -} - -//check decoding predefined certificate -TEST(X509Certificate, DecodeTest) -{ - ByteArray code = PKITest::g_derCode; - - ASSERT_EQ(DecodeCertificate(code, &PKITest::g_certificate), PKI_SUCCESS); - code.data = NULL; - ASSERT_NE(DecodeCertificate(code, &PKITest::g_certificate), PKI_SUCCESS); -} - -//check decoding of random symbols sequence -TEST(X509Certificate, RandomDecode) -{ - srand((unsigned int)time(NULL)); - - ByteArray code; - INIT_BYTE_ARRAY(code); - - for (unsigned int i = 0; i < RUNS; i++) - { - code.len = (size_t)((size_t)rand() % MAX_LEN); - code.data = (uint8_t *)malloc(code.len * sizeof(uint8_t)); - - EXPECT_NE(code.data, (uint8_t *)NULL); - - for (unsigned int j = 0; j < code.len; j++) - { - code.data[j] = (uint8_t)(rand() % 128 + 1); - } - - EXPECT_NE(PKI_SUCCESS, DecodeCertificate(code, &PKITest::g_certificate)); - - free(code.data); - } -} -//testing validity check of predefined certificate -TEST(X509Certificate, testCheckValidity) -{ - CertificateX509 tempCrt; - ASSERT_EQ(PKI_SUCCESS, DecodeCertificate(PKITest::g_derCode, &tempCrt)); - ASSERT_EQ(PKI_SUCCESS, CheckValidity(tempCrt.validFrom, tempCrt.validTo)); - ByteArray temp = tempCrt.validTo; - - tempCrt.validTo = tempCrt.validFrom; - tempCrt.validFrom = temp; - ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckValidity(tempCrt.validFrom, tempCrt.validTo)); -} - -//testing signature check of predefined certificate -TEST(X509Certificate, CheckSignature) -{ - ByteArray code = PKITest::g_derCode; - - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(code, PKITest::g_caPublicKey)); - code.data = NULL; - ASSERT_NE(PKI_SUCCESS, CheckCertificate(code, PKITest::g_caPublicKey)); -} - -//test saving certificate into file -TEST_F(PKITest, DERCertificateFile) -{ - uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - ByteArray certDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - certDer.data = derData; - certDer.len = ISSUER_MAX_CERT_SIZE; - - pubKeyIss.data = caPubKey; - pubKeyIss.len = sizeof(caPubKey); - privKeyIss.data = caPrivKey; - privKeyIss.len = sizeof(caPrivKey); - rootName.data = (uint8_t *)"ROOT1"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - - for (int i = 1; i <= RUNS; i++) - { - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss)); - ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i)); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer)); - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - ASSERT_EQ(PKI_SUCCESS, GenerateDERCertificateFile (&certDer, "der_cert")); - } - ASSERT_EQ(CloseCKMInfo(), PKI_SUCCESS); -} - -//test checking time validity of generated certificate -TEST_F(PKITest, TimeValidity) -{ - uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - ByteArray certDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKey = BYTE_ARRAY_INITIALIZER; - ByteArray privKey = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - privKey.data = caPrivKey; - privKey.len = sizeof(caPrivKey); - - certDer.data = derData; - certDer.len = sizeof(derData); - - pubKey.data = caPubKey; - pubKey.len = sizeof(caPubKey); - - rootName.data = (uint8_t *)"ROOT3"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - - for (int i = 1; i <= RUNS; i++) - { - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKey, &pubKey)); - ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i)); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - - ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer)); - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKey)); - - certDer.len = sizeof(derData); - ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, (uint8_t *)"130101000000Z", &certDer)); - ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckCertificate(certDer, pubKey)); - - certDer.len = sizeof(derData); - ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate((uint8_t *)"170101000000Z", 0, &certDer)); - ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckCertificate(certDer, pubKey)); - } - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//testing certificate generation by certificate signing request -TEST_F(PKITest, CertificateSigningRequest) -{ - uint8_t certData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t csrData[CSR_MAX_SIZE] = {0}; - uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - uint8_t *subjName = (uint8_t *)"Subject05"; - - ByteArray certDer = BYTE_ARRAY_INITIALIZER; - ByteArray csrDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - certDer.data = certData; - certDer.len = sizeof(certData); - csrDer.data = csrData; - csrDer.len = CSR_MAX_SIZE; - - pubKeyIss.data = caPubKey; - pubKeyIss.len = sizeof(caPubKey); - privKeyIss.data = caPrivKey; - privKeyIss.len = sizeof(caPrivKey); - pubKeySubj.data = subjPubKey; - pubKeySubj.len = sizeof(subjPubKey); - privKeySubj.data = subjPrivKey; - privKeySubj.len = sizeof(subjPrivKey); - rootName.data = (uint8_t *)"ROOT2"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - - ASSERT_EQ(GenerateCAKeyPair(&privKeyIss, &pubKeyIss), PKI_SUCCESS); - ASSERT_EQ(SetSerialNumber(1), PKI_SUCCESS); - ASSERT_EQ(SetRootName(rootName), PKI_SUCCESS); - - for (int i = 1; i <= RUNS; i++) - { - ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeySubj, &pubKeySubj)); - ASSERT_EQ(PKI_SUCCESS, GenerateCSR(subjName, subjPubKey, subjPrivKey, &csrDer)); - ASSERT_EQ(PKI_SUCCESS, GenerateCertificateByCSR(&csrDer, &certDer)); - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - certDer.data[0]++; - ASSERT_NE(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - certDer.data[0]--; - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - } - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//test public key structure parsing -TEST(X509Certificate, testParsePublicKey) -{ - ASSERT_EQ(PKI_SUCCESS, ParsePublicKey((ByteArray*)&PKITest::g_caPublicKey)); - - size_t length = 3; - uint8_t shortAr[length]; - ByteArray shortArray = {shortAr, length}; - ASSERT_EQ(PKI_WRONG_ARRAY_LEN, ParsePublicKey(&shortArray)); - - uint8_t uncompressed[PUBLIC_KEY_SIZE + 2]; - uncompressed[0] = 0; - uncompressed[1] = ASN1_UNCOMPRESSED_KEY; - memcpy(&uncompressed[2], PKITest::g_caPublicKey.data, PUBLIC_KEY_SIZE); - ByteArray uncomprArr = {uncompressed, PUBLIC_KEY_SIZE+2}; - ParsePublicKey(&uncomprArr); - ASSERT_EQ((size_t)PUBLIC_KEY_SIZE, uncomprArr.len); - ASSERT_EQ(0, memcmp(uncomprArr.data, PKITest::g_caPublicKey.data, PUBLIC_KEY_SIZE)); -} - -//test checking of certificate generated by OpenSSL -TEST(OpenSSLCompatibility, verifyOpenSslCertSign) -{ - struct stat st; - char *fpath = NULL; - uint8_t crtData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t pubKeyData[PUBLIC_KEY_SIZE] = {0}; - ByteArray crtDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKey = BYTE_ARRAY_INITIALIZER; - CertificateX509 certificate; - - crtDer.data = crtData; - crtDer.len = sizeof(crtData); - pubKey.data = pubKeyData; - pubKey.len = sizeof(pubKeyData); - - //open file - fpath = resolve_file_path("/01.der"); - int fileCert = open(fpath, O_RDONLY); - OICFree(fpath); - - ASSERT_TRUE(fileCert != -1); - //get status - ASSERT_TRUE(fstat(fileCert, &st) == 0); - //read the content - int res = read(fileCert, crtDer.data, crtDer.len); - ASSERT_NE(-1, res); - EXPECT_EQ(st.st_size, res); - close(fileCert); - - //open file - fpath = resolve_file_path("/capub.der"); - int fileKey = open(fpath, O_RDONLY); - OICFree(fpath); - ASSERT_TRUE(fileKey != -1); - //get status - ASSERT_TRUE(fstat(fileKey, &st) == 0); - - if(st.st_size > PUBLIC_KEY_SIZE) - { - ASSERT_NE(-1, lseek(fileKey, (st.st_size - PUBLIC_KEY_SIZE), SEEK_SET)); - } - - //read the content - res = read(fileKey, pubKey.data, pubKey.len); - ASSERT_NE(-1, res); - EXPECT_EQ(PUBLIC_KEY_SIZE, res); - close(fileKey); - - EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtDer, &certificate)); - EXPECT_EQ(PKI_SUCCESS, CheckCertificate(crtDer, pubKey)); -} - -//test parsing of certificate chain generated by OpenSSL -TEST(CertificateChain, LoadCertificateChain) -{ - char* fpath = NULL; - ByteArray crtChainDer[MAX_CHAIN_LEN] = {{0,0},}; - CertificateX509 crtChain[MAX_CHAIN_LEN] = {{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}},}; - ByteArray msg = BYTE_ARRAY_INITIALIZER; - uint8_t chainLength; - - fpath = resolve_file_path("/cert_chain.dat"); - FILE *file = fopen(fpath, "rb"); - OICFree(fpath); - ASSERT_TRUE(file != NULL); - - while (!feof (file)) - { - msg.data = (uint8_t *) realloc (msg.data, msg.len + 1); - msg.data[msg.len] = fgetc (file); - msg.len++; - } - msg.len--; - fclose (file); - INC_BYTE_ARRAY(msg, 3); - EXPECT_EQ(PKI_SUCCESS, LoadCertificateChain (msg, crtChainDer, &chainLength)); -#ifdef X509_DEBUG - printf("chain len: %d\n", chainLength); -#endif - EXPECT_EQ(PKI_UNKNOWN_OID, ParseCertificateChain (crtChainDer, crtChain, chainLength)); - - free(msg.data - 3); -} - -//test checking CA certificate generated by OpenSSL -TEST(OpenSSLCompatibility, testOpenSSLCertificate) -{ - char* fpath = NULL; - struct stat st; - ByteArray crtDer = BYTE_ARRAY_INITIALIZER; - uint8_t crtData[ISSUER_MAX_CERT_SIZE] = {0}; - - crtDer.data = crtData; - crtDer.len = sizeof(crtData); - - //open file - fpath = resolve_file_path("/cacert.der"); - int fd = open(fpath, O_RDONLY); - OICFree(fpath); - ASSERT_TRUE(fd != -1); - //get status - ASSERT_TRUE(fstat(fd, &st) == 0); - - //read the content - int res = read(fd, crtDer.data, crtDer.len); - ASSERT_NE(-1, res); - ASSERT_EQ(st.st_size, res); - close(fd); - - crtDer.len = st.st_size; - - #ifdef X509_DEBUG - printf("Length of cert: %lu\n", crtDer.len); - #endif - EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtDer, &PKITest::g_certificate)); -} - -//test signatures checking of certificate chain generated by OpenSSL -TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain) -{ - struct stat st; - ByteArray crtChainDer[MAX_CHAIN_LEN] = {{0,0},}; - CertificateX509 crtChain[MAX_CHAIN_LEN] = {{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}},}; - ByteArray msg = BYTE_ARRAY_INITIALIZER; - uint8_t chainLength; - - char* chainPath = resolve_file_path("/chain.der"); - FILE *fileChain = fopen(chainPath, "rb"); - OICFree(chainPath); - ASSERT_TRUE(fileChain != NULL); - - //get the length - ASSERT_NE(-1, fseek(fileChain, 0, SEEK_END)); - int len = ftell(fileChain); - ASSERT_NE(-1, len); - msg.len = (size_t) len; - ASSERT_NE(-1, fseek(fileChain, 0, SEEK_SET)); - //allocate memory - msg.data = (uint8_t*)malloc(msg.len+1); - //read the content - ASSERT_EQ(READ_WRITE_BLOCK_N, fread(msg.data, msg.len, READ_WRITE_BLOCK_N, fileChain)); - - fclose (fileChain); - - INC_BYTE_ARRAY(msg, 3); - EXPECT_EQ(PKI_SUCCESS, LoadCertificateChain(msg, crtChainDer, &chainLength)); - EXPECT_EQ(3, chainLength); - #ifdef X509_DEBUG - printf("Length of the chain: %d\n", chainLength); - #endif - - EXPECT_EQ(PKI_SUCCESS, ParseCertificateChain(crtChainDer, crtChain, chainLength)); - - ByteArray caPubKey = BYTE_ARRAY_INITIALIZER; - uint8_t pubKeyData[PUBLIC_KEY_SIZE] = {0}; - - caPubKey.data = pubKeyData; - caPubKey.len = sizeof(pubKeyData); - - //open file - char* fpath = resolve_file_path("/capub.der"); - int fileKey = open(fpath, O_RDONLY); - OICFree(fpath); - ASSERT_TRUE(fileKey != -1); - //get status - ASSERT_TRUE(fstat(fileKey, &st) == 0); - - if(st.st_size > PUBLIC_KEY_SIZE) - { - ASSERT_NE(-1, lseek(fileKey, (st.st_size - PUBLIC_KEY_SIZE), SEEK_SET)); - } - - //read the content - int res = read(fileKey, caPubKey.data, caPubKey.len); - ASSERT_NE(-1, res); - EXPECT_EQ(PUBLIC_KEY_SIZE, res); - close(fileKey); - - EXPECT_EQ(PKI_SUCCESS, CheckCertificateChain(crtChain, chainLength, caPubKey)); - - free(msg.data - 3); -} - -//testing correctness of decoding certificate length from ASN.1 structure -TEST(CRL, testDecodeLength) -{ - ByteArray cert = BYTE_ARRAY_INITIALIZER; - size_t length(0); - EXPECT_EQ(PKI_NULL_PASSED, DecodeLength(&cert, &length)); - - //a simple DER - size_t derLength = (size_t)rand() % LEN_LONG; - cert.len = derLength + 2; - uint8_t *certData = (uint8_t*)malloc(cert.len); - cert.data = certData; - cert.data[0] = (uint8_t)0x30; //mixed types - cert.data[1] = (uint8_t)(derLength & 0xff); - EXPECT_EQ(PKI_SUCCESS, DecodeLength(&cert, &length)); - EXPECT_EQ(derLength, length); - free(certData); -} - -//testing serial number storage -TEST(CRL, StoreSerialNumber) -{ - uint8_t data[10] = {0x01, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03}; - const ByteArray sn = { data, sizeof(data) / sizeof(uint8_t)}; - int i; - for (i = 0; i < 400; i++) - { - sn.data[0] = i % 20; - ASSERT_EQ(PKI_SUCCESS, StoreSerialNumber(sn)); - } - ASSERT_EQ(PKI_CERT_REVOKED, CheckSerialNumber(sn)); - - sn.data[1] = 0x01; - ASSERT_EQ(PKI_SUCCESS, CheckSerialNumber(sn)); - - FreeSNStore(); -} -#ifdef ARDUINO_MEMORY_DEBUG -//testing memory allocation fault handling at Arduino -TEST(SNStore, MemoryOverflow) -{ - uint8_t data[10] = {0x01, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03}; - const ByteArray sn = { data, sizeof(data) / sizeof(uint8_t)}; - int i; - PKIError res; - do - { - res = StoreSerialNumber(sn); - } - while (res == PKI_SUCCESS); - ASSERT_EQ(PKI_MEMORY_ALLOC_FAILED, res); - - FreeSNStore(); -} -#endif /* ARDUINO_MEMORY_DEBUG */ - -//testing next certificate serial number handling by "CKM info" unit -TEST_F(PKITest, CAInitAndSerialNum) -{ - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - long serialNum = (long)((long)rand() % (MAX_LEN - 1) + 1); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - //all the serials should start from - ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(serialNum)); - long nextSerial; - ASSERT_EQ(PKI_SUCCESS, GetNextSerialNumber(&nextSerial)); - ASSERT_EQ(nextSerial, serialNum); - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//testing CA name handling by "CKM info" unit -TEST_F(PKITest, testCAName) -{ - ByteArray caName = BYTE_ARRAY_INITIALIZER; - caName.len = (size_t)((size_t)rand() % (ISSUER_MAX_NAME_SIZE - 1) + 1); - caName.data = (uint8_t*)malloc(caName.len); - size_t i; - for(i = 0; i < caName.len; i++){ - caName.data[i] = (uint8_t)(rand() % 128); - } - EXPECT_EQ(PKI_SUCCESS, InitCKMInfo()); - EXPECT_EQ(PKI_SUCCESS, SetRootName(caName)); - ByteArray getName = BYTE_ARRAY_INITIALIZER; - uint8_t uint8CAName[ISSUER_MAX_NAME_SIZE] = {0}; - getName.data = uint8CAName; - getName.len = ISSUER_MAX_NAME_SIZE; - EXPECT_EQ(PKI_SUCCESS, GetCAName(&getName)); - EXPECT_EQ(0, memcmp(caName.data, getName.data, caName.len)); - free(caName.data); - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//testing key pair generation and storing by "CKM info" unit -TEST_F(PKITest, testKeyPair) -{ - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - rootName.data = (uint8_t *)"ROOT"; - rootName.len = strlen((char *)rootName.data); - SetRootName(rootName); - - //first test the GenerateCAKeyPair - this writes to the CA storage - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - privKeyIss.len = PRIVATE_KEY_SIZE; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - privKeyIss.data = caPrivKey; - - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - pubKeyIss.len = PUBLIC_KEY_SIZE; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - pubKeyIss.data = caPubKey; - - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss)); - - ByteArray keyCheck = BYTE_ARRAY_INITIALIZER; - keyCheck.len = PUBLIC_KEY_SIZE; - uint8_t keyCheckData[PUBLIC_KEY_SIZE] = {0}; - keyCheck.data = keyCheckData; - ASSERT_EQ(PKI_SUCCESS, GetCAPrivateKey(&keyCheck)); - ASSERT_EQ(0, memcmp(keyCheck.data, privKeyIss.data, PRIVATE_KEY_SIZE)); - - ASSERT_EQ(PKI_SUCCESS, GetCAPublicKey(&keyCheck)); - ASSERT_EQ(0, memcmp(keyCheck.data, pubKeyIss.data, PUBLIC_KEY_SIZE)); - - //now test the GenerateKeyPair - does not write to the CA storage - ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeyIss, &pubKeyIss)); - - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - ASSERT_EQ(PKI_SUCCESS, GetCAPrivateKey(&keyCheck)); - ASSERT_NE(0, memcmp(keyCheck.data, privKeyIss.data, PRIVATE_KEY_SIZE)); - - ASSERT_EQ(PKI_SUCCESS, GetCAPublicKey(&keyCheck)); - ASSERT_NE(0, memcmp(keyCheck.data, pubKeyIss.data, PUBLIC_KEY_SIZE)); - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//testing CRL encoding -TEST_F(PKITest, testEncodeCRL) -{ - CertificateList crl; - - uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z"; - uint32_t numberOfRevoked = 0; - uint32_t revokedNumbers[2]; - const uint8_t *revocationDates[2]; - - ByteArray code = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - pubKeyIss.data = caPubKey; - pubKeyIss.len = PUBLIC_KEY_SIZE; - privKeyIss.data = caPrivKey; - privKeyIss.len = PRIVATE_KEY_SIZE; - - numberOfRevoked = 2; - - revokedNumbers[0] = 100; // serial number of first revoked certificate - revokedNumbers[1] = 200; // serial number of second revoked certificate - revocationDates[0] = (const uint8_t *)"130101000001Z"; - revocationDates[1] = (const uint8_t *)"130101000002Z"; - - rootName.data = (uint8_t *)"ROOT2"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss)); - - code.data = (uint8_t *)calloc(1, - (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4))); - code.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)); - - EXPECT_EQ(PKI_SUCCESS,CKMIssueCRL(uint8ThisUpdateTime, numberOfRevoked, revokedNumbers, - revocationDates,&code)); - EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (code, &crl, pubKeyIss)); -#ifdef X509_DEBUG - PrintSNStore(); - PrintCRL(&crl); -#endif - - FreeSNStore(); - free(code.data); - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//check correctness of certificate revocation by CKMIssueCRL() and CKMRevocateCertificate() -TEST_F(PKITest, testRevocateCertificate) -{ - CertificateList crl; - - uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z"; - uint32_t numberOfRevoked = 0; - uint32_t revokedNumbers[2]; - const uint8_t *revocationDates[2]; - - ByteArray code = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - pubKeyIss.data = caPubKey; - pubKeyIss.len = sizeof(caPubKey); - privKeyIss.data = caPrivKey; - privKeyIss.len = sizeof(caPrivKey); - - numberOfRevoked = 2; - - revokedNumbers[0] = 100; // serial number of first revoked certificate - revokedNumbers[1] = 200; // serial number of second revoked certificate - revocationDates[0] = (const uint8_t *)"130101000001Z"; - revocationDates[1] = (const uint8_t *)"130101000002Z"; - - rootName.data = (uint8_t *)"ROOT2"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss)); - - code.len = CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4); - code.data = (uint8_t *)calloc(1, code.len); - - EXPECT_EQ(PKI_SUCCESS, CKMIssueCRL (uint8ThisUpdateTime, numberOfRevoked, revokedNumbers, - revocationDates, &code)); - EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (code, &crl, pubKeyIss)); - free(code.data); - numberOfRevoked++; - code.len = CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4); - code.data = (uint8_t *)calloc(1, code.len); - EXPECT_EQ(PKI_SUCCESS, CKMRevocateCertificate (uint8ThisUpdateTime, 50, &code)); - EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (code, &crl, pubKeyIss)); -#ifdef X509_DEBUG - PrintSNStore(); - PrintCRL(&crl); -#endif - - FreeSNStore(); - free(code.data); - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//checck correctness of saving root certificate to binary file -TEST_F(PKITest, StoreCKMInfo) -{ - struct stat st; - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - const long serNum = 48598490; - CertificateList crl; - uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z"; - uint32_t numberOfRevoked = 0; - uint32_t revokedNumbers[2]; - const uint8_t *revocationDates[2]; - - ByteArray certDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - ByteArray code = BYTE_ARRAY_INITIALIZER; - - certDer.data = derData; - certDer.len = ISSUER_MAX_CERT_SIZE; - pubKeyIss.data = caPubKey; - pubKeyIss.len = PUBLIC_KEY_SIZE; - privKeyIss.data = caPrivKey; - privKeyIss.len = PRIVATE_KEY_SIZE; - rootName.data = (uint8_t *)"ROOT"; - rootName.len = strlen((char *)rootName.data); - - //generate CA Certificate - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss)); - ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(serNum)); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer)); - - //generate CRL - numberOfRevoked = NUMBER_OF_REVOKED; - - revokedNumbers[0] = 100; // serial number of first revoked certificate - revokedNumbers[1] = 200; // serial number of second revoked certificate - revocationDates[0] = (const uint8_t *)"130101000001Z"; - revocationDates[1] = (const uint8_t *)"130101000002Z"; - - code.data = (uint8_t *)calloc(1, - (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4))); - code.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)); - - ASSERT_EQ(PKI_SUCCESS, CKMIssueCRL (uint8ThisUpdateTime, numberOfRevoked, revokedNumbers, - revocationDates, &code)); - - // Check Certificate file - CertificateX509 certificate; - ByteArray crtDer = BYTE_ARRAY_INITIALIZER; - uint8_t crtDerData[ISSUER_MAX_CERT_SIZE] = {0}; - - crtDer.data = crtDerData; - crtDer.len = sizeof(crtDerData); - - //open file - int fd = open(CA_STORAGE_CRT_FILE, O_RDONLY); - ASSERT_TRUE(fd != -1); - //get status - ASSERT_TRUE(fstat(fd, &st) == 0); - //read the content - int res = read(fd, crtDer.data, crtDer.len); - ASSERT_NE(-1, res); - EXPECT_EQ(st.st_size > ISSUER_MAX_CERT_SIZE ? ISSUER_MAX_CERT_SIZE : st.st_size, res); - close(fd); - - ByteArray crtCheck; - crtCheck.data = crtDer.data + 3; //now file contains length of certificate - crtCheck.len = crtDer.len - 3; - EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtCheck, &certificate)); -#ifdef X509_DEBUG - PrintCertificate(&certificate); -#endif - - //check CRL - ByteArray crlDer = BYTE_ARRAY_INITIALIZER; - crlDer.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)); - crlDer.data = (uint8_t *)malloc(crlDer.len); - - EXPECT_EQ(PKI_SUCCESS, GetCertificateRevocationList(&crlDer)); - - EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (crlDer, &crl, pubKeyIss)); -#ifdef X509_DEBUG - PrintCRL(&crl); -#endif - EXPECT_EQ(PKI_SUCCESS, CloseCKMInfo()); - free(crlDer.data); - free(code.data); -} - -//check correctness of root certificate generation -TEST_F(PKITest, GenerateRootCertificate) -{ - uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - - ByteArray certDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - certDer.data = derData; - certDer.len = sizeof(derData); - - pubKeyIss.data = caPubKey; - pubKeyIss.len = sizeof(caPubKey); - privKeyIss.data = caPrivKey; - privKeyIss.len = sizeof(caPrivKey); - rootName.data = (uint8_t *)"ROOT"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - - for (int i = 1; i <= RUNS; i++) - { - ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss)); - ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i)); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer)); - - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - certDer.data[0]++; - ASSERT_NE(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - certDer.data[0]--; - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - } - ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo()); -} - -//check correctness of ordinal device certificate generation -TEST_F(PKITest, GenerateDeviceCertificate) -{ - uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0}; - uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0}; - uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0}; - uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0}; - uint8_t *subjName = (uint8_t *)"Subject Name"; - - ByteArray certDer = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER; - ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER; - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - - certDer.data = derData; - certDer.len = ISSUER_MAX_CERT_SIZE; - - pubKeyIss.data = caPubKey; - pubKeyIss.len = sizeof(caPubKey); - privKeyIss.data = caPrivKey; - privKeyIss.len = sizeof(caPrivKey); - pubKeySubj.data = subjPubKey; - pubKeySubj.len = sizeof(subjPubKey); - privKeySubj.data = subjPrivKey; - privKeySubj.len = sizeof(subjPrivKey); - rootName.data = (uint8_t *)"ROOT2"; - rootName.len = strlen((char *)rootName.data); - ASSERT_EQ(PKI_SUCCESS, InitCKMInfo()); - - ASSERT_EQ(GenerateCAKeyPair(&privKeyIss, &pubKeyIss), PKI_SUCCESS); - for (int i = 1; i <= RUNS; i++) - { - ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeySubj, &pubKeySubj)); - ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i)); - ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName)); - ASSERT_EQ(PKI_SUCCESS, CKMIssueDeviceCertificate(subjName, 0, 0, subjPubKey, &certDer)); - - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - certDer.data[0]++; - ASSERT_NE(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - certDer.data[0]--; - ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss)); - } - ASSERT_EQ(CloseCKMInfo(), PKI_SUCCESS); -} - -//check correctness of saving CRL to storage and loading CRL from storage -TEST_F(PKITest, CRLSetGet) -{ - OicSecCrl_t *defaultCrl = NULL; - defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t)); - ASSERT_NE(defaultCrl, (OicSecCrl_t *) NULL); - defaultCrl->CrlId = CRL_DEFAULT_CRL_ID; - defaultCrl->CrlData.data = (uint8_t *)CRL_DEFAULT_CRL_DATA; - defaultCrl->CrlData.len = strlen(CRL_DEFAULT_CRL_DATA); - defaultCrl->ThisUpdate.data = (uint8_t *)CRL_DEFAULT_THIS_UPDATE; - defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE); - EXPECT_EQ(OC_STACK_OK, UpdateCRLResource(defaultCrl)); - - EXPECT_NE((void *)NULL, GetCrl()); - OICFree(defaultCrl); -} - -//CKMGetCRL test -TEST_F(PKITest, CKMGetCRL) -{ - const size_t CRL_MAX_SIZE = 1024; - ByteArray certificateRevocationList; - certificateRevocationList.data = (uint8_t*)OICCalloc(1,CRL_MAX_SIZE); - certificateRevocationList.len = CRL_MAX_SIZE; - EXPECT_EQ(PKI_SUCCESS, CKMGetCRL(&certificateRevocationList)); - OICFree(certificateRevocationList.data); -} - -//CKMSetCAInfo test -TEST_F(PKITest, CKMSetCAInfo) -{ - ByteArray rootName = BYTE_ARRAY_INITIALIZER; - rootName.data = (uint8_t *)"ROOT2"; - rootName.len = strlen((char *)rootName.data); - const long serNum = 100; - EXPECT_EQ(PKI_SUCCESS, CKMSetCAInfo(serNum, rootName)); -} - -int main(int argc, char **argv) -{ - int urandom; - unsigned int seed = 0; - - urandom = open ("/dev/urandom", O_RDONLY); - if(urandom) - { - fprintf(stderr, "Cannot open /dev/urandom\n"); - } - else - { - if(read(urandom, &seed, sizeof(seed)) != sizeof(seed)) - { - fprintf(stderr, "Error read from /dev/urandom\n"); - } - close(urandom); - } - - srand(seed); - - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/01.der b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/01.der deleted file mode 100644 index 9f4e0d9..0000000 Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/01.der and /dev/null differ diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat deleted file mode 100644 index 70e2b51..0000000 Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat and /dev/null differ diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json deleted file mode 100644 index 5ac89c0..0000000 --- a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "acl": { - "aclist": { - "aces": [ - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/res", - "rel": "", - "rt": ["oic.wk.res"], - "if": ["oic.if.ll"] - },{ - "href": "/oic/d", - "rel": "", - "rt": ["oic.wk.d"], - "if": ["oic.if.baseline", "oic.if.r"] - },{ - "href": "/oic/p", - "rel": "", - "rt": ["oic.wk.p"], - "if": ["oic.if.baseline", "oic.if.r"] - } - ], - "permission": 2 - }, - { - "subjectuuid": "*", - "resources": [ - { - "href": "/oic/sec/doxm", - "rel": "", - "rt": ["oic.r.doxm"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/pstat", - "rel": "", - "rt": ["oic.r.pstat"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/acl", - "rel": "", - "rt": ["oic.r.acl"], - "if": ["oic.if.baseline"] - }, - { - "href": "/oic/sec/cred", - "rel": "", - "rt": ["oic.r.cred"], - "if": ["oic.if.baseline"] - } - ], - "permission": 7 - } - ] - }, - "rowneruuid" : "61646d69-6e44-6576-6963-655555494430" - }, - "crl": { - "CRLId": 1, - "ThisUpdate": "150101000000Z", - "CRLData": "-" - }, - "pstat": { - "isop": true, - "deviceuuid": "61646d69-6e44-6576-6963-655555494430", - "rowneruuid": "61646d69-6e44-6576-6963-655555494430", - "cm": 0, - "tm": 0, - "om": 3, - "sm": 3 - }, - "doxm": { - "oxms": [0], - "oxmsel": 0, - "sct": 1, - "owned": true, - "deviceuuid": "61646d69-6e44-6576-6963-655555494430", - "devowneruuid": "61646d69-6e44-6576-6963-655555494430", - "rowneruuid": "61646d69-6e44-6576-6963-655555494430", - "x.org.iotivity.dpc": false - } -} \ No newline at end of file diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/cacert.der b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/cacert.der deleted file mode 100644 index e8d0a67..0000000 Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/cacert.der and /dev/null differ diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/capub.der b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/capub.der deleted file mode 100644 index 55252f0..0000000 Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/capub.der and /dev/null differ diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/cert_chain.dat b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/cert_chain.dat deleted file mode 100755 index e400aa8..0000000 Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/cert_chain.dat and /dev/null differ diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/chain.der b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/chain.der deleted file mode 100644 index 37f3dd8..0000000 Binary files a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/chain.der and /dev/null differ diff --git a/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h b/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h index 97b90f0..fa9813d 100644 --- a/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h +++ b/resource/csdk/security/provisioning/include/internal/secureresourceprovider.h @@ -64,18 +64,7 @@ OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDevi OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo, OCProvisionResultCB resultCallback); -#if defined(__WITH_X509__) || defined(__WITH_TLS__) -/** - * API to send CRL information to resource. - * - * @param[in] selectedDeviceInfo Selected target device. - * @param[in] crl CRL to provision. - * @param[in] resultCallback callback provided by API user, callback will be called when - * provisioning request recieves a response from resource server. - * @return OC_STACK_OK in case of success and other value otherwise. - */ -OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo, - OicSecCrl_t *crl, OCProvisionResultCB resultCallback); +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * function to provision Trust certificate chain to devices. @@ -114,7 +103,7 @@ OCStackResult SRPSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize, */ OCStackResult SRPSaveOwnCertChain(OicSecCert_t * cert, OicSecKey_t * key, uint16_t *credId); -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ /** * API to send Direct-Pairing Configuration to a device. * diff --git a/resource/csdk/security/provisioning/include/ocprovisioningmanager.h b/resource/csdk/security/provisioning/include/ocprovisioningmanager.h index 920dd0c..4dbf992 100755 --- a/resource/csdk/security/provisioning/include/ocprovisioningmanager.h +++ b/resource/csdk/security/provisioning/include/ocprovisioningmanager.h @@ -307,7 +307,7 @@ void OCDeleteACLList(OicSecAcl_t* pAcl); */ void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl); -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * this function sends CRL information to resource. * @@ -347,7 +347,7 @@ OCStackResult OCProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16 OCStackResult OCSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize, OicEncodingType_t encodingType, uint16_t *credId); -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ #ifdef __cplusplus diff --git a/resource/csdk/security/provisioning/sample/SConscript b/resource/csdk/security/provisioning/sample/SConscript index da600ae..45d7060 100644 --- a/resource/csdk/security/provisioning/sample/SConscript +++ b/resource/csdk/security/provisioning/sample/SConscript @@ -74,7 +74,7 @@ if target_os not in ['msys_nt', 'windows']: provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) else: provisioning_env.AppendUnique(LIBPATH = [os.path.join(env.get('BUILD_DIR'), 'resource', 'csdk')]) - provisioning_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32', 'timer']) + provisioning_env.AppendUnique(LIBS = ['ws2_32', 'iphlpapi', 'advapi32']) provisioning_env.PrependUnique(LIBS = ['oc', 'oc_logger', 'octbstack', 'connectivity_abstraction', 'coap']) @@ -83,10 +83,8 @@ if target_os not in ['msys_nt', 'windows']: provisioning_env.PrependUnique(LIBS = ['ocpmapi', 'ocsrm']) if env.get('SECURED') == '1': - provisioning_env.AppendUnique(LIBS = ['tinydtls']) -if env.get('DTLS_WITH_X509') == '1': - provisioning_env.AppendUnique(LIBS = ['CKManager']) - provisioning_env.AppendUnique(LIBS = ['asn1']) + provisioning_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto']) + provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG']) diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudCommon.c b/resource/csdk/security/provisioning/sample/cloud/cloudCommon.c index 4ee8c9e..9ab083e 100644 --- a/resource/csdk/security/provisioning/sample/cloud/cloudCommon.c +++ b/resource/csdk/security/provisioning/sample/cloud/cloudCommon.c @@ -330,7 +330,7 @@ static OCStackResult saveTrustCert(void) OCStackResult res = OC_STACK_ERROR; OIC_LOG(INFO, TAG, "Save Trust Cert. Chain into Cred of SVR"); - ByteArray trustCertChainArray = {0, 0}; + ByteArray_t trustCertChainArray = {0, 0}; const char *filename = "rootca.crt"; if (!readFile(filename, (OCByteString *)&trustCertChainArray)) diff --git a/resource/csdk/security/provisioning/src/credentialgenerator.c b/resource/csdk/security/provisioning/src/credentialgenerator.c index 5062374..5db39c7 100644 --- a/resource/csdk/security/provisioning/src/credentialgenerator.c +++ b/resource/csdk/security/provisioning/src/credentialgenerator.c @@ -29,14 +29,6 @@ #include "srmutility.h" #include "stdbool.h" #include "securevirtualresourcetypes.h" -#ifdef __WITH_X509__ -#include "ck_manager.h" -//Certificate-related functions -#define CERT_LEN_PREFIX (3) -#define BYTE_SIZE (8) //bits - -#define CHAIN_LEN (2) //TODO: replace by external define or a runtime value -#endif //__WITH_X509__ #define TAG "SRPAPI-CG" @@ -92,145 +84,3 @@ exit: return res; } - -#ifdef __WITH_X509__ -static void writeCertPrefix(uint8_t *prefix, uint32_t certLen) -{ - for (size_t i = 0; i < CERT_LEN_PREFIX; ++i) - { - prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF; - } -} - -static uint32_t appendCert2Chain(uint8_t *appendPoint, uint8_t *cert, size_t len) -{ - uint32_t ret = 0; - VERIFY_NON_NULL(TAG, appendPoint, ERROR); - VERIFY_NON_NULL(TAG, cert, ERROR); - - memcpy(appendPoint + CERT_LEN_PREFIX, cert, len); - writeCertPrefix(appendPoint, len); - - ret = len + CERT_LEN_PREFIX; -exit: - return ret; -} - -/** - * Function to generate Base64 encoded credential data for device. - * - * @param[in] subject Device id. - * @param[out] certificateChain Pointer to Array of Base64 encoded certificate strings. - * @param[out] chainLength Pointer to number of the certificates in certificateChain. - * @param[out] privKey Pointer to Base64 encoded private key. - * @return OC_STACK_OK on success - */ -static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, OicSecCert_t * certificateChain, - OicSecKey_t * privKey) -{ - if (NULL == subject || NULL == certificateChain || NULL == privKey) - { - return OC_STACK_INVALID_PARAM; - } - certificateChain->data = NULL; - privKey->data = NULL; - - ByteArray pubKeyBA = BYTE_ARRAY_INITIALIZER; - ByteArray privKeyBA = BYTE_ARRAY_INITIALIZER; - ByteArray cert[CHAIN_LEN]; - - uint8_t pubKeyData[PUBLIC_KEY_SIZE] = {0}; - uint8_t privKeyData[PRIVATE_KEY_SIZE] = {0}; - uint8_t certData[ISSUER_MAX_CERT_SIZE * CHAIN_LEN] = {0}; - uint8_t subjName[UUID_LENGTH + 1] = {0}; - - pubKeyBA.data = pubKeyData; - pubKeyBA.len = PUBLIC_KEY_SIZE; - privKeyBA.data = privKeyData; - privKeyBA.len = PRIVATE_KEY_SIZE; - for (size_t i = 0; i < CHAIN_LEN; ++i) - { - cert[i].data = certData + ISSUER_MAX_CERT_SIZE * i; - cert[i].len = ISSUER_MAX_CERT_SIZE; - } - - memcpy(subjName, subject->id, UUID_LENGTH); - subjName[UUID_LENGTH] = '\0'; - - if (PKI_SUCCESS != GenerateKeyPair(&privKeyBA, &pubKeyBA)) - { - OIC_LOG(ERROR, TAG, "Error generating keys."); - return OC_STACK_ERROR; - } - if (PKI_SUCCESS != CKMIssueDeviceCertificate(subjName, NULL, NULL, pubKeyBA.data, cert)) - { - OIC_LOG(ERROR, TAG, "Error generating certificate."); - return OC_STACK_ERROR; - } - - uint8_t numCert = 0; - if (PKI_SUCCESS != GetCAChain(&numCert , cert + 1)) - { - OIC_LOG(ERROR, TAG, "Error getting CA certificate chain."); - return OC_STACK_ERROR; - } - - numCert ++; - uint32_t len = 0; - for (size_t i = 0; i < numCert; i++) - { - certificateChain->data = (uint8_t *) OICRealloc(certificateChain->data, - len + cert[i].len + CERT_LEN_PREFIX); - if (NULL == certificateChain->data) - { - OIC_LOG(ERROR, TAG, "Error while memory allocation"); - return OC_STACK_ERROR; - } - - uint32_t appendedLen = appendCert2Chain(certificateChain->data + len, - cert[i].data, cert[i].len); - if (0 == appendedLen) - { - OIC_LOG(ERROR, TAG, "Error while certifiacate chain creation."); - OICFree(certificateChain->data); - certificateChain->len = 0; - return OC_STACK_ERROR; - } - len += appendedLen; - } - certificateChain->len = len; - privKey->data = (uint8_t*) OICMalloc(PRIVATE_KEY_SIZE); - if (NULL == privKey->data) - { - OIC_LOG(ERROR, TAG, "Error while memory allocation"); - OICFree(certificateChain->data); - certificateChain->len = 0; - privKey->len = 0; - return OC_STACK_ERROR; - } - memcpy(privKey->data, privKeyData, PRIVATE_KEY_SIZE); - privKey->len = PRIVATE_KEY_SIZE; - - return OC_STACK_OK; -} - -OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId, - const OicUuid_t *deviceId, OicSecCred_t **const cred) -{ - if (NULL == ptDeviceId || NULL == deviceId || NULL == cred || NULL != *cred) - { - return OC_STACK_INVALID_PARAM; - } - OicSecCert_t certificateChain; - OicSecKey_t privKey; - if (OC_STACK_OK != GenerateCertificateAndKeys(deviceId, &certificateChain, &privKey)) - { - OIC_LOG(ERROR, TAG, "Error while generating credential data."); - return OC_STACK_ERROR; - } - - *cred = GenerateCredential(deviceId, SIGNED_ASYMMETRIC_KEY, &certificateChain, - &privKey, ptDeviceId); - return OC_STACK_OK; -} -#endif // __WITH_X509__ diff --git a/resource/csdk/security/provisioning/src/ocprovisioningmanager.c b/resource/csdk/security/provisioning/src/ocprovisioningmanager.c index 8364a20..60dc0a3 100755 --- a/resource/csdk/security/provisioning/src/ocprovisioningmanager.c +++ b/resource/csdk/security/provisioning/src/ocprovisioningmanager.c @@ -358,8 +358,9 @@ static OCStackResult RemoveDeviceInfoFromLocal(const OCProvisionDev_t* pTargetDe // Close the DTLS session of the removed device. CAEndpoint_t *endpoint = (CAEndpoint_t *)&pTargetDev->endpoint; endpoint->port = pTargetDev->securePort; - CAResult_t caResult = CACloseDtlsSession(endpoint); - if (CA_STATUS_OK != caResult) { + CAResult_t caResult = CAcloseSslSession(endpoint); + if(CA_STATUS_OK != caResult) + { OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close DTLS session : %d", caResult); } @@ -1043,25 +1044,7 @@ void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl) { FreePdAclList(pPdAcl); } - - -#if defined(__WITH_X509__) || defined(__WITH_TLS__) -/** - * this function sends CRL information to resource. - * - * @param[in] ctx Application context would be returned in result callback. - * @param[in] selectedDeviceInfo Selected target device. - * @param[in] crl CRL to provision. - * @param[in] resultCallback callback provided by API user, callback will be called when provisioning - request recieves a response from resource server. - * @return OC_STACK_OK in case of success and other value otherwise. - */ -OCStackResult OCProvisionCRL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecCrl_t *crl, - OCProvisionResultCB resultCallback) -{ - return SRPProvisionCRL(ctx, selectedDeviceInfo, crl, resultCallback); -} - +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * function to provision Trust certificate chain to devices. * @@ -1080,7 +1063,6 @@ OCStackResult OCProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16 return SRPProvisionTrustCertChain(ctx, type, credId, selectedDeviceInfo, resultCallback); } - /** * function to save Trust certificate chain into Cred of SVR. * @@ -1096,5 +1078,5 @@ OCStackResult OCSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize, return SRPSaveTrustCertChain(trustCertChain, chainSize, encodingType, credId); } -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ diff --git a/resource/csdk/security/provisioning/src/ownershiptransfermanager.c b/resource/csdk/security/provisioning/src/ownershiptransfermanager.c index dec4627..cfcd458 100644 --- a/resource/csdk/security/provisioning/src/ownershiptransfermanager.c +++ b/resource/csdk/security/provisioning/src/ownershiptransfermanager.c @@ -245,22 +245,10 @@ static void SetResult(OTMContext_t* otmCtx, const OCStackResult res) //Revert psk_info callback and new deivce uuid in case of random PIN OxM if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel) { - if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter) + if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials)) { - if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials)) - { - OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback."); - } + OIC_LOG(WARNING, TAG, "Failed to revert is DTLS credential handler."); } -#ifdef __WITH_TLS__ - else - { - if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials)) - { - OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback."); - } - } -#endif OicUuid_t emptyUuid = { .id={0}}; SetUuidForRandomPinOxm(&emptyUuid); } @@ -420,7 +408,7 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo) } uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0}; - OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_UNKNOW}; + OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128}; //Generating OwnerPSK CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint, @@ -780,16 +768,8 @@ static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNU CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint; endpoint->port = otmCtx->selectedDeviceInfo->securePort; CAResult_t caResult = CA_STATUS_OK; - if(CA_ADAPTER_IP == endpoint->adapter) - { - caResult = CACloseDtlsSession(endpoint); - } -#ifdef __WITH_TLS__ - else - { - caResult = CAcloseTlsConnection(endpoint); - } -#endif + caResult = CAcloseSslConnection(endpoint); + if(CA_STATUS_OK != caResult) { OIC_LOG(ERROR, TAG, "Failed to close DTLS session"); @@ -801,15 +781,8 @@ static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNU * If we select NULL cipher, * client will select appropriate cipher suite according to server's cipher-suite list. */ - if(CA_ADAPTER_IP == endpoint->adapter) - { - caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, endpoint->adapter); - } - else - { - // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */ - caResult = CASelectCipherSuite(0xC037, endpoint->adapter); - } + // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */ + caResult = CASelectCipherSuite(0xC037, endpoint->adapter); if(CA_STATUS_OK != caResult) { @@ -827,16 +800,7 @@ static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNU OicUuid_t emptyUuid = { .id={0}}; SetUuidForRandomPinOxm(&emptyUuid); - if(CA_ADAPTER_IP == endpoint->adapter) - { - caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials); - } -#ifdef __WITH_TLS__ - else - { - caResult = CAregisterTlsCredentialsHandler(GetDtlsPskCredentials); - } -#endif + caResult = CAregisterPskCredentialsHandler(GetDtlsPskCredentials); if(CA_STATUS_OK != caResult) { @@ -1066,10 +1030,10 @@ static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx) newCredential.privateData.data = ""; newCredential.privateData.len = 0; newCredential.privateData.encoding = ownerCredential->privateData.encoding; -#ifdef __WITH_X509__ + newCredential.publicData.data = NULL; newCredential.publicData.len = 0; -#endif + int secureFlag = 0; //Send owner credential to new device : POST /oic/sec/cred [ owner credential ] if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData, @@ -1395,24 +1359,13 @@ static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selecte return res; } - //Register DTLS event handler to catch the dtls event while handshake - if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + //Register TLS event handler to catch the tls event while handshake + if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DTLSHandshakeCB)) { - if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DTLSHandshakeCB)) - { - OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback."); - } - } -#ifdef __WITH_TLS__ - else - { - if(CA_STATUS_OK != CAregisterTlsHandshakeCallback(DTLSHandshakeCB)) - { - OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback."); - } + OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register TLS handshake callback."); } -#endif - +#endif // __WITH_DTLS__ or __WITH_TLS__ OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer"); return res; diff --git a/resource/csdk/security/provisioning/src/oxmjustworks.c b/resource/csdk/security/provisioning/src/oxmjustworks.c index 0417323..90b8dfe 100644 --- a/resource/csdk/security/provisioning/src/oxmjustworks.c +++ b/resource/csdk/security/provisioning/src/oxmjustworks.c @@ -121,7 +121,7 @@ OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx) else { endpoint.port = selDevInfo->tcpPort; - caresult = CAinitiateTlsHandshake(&endpoint); + caresult = CAinitiateSslHandshake(&endpoint); } #endif if (CA_STATUS_OK != caresult) diff --git a/resource/csdk/security/provisioning/src/oxmrandompin.c b/resource/csdk/security/provisioning/src/oxmrandompin.c index 8375fc8..0faa8e7 100644 --- a/resource/csdk/security/provisioning/src/oxmrandompin.c +++ b/resource/csdk/security/provisioning/src/oxmrandompin.c @@ -92,18 +92,12 @@ OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx) * Credential should not be saved into SVR. * For this reason, We will use a temporary get_psk_info callback to random PIN OxM. */ -#ifdef __WITH_TLS__ - if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskForRandomPinOxm)) + + if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm)) { OIC_LOG(ERROR, TAG, "Failed to register TLS credentials handler for random PIN OxM."); res = OC_STACK_ERROR; } -#endif - if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm)) - { - OIC_LOG(ERROR, TAG, "Failed to register DTLS credentials handler for random PIN OxM."); - res = OC_STACK_ERROR; - } //Set the device id to derive temporal PSK SetUuidForRandomPinOxm(&(otmCtx->selectedDeviceInfo->doxm->deviceID)); @@ -149,7 +143,7 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx) else { endpoint.port = selDevInfo->tcpPort; - caresult = CAinitiateTlsHandshake(&endpoint); + caresult = CAinitiateSslHandshake(&endpoint); } #endif if (CA_STATUS_OK != caresult) diff --git a/resource/csdk/security/provisioning/src/secureresourceprovider.c b/resource/csdk/security/provisioning/src/secureresourceprovider.c index 33df082..5400641 100644 --- a/resource/csdk/security/provisioning/src/secureresourceprovider.c +++ b/resource/csdk/security/provisioning/src/secureresourceprovider.c @@ -45,7 +45,7 @@ #include "utlist.h" #include "ocpayload.h" -#ifdef __WITH_X509__ +#ifdef __WITH_DTLS__ #include "crlresource.h" #endif // WITH_X509__ @@ -360,7 +360,7 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred, return OC_STACK_OK; } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * Structure to carry certificate data to callback. */ @@ -376,19 +376,6 @@ struct CertificateData }; /** - * Structure to carry CRL provision API data to callback. - */ -typedef struct CRLData CRLData_t; -struct CRLData -{ - void *ctx; /**< Pointer to user context.**/ - const OCProvisionDev_t *deviceInfo; /**< Pointer to PMDevInfo_t.**/ - OCProvisionResultCB resultCallback; /**< Pointer to result callback.**/ - OCProvisionResult_t *resArr; /**< Result array.**/ - int numOfResults; /**< Number of results in result array.**/ -}; - -/** * Internal function to update result in result array. */ static void registerResultForCertProvisioning(CertData_t *certData, @@ -403,143 +390,6 @@ static void registerResultForCertProvisioning(CertData_t *certData, } /** - * Internal Function to store results in result array during ACL provisioning. - */ -static void registerResultForCRLProvisioning(CRLData_t *crlData, - OCStackResult stackresult) -{ - OIC_LOG_V(INFO, TAG, "Inside registerResultForCRLProvisioning crlData->numOfResults is %d\n", - crlData->numOfResults); - memcpy(crlData->resArr[(crlData->numOfResults)].deviceId.id, - crlData->deviceInfo->doxm->deviceID.id, UUID_LENGTH); - crlData->resArr[(crlData->numOfResults)].res = stackresult; - ++(crlData->numOfResults); -} - - -/** - * Callback handler of SRPProvisionCRL. - * - * @param[in] ctx ctx value passed to callback from calling function. - * @param[in] UNUSED handle to an invocation - * @param[in] clientResponse Response from queries to remote servers. - * @return OC_STACK_DELETE_TRANSACTION to delete the transaction - * and OC_STACK_KEEP_TRANSACTION to keep it. - */ -static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED, - OCClientResponse *clientResponse) -{ - OIC_LOG_V(INFO, TAG, "Inside SRPProvisionCRLCB."); - (void)UNUSED; - VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION); - CRLData_t *crlData = (CRLData_t*)ctx; - OCProvisionResultCB resultCallback = crlData->resultCallback; - - if (clientResponse) - { - if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) - { - registerResultForCRLProvisioning(crlData, OC_STACK_RESOURCE_CHANGED); - ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults, - crlData->resArr, - false); - OICFree(crlData->resArr); - OICFree(crlData); - return OC_STACK_DELETE_TRANSACTION; - } - } - registerResultForCRLProvisioning(crlData, OC_STACK_ERROR); - ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults, - crlData->resArr, - true); - OIC_LOG_V(ERROR, TAG, "SRPProvisionCRLCB received Null clientResponse"); - OICFree(crlData->resArr); - OICFree(crlData); - return OC_STACK_DELETE_TRANSACTION; -} - -OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo, - OicSecCrl_t *crl, OCProvisionResultCB resultCallback) -{ - VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR, OC_STACK_INVALID_PARAM); - VERIFY_NON_NULL(TAG, crl, ERROR, OC_STACK_INVALID_PARAM); - VERIFY_NON_NULL(TAG, resultCallback, ERROR, OC_STACK_INVALID_CALLBACK); - - OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload)); - if (!secPayload) - { - OIC_LOG(ERROR, TAG, "Failed to memory allocation"); - return OC_STACK_NO_MEMORY; - } - - secPayload->base.type = PAYLOAD_TYPE_SECURITY; - OCStackResult res; - res = CrlToCBORPayload(crl, &secPayload->securityData, &secPayload->payloadSize, NULL); - if((OC_STACK_OK != res) && (NULL == secPayload->securityData)) - { - OICFree(secPayload); - OIC_LOG(ERROR, TAG, "Failed to BinToCrlJSON"); - return OC_STACK_NO_MEMORY; - } - OIC_LOG(DEBUG, TAG, "Created payload for CRL:"); - OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize); - - char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; - if(!PMGenerateQuery(true, - selectedDeviceInfo->endpoint.addr, - selectedDeviceInfo->securePort, - selectedDeviceInfo->connType, - query, sizeof(query), OIC_RSRC_CRL_URI)) - { - OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query"); - OCPayloadDestroy((OCPayload *)secPayload); - return OC_STACK_ERROR; - } - OIC_LOG_V(DEBUG, TAG, "Query=%s", query); - - OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL}; - cbData.cb = &SRPProvisionCRLCB; - CRLData_t *crlData = (CRLData_t *) OICCalloc(1, sizeof(CRLData_t)); - if (crlData == NULL) - { - OCPayloadDestroy((OCPayload *)secPayload); - OIC_LOG(ERROR, TAG, "Unable to allocate memory"); - return OC_STACK_NO_MEMORY; - } - - crlData->deviceInfo = selectedDeviceInfo; - crlData->resultCallback = resultCallback; - crlData->numOfResults=0; - crlData->ctx = ctx; - - crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t)); - if (crlData->resArr == NULL) - { - OCPayloadDestroy((OCPayload *)secPayload); - OIC_LOG(ERROR, TAG, "Unable to allocate memory"); - return OC_STACK_NO_MEMORY; - } - - cbData.context = (void *)crlData; - cbData.cd = NULL; - OCMethod method = OC_REST_POST; - OCDoHandle handle = NULL; - OIC_LOG(DEBUG, TAG, "Sending CRL info to resource server"); - - OCStackResult ret = OCDoResource(&handle, method, query, - &selectedDeviceInfo->endpoint, (OCPayload*)secPayload, - selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0); - - if (ret != OC_STACK_OK) - { - OICFree(crlData->resArr); - OICFree(crlData); - } - - return ret; -} - -/** * Internal function for handling credential generation and sending cretificate credential. * * @param[in] cred Instance of cred resource. @@ -834,7 +684,7 @@ OCStackResult SRPSaveOwnCertChain(OicSecCert_t * cert, OicSecKey_t * key, uint16 return res; } -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize, const OCProvisionDev_t *pDev1, @@ -946,50 +796,6 @@ OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t k VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR); return res; } -#ifdef __WITH_X509__ - case SIGNED_ASYMMETRIC_KEY: - { - const OCProvisionDev_t *firstDevice = pDev1; - OicSecCred_t *cred = NULL; - OCStackResult res = PMGenerateCertificateCredentials(&provTooldeviceID, - &firstDevice->doxm->deviceID,&cred); - VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR); - OIC_LOG(INFO, TAG, "Certificate credentials generated successfully"); - CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t)); - if (NULL == certData) - { - OICFree(cred); - OIC_LOG(ERROR, TAG, "Memory allocation problem"); - return OC_STACK_NO_MEMORY; - } - - certData->deviceInfo = firstDevice; - certData->ctx = ctx; - certData->credInfo = cred; - certData->numOfResults = 0; - certData->resultCallback = resultCallback; - - certData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t)); - if (NULL == certData->resArr) - { - DeleteCredList(cred); - OICFree(certData); - OIC_LOG(ERROR, TAG, "Memory allocation problem"); - return OC_STACK_NO_MEMORY; - } - - res = provisionCertCred(cred, firstDevice, certData, &provisionCertCB); - if (OC_STACK_OK != res) - { - OICFree(certData->resArr); - OICFree(certData); - } - DeleteCredList(cred); - OIC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res); - - return res; - } -#endif default: { OIC_LOG(ERROR, TAG, "Invalid option."); @@ -1960,7 +1766,7 @@ static OCStackApplicationResult SRPResetDeviceCB(void *ctx, OCDoHandle handle, //Close the DTLS session of the reset device. CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr; - CAResult_t caResult = CACloseDtlsSession(endpoint); + CAResult_t caResult = CAcloseSslSession(endpoint); if(CA_STATUS_OK != caResult) { OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult); diff --git a/resource/csdk/security/provisioning/unittest/SConscript b/resource/csdk/security/provisioning/unittest/SConscript index bc28e0b..04373b8 100644 --- a/resource/csdk/security/provisioning/unittest/SConscript +++ b/resource/csdk/security/provisioning/unittest/SConscript @@ -70,16 +70,9 @@ sptest_env.PrependUnique(LIBS = [ 'ocpmapi', 'coap']) if sptest_env.get('SECURED') == '1': - sptest_env.AppendUnique(LIBS = ['timer']) + sptest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) sptest_env.AppendUnique(LIBS = ['tinydtls']) -if sptest_env.get('DTLS_WITH_X509') == '1': - sptest_env.AppendUnique(LIBS = ['CKManager']) - sptest_env.AppendUnique(LIBS = ['asn1']) - -if sptest_env.get('WITH_TCP') == True: - sptest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) - if not sptest_env.get('RELEASE'): sptest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) @@ -87,7 +80,10 @@ if target_os in ['msys_nt', 'windows']: sptest_env.AppendUnique(LIBS = ['ws2_32', 'advapi32', 'bcrypt', + 'octbstack_static', 'iphlpapi']) +else: + sptest_env.AppendUnique(LIBS = ['octbstack']) ###################################################################### # Source files and Targets diff --git a/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp b/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp index 52a034b..4f3f086 100644 --- a/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp +++ b/resource/csdk/security/provisioning/unittest/credentialgeneratortest.cpp @@ -110,50 +110,3 @@ TEST(PMGeneratePairWiseCredentialsTest, InvalidCred) OICFree(provisioningDevID); } -#ifdef __WITH_X509__ - -TEST(PMGenerateCertificateCredentialsTest, InvalidProvisioningtoolDevID) -{ - OicUuid_t *DevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t)); - if(DevID) - { - DevID->id[0] = 1; - } - OicSecCred_t *cred = NULL; - EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(NULL, DevID, &cred)); - OICFree(DevID); -} - -TEST(PMGenerateCertificateCredentialsTest, InvalidDevID) -{ - OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t)); - if(provisioningDevID) - { - provisioningDevID->id[0] = 1; - } - OicSecCred_t *cred = NULL; - EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(provisioningDevID, - NULL, &cred)); - OICFree(provisioningDevID); -} - -TEST(PMGenerateCertificateCredentialsTest, InvalidCred) -{ - OicUuid_t *provisioningDevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t)); - if(provisioningDevID) - { - provisioningDevID->id[0] = 1; - } - OicUuid_t *DevID = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t)); - if(DevID) - { - DevID->id[0] = 1; - } - EXPECT_EQ(OC_STACK_INVALID_PARAM, PMGenerateCertificateCredentials(provisioningDevID, DevID, - NULL)); - OICFree(provisioningDevID); - OICFree(DevID); -} - -#endif // __WITH_X509__ - diff --git a/resource/csdk/security/src/credresource.c b/resource/csdk/security/src/credresource.c index 0b9d41a..ea4c816 100644 --- a/resource/csdk/security/src/credresource.c +++ b/resource/csdk/security/src/credresource.c @@ -104,13 +104,13 @@ static void FreeCred(OicSecCred_t *cred) #endif //Clean PublicData/OptionalData/Credusage -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) // TODO: Need to check credUsage. OICFree(cred->publicData.data); OICFree(cred->optionalData.data); OICFree(cred->credUsage); -#endif /* __WITH_X509__ || __WITH_TLS__*/ +#endif /* __WITH_DTLS__ || __WITH_TLS__*/ //Clean PrivateData OICFree(cred->privateData.data); @@ -147,7 +147,7 @@ size_t GetCredKeyDataSize(const OicSecCred_t* cred) { size += credPtr->privateData.len; } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) if (credPtr->publicData.data && 0 < credPtr->publicData.len) { size += credPtr->publicData.len; @@ -224,7 +224,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload { mapSize++; } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data) { mapSize++; @@ -237,7 +237,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload { mapSize++; } -#endif /* __WITH_X509__ || __WITH_TLS__*/ +#endif /* __WITH_DTLS__ || __WITH_TLS__*/ if (!secureFlag && cred->privateData.data) { mapSize++; @@ -281,7 +281,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload cborEncoderResult = cbor_encode_int(&credMap, cred->credType); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value."); -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) //PublicData -- Not Mandatory if (SIGNED_ASYMMETRIC_KEY == cred->credType && cred->publicData.data) { @@ -410,7 +410,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload strlen(cred->credUsage)); VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Credusage Name Value."); } -#endif /* __WITH_X509__ || __WITH_TLS__*/ +#endif /* __WITH_DTLS__ || __WITH_TLS__*/ //PrivateData -- Not Mandatory if(!secureFlag && cred->privateData.data) { @@ -782,7 +782,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size, } } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) //PublicData -- Not Mandatory if (strcmp(name, OIC_JSON_PUBLICDATA_NAME) == 0) { @@ -912,7 +912,7 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size, cborFindResult = cbor_value_dup_text_string(&credMap, &cred->credUsage, &len, NULL); VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period."); } -#endif //__WITH_X509__ || __WITH_TLS__ +#endif //__WITH_DTLS__ || __WITH_TLS__ if (0 == strcmp(OIC_JSON_PERIOD_NAME, name)) { @@ -993,7 +993,7 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr SYMMETRIC_GROUP_KEY | ASYMMETRIC_KEY | SIGNED_ASYMMETRIC_KEY | PIN_PASSWORD), ERROR); cred->credType = credType; -#ifdef __WITH_X509__ +#ifdef __WITH_DTLS__ if (publicData && publicData->data) { cred->publicData.data = (uint8_t *)OICCalloc(1, publicData->len); @@ -1001,7 +1001,7 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr memcpy(cred->publicData.data, publicData->data, publicData->len); cred->publicData.len = publicData->len; } -#endif // __WITH_X509__ +#endif // __WITH_DTLS__ if (privateData && privateData->data) { @@ -1480,7 +1480,7 @@ exit: return false; } -#endif //__WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * ehRequest) { @@ -1542,20 +1542,14 @@ static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * eh OicUuid_t emptyUuid = { .id={0}}; SetUuidForRandomPinOxm(&emptyUuid); -#ifdef __WITH_TLS__ - if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials)) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials)) { OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler."); ret = OC_EH_ERROR; break; } -#endif - if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials)) - { - OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler."); - ret = OC_EH_ERROR; - break; - } +#endif // __WITH_DTLS__ or __WITH_TLS__ } //Select cipher suite to use owner PSK @@ -2025,81 +2019,6 @@ exit: } #endif /* __WITH_DTLS__ */ -#ifdef __WITH_X509__ -#define CERT_LEN_PREFIX (3) -#define BYTE_SIZE (8) //bits -#define PUB_KEY_X_COORD ("x") -#define PUB_KEY_Y_COORD ("y") -#define CERTIFICATE ("x5c") -#define PRIVATE_KEY ("d") - -static uint32_t parseCertPrefix(uint8_t *prefix) -{ - uint32_t res = 0; - if (NULL != prefix) - { - for (int i = 0; i < CERT_LEN_PREFIX; ++i) - { - res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE)); - } - } - return res; -} - -static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo) -{ - OCStackResult ret = OC_STACK_ERROR; - uint8_t *ccPtr = credInfo->certificateChain; - for (uint8_t i = 0; i < credInfo->chainLen - 1; ++i) - { - ccPtr += CERT_LEN_PREFIX + parseCertPrefix(ccPtr); - } - - ByteArray cert = { .data = ccPtr + CERT_LEN_PREFIX, .len = parseCertPrefix(ccPtr) }; - CertificateX509 certStruct; - - VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR); - - INC_BYTE_ARRAY(certStruct.pubKey, 2); - - memcpy(credInfo->rootPublicKeyX, certStruct.pubKey.data, PUBLIC_KEY_SIZE / 2); - memcpy(credInfo->rootPublicKeyY, certStruct.pubKey.data + PUBLIC_KEY_SIZE / 2, PUBLIC_KEY_SIZE / 2); - - ret = OC_STACK_OK; - exit: - return ret; -} - -int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo) -{ - int ret = 1; - VERIFY_NON_NULL(TAG, credInfo, ERROR); - if (NULL == gCred) - { - VERIFY_SUCCESS(TAG, OC_STACK_OK == InitCredResource(), ERROR); - } - - OicSecCred_t *cred = NULL; - LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY); - VERIFY_NON_NULL(TAG, cred, ERROR); - - if (cred->publicData.len > MAX_CERT_MESSAGE_LEN || cred->privateData.len > PRIVATE_KEY_SIZE) - { - goto exit; - } - credInfo->chainLen = 2; - memcpy(credInfo->certificateChain, cred->publicData.data, cred->publicData.len); - memcpy(credInfo->devicePrivateKey, cred->privateData.data, cred->privateData.len); - credInfo->certificateChainLen = cred->publicData.len; - GetCAPublicKeyData(credInfo); - ret = 0; - -exit: - - return ret; -} -#undef CERT_LEN_PREFIX -#endif /* __WITH_X509__ */ OCStackResult SetCredRownerId(const OicUuid_t* newROwner) { @@ -2154,8 +2073,8 @@ OCStackResult GetCredRownerId(OicUuid_t *rowneruuid) return retVal; } -#ifdef __WITH_TLS__ -void GetDerCaCert(ByteArray * crt) +#if defined (__WITH_TLS__) || defined(__WITH_DTLS__) +void GetDerCaCert(ByteArray_t * crt) { if (NULL == crt) { @@ -2210,7 +2129,7 @@ void GetDerCaCert(ByteArray * crt) return; } -void GetDerOwnCert(ByteArray * crt) +void GetDerOwnCert(ByteArray_t * crt) { if (NULL == crt) { @@ -2240,7 +2159,7 @@ void GetDerOwnCert(ByteArray * crt) return; } -void GetDerKey(ByteArray * key) +void GetDerKey(ByteArray_t * key) { if (NULL == key) { diff --git a/resource/csdk/security/src/crlresource.c b/resource/csdk/security/src/crlresource.c index 12d4f0b..e73038f 100644 --- a/resource/csdk/security/src/crlresource.c +++ b/resource/csdk/security/src/crlresource.c @@ -29,7 +29,6 @@ #include "oic_malloc.h" #include "oic_string.h" #include "crlresource.h" -#include "crl.h" #include "ocpayloadcbor.h" #include "base64.h" #include @@ -609,6 +608,7 @@ static OicSecCrl_t *GetCrlDefault() } defaultCrl->CrlId = CRL_DEFAULT_CRL_ID; + defaultCrl->CrlData.encoding = OIC_ENCODING_DER; bool result1 = copyByteArray((const uint8_t *)CRL_DEFAULT_CRL_DATA, strlen(CRL_DEFAULT_CRL_DATA), @@ -768,7 +768,7 @@ uint8_t *GetCrl() return NULL; } -void GetDerCrl(ByteArray* out) +void GetDerCrl(ByteArray_t* out) { if(NULL == out) { @@ -810,14 +810,9 @@ void GetDerCrl(ByteArray* out) out->len = 0; -#ifdef __WITH_X509__ - char *str = "Not enough space in out buffer to store crl!"; - if (out->data && crl->data && crl->len <= out->len) -#else char *str = "Can't allocate memory for out->data"; out->data = OICMalloc(crl->len); if (out->data) -#endif { memcpy(out->data, crl->data, crl->len); out->len = crl->len; diff --git a/resource/csdk/security/src/directpairing.c b/resource/csdk/security/src/directpairing.c index 4bac266..be6ea15 100644 --- a/resource/csdk/security/src/directpairing.c +++ b/resource/csdk/security/src/directpairing.c @@ -1,1057 +1,1057 @@ -/* ***************************************************************** - * - * 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. - * - * *****************************************************************/ -#ifndef _POSIX_C_SOURCE -#define _POSIX_C_SOURCE 200112L -#endif -#include "iotivity_config.h" -#ifdef HAVE_UNISTD_H -#include -#endif -#ifdef HAVE_TIME_H -#include -#endif -#ifdef HAVE_SYS_TIME_H -#include -#endif -#ifdef HAVE_STRING_H -#include -#endif - -#include "ocstack.h" -#include "oic_malloc.h" -#include "oic_string.h" -#include "logger.h" -#include "cJSON.h" -#include "utlist.h" -#include "ocpayload.h" -#include "payload_logging.h" -#include "cainterface.h" - -#include "directpairing.h" -#include "srmresourcestrings.h" //@note: SRM's internal header -#include "doxmresource.h" //@note: SRM's internal header -#include "pconfresource.h" //@note: SRM's internal header -#include "dpairingresource.h" //@note: SRM's internal header -#include "credresource.h" - -#include "pmtypes.h" -#include "pmutility.h" - -#include "srmutility.h" - -#ifdef __WITH_DTLS__ -#include "global.h" -#endif - - -#define TAG ("DP") -static const uint16_t CBOR_SIZE = 1024; - -/** - * Structure to carry direct-pairing API data to callback. - */ -typedef struct DPairData -{ - OCDirectPairingDev_t *peer; /**< Pointer to pairing target info.**/ - char pin[DP_PIN_LENGTH]; /**< PIN **/ - OCDirectPairingResultCB resultCallback; /**< Pointer to result callback.**/ - void *userCtx; /** < user context to pass in callback **/ -} DPairData_t; - -static OCDirectPairingDev_t *g_dp_paired = NULL; -static OCDirectPairingDev_t *g_dp_discover = NULL; -static DPairData_t *g_dp_proceed_ctx = NULL; - - -/** - * Function to search node in linked list that matches given IP and port. - * - * @param[in] pList List of OCProvisionDev_t. - * @param[in] addr address of target device. - * @param[in] port port of remote server. - * - * @return pointer of OCProvisionDev_t if exist, otherwise NULL - */ -OCDirectPairingDev_t* getDev(OCDirectPairingDev_t **ppList, const char* addr, const uint16_t port) -{ - if(NULL == addr) - { - OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__); - return NULL; - } - - OCDirectPairingDev_t *ptr = NULL; - LL_FOREACH(*ppList, ptr) - { - if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port) - { - return ptr; - } - } - - return NULL; -} - - - -/** - * Add device information to list. - * - * @param[in] pList List of OCProvisionDev_t. - * @param[in] addr address of target device. - * @param[in] port port of remote server. - * @param[in] adapter adapter type of endpoint. - * @param[in] doxm pointer to doxm instance. - * @param[in] connType connectivity type of endpoint - * - * @return OC_STACK_OK for success and errorcode otherwise. - */ -OCStackResult addDev(OCDirectPairingDev_t **ppList, OCDevAddr *endpoint, - OCConnectivityType conn, OicSecPconf_t *pconf) -{ - if(NULL == endpoint || NULL == pconf) - { - OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__); - return OC_STACK_INVALID_PARAM; - } - - OCDirectPairingDev_t *ptr = getDev(ppList, endpoint->addr, endpoint->port); - if(!ptr) - { - ptr = (OCDirectPairingDev_t *)OICCalloc(1, sizeof (OCDirectPairingDev_t)); - if (NULL == ptr) - { - OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!"); - return OC_STACK_NO_MEMORY; - } - - memcpy(&ptr->endpoint, endpoint, sizeof(OCDevAddr)); - ptr->connType = conn; - ptr->securePort = DEFAULT_SECURE_PORT; - ptr->edp = pconf->edp; - ptr->prm = pconf->prm; - pconf->prm = NULL; // to prevent free - ptr->prmLen = pconf->prmLen; - memcpy(&ptr->deviceID, &pconf->deviceID, sizeof(OicUuid_t)); - memcpy(&ptr->rowner, &pconf->rownerID, sizeof(OicUuid_t)); - ptr->next = NULL; - - LL_PREPEND(*ppList, ptr); - OIC_LOG(INFO, TAG, "device added !"); - } - - return OC_STACK_OK; -} - - -/** - * Add device information to list. - * - * @param[in] ppList List of OCProvisionDev_t. - * @param[in] pDev target device. - * - * @return OC_STACK_OK for success and errorcode otherwise. - */ -OCStackResult addDev2(OCDirectPairingDev_t **ppList, OCDirectPairingDev_t *pDev) -{ - if(NULL == pDev) - { - OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__); - return OC_STACK_INVALID_PARAM; - } - - OCDirectPairingDev_t *ptr = getDev(ppList, pDev->endpoint.addr, pDev->endpoint.port); - if(!ptr) - { - ptr = (OCDirectPairingDev_t *)OICCalloc(1, sizeof (OCDirectPairingDev_t)); - if (NULL == ptr) - { - OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!"); - return OC_STACK_NO_MEMORY; - } - - memcpy(&ptr->endpoint, &pDev->endpoint, sizeof(OCDevAddr)); - ptr->connType = pDev->connType; - ptr->securePort = pDev->securePort; - ptr->edp = pDev->edp; - ptr->prmLen = pDev->prmLen; - ptr->prm = (OicSecPrm_t*)OICCalloc(ptr->prmLen, sizeof (OicSecPrm_t)); - if (NULL == ptr->prm) - { - OIC_LOG(ERROR, TAG, "Error while allocating memory for prm !!"); - return OC_STACK_NO_MEMORY; - } - memcpy(ptr->prm, pDev->prm, sizeof(OicSecPrm_t)*ptr->prmLen); - memcpy(&ptr->deviceID, &pDev->deviceID, sizeof(OicUuid_t)); - memcpy(&ptr->rowner, &pDev->rowner, sizeof(OicUuid_t)); - ptr->next = NULL; - - LL_PREPEND(*ppList, ptr); - OIC_LOG(INFO, TAG, "device added !"); - } - - return OC_STACK_OK; -} - - - -/** - * This function deletes list of provision target devices - * - * @param[in] pDevicesList List of OCProvisionDev_t. - */ -void delList(OCDirectPairingDev_t *pList) -{ - if(pList) - { - OCDirectPairingDev_t *del = NULL, *tmp = NULL; - LL_FOREACH_SAFE(pList, del, tmp) - { - LL_DELETE(pList, del); - if (del && del->prm) - { - OICFree(del->prm); - } - } - } -} - -bool DPGenerateQuery(bool isSecure, - const char* address, const uint16_t port, - const OCConnectivityType connType, - char* buffer, size_t bufferSize, const char* uri) -{ - if(!address || !buffer || !uri) - { - OIC_LOG(ERROR, TAG, "DPGenerateQuery : Invalid parameters."); - return false; - } - - static char QPREFIX_COAP[] = "coap://"; - static char QPREFIX_COAPS[] = "coaps://"; - static char QPREFIX_COAP_TCP[] = "coap+tcp://"; - static char QPREFIX_COAPS_TCP[] = "coaps+tcp://"; - - int snRet = 0; - char* prefix = (isSecure == true) ? QPREFIX_COAPS : QPREFIX_COAP; - - switch(connType & CT_MASK_ADAPTER) - { -// @todo: Remove this ifdef. On Arduino, CT_ADAPTER_TCP resolves to the same value -// as CT_ADAPTER_IP, resulting in a compiler error. -#ifdef WITH_TCP -#ifndef WITH_ARDUINO - case CT_ADAPTER_TCP: - prefix = (isSecure == true) ? QPREFIX_COAPS_TCP : QPREFIX_COAP_TCP; -#endif -#endif - case CT_ADAPTER_IP: - switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE) - { - case CT_IP_USE_V4: - snRet = snprintf(buffer, bufferSize, "%s%s:%d%s", - prefix, address, port, uri); - break; - case CT_IP_USE_V6: - snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s", - prefix, address, port, uri); - break; - default: - OIC_LOG(ERROR, TAG, "Unknown address format."); - return false; - } - // snprintf return value check - if (snRet < 0) - { - OIC_LOG_V(ERROR, TAG, "DPGenerateQuery : Error (snprintf) %d\n", snRet); - return false; - } - else if ((size_t)snRet >= bufferSize) - { - OIC_LOG_V(ERROR, TAG, "DPGenerateQuery : Truncated (snprintf) %d\n", snRet); - return false; - } - - break; -#ifndef WITH_ARDUINO - // TODO: We need to verify tinyDTLS in below cases - case CT_ADAPTER_GATT_BTLE: - case CT_ADAPTER_RFCOMM_BTEDR: - OIC_LOG(ERROR, TAG, "Not supported connectivity adapter."); - return false; - break; -#endif - default: - OIC_LOG(ERROR, TAG, "Unknown connectivity adapter."); - return false; - } - - return true; -} - -const OCDirectPairingDev_t* DPGetDiscoveredDevices() -{ - return g_dp_discover; -} - -const OCDirectPairingDev_t* DPGetPairedDevices() -{ - return g_dp_paired; -} - -void DPDeleteLists() -{ - delList(g_dp_discover); - delList(g_dp_paired); -} - -/** - * Callback handler of FinalizeDirectPairing. - * - * @param[in] ctx ctx value passed to callback from calling function. - * @param[in] UNUSED handle to an invocation - * @param[in] clientResponse Response from queries to remote servers. - * @return OC_STACK_DELETE_TRANSACTION to delete the transaction - * and OC_STACK_KEEP_TRANSACTION to keep it. - */ -static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHandle UNUSED, - OCClientResponse *clientResponse) -{ - OIC_LOG_V(INFO, TAG, "IN DirectPairingFinalizeHandler()"); - (void)UNUSED; - if(NULL == ctx) - { - OIC_LOG(ERROR, TAG, "Context is Null"); - return OC_STACK_DELETE_TRANSACTION; - } - - OCStackResult res; - DPairData_t *dpairData = (DPairData_t*)ctx; - OCDirectPairingDev_t *peer = dpairData->peer; - OCDirectPairingResultCB resultCallback = dpairData->resultCallback; - - if (clientResponse) - { - if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) - { - // result - OIC_LOG(INFO, TAG, "DirectPairingFinalizeHandler : success PUT" - " request to /oic/sec/dpairing"); - - CAEndpoint_t endpoint; - memset(&endpoint, 0x00, sizeof(CAEndpoint_t)); - OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, peer->endpoint.addr); - endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0'; - endpoint.port = peer->securePort; - - OicUuid_t ptDeviceID = {.id={0}}; - if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID)) - { - OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID"); - resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR); - return OC_STACK_DELETE_TRANSACTION; - } - -#ifdef __WITH_DTLS__ - res = SavePairingPSK((OCDevAddr*)&endpoint, &peer->deviceID, &ptDeviceID, false); - if(OC_STACK_OK != res) - { - OIC_LOG(ERROR, TAG, "Failed to PairingPSK generation"); - resultCallback(dpairData->userCtx, peer, res); - return OC_STACK_DELETE_TRANSACTION; - } - - // close temporary sesion - CAResult_t caResult = CACloseDtlsSession((const CAEndpoint_t*)&endpoint); - if(CA_STATUS_OK != caResult) - { - OIC_LOG(INFO, TAG, "Fail to close temporary dtls session"); - } - - caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, CA_ADAPTER_IP); - if(CA_STATUS_OK != caResult) - { - OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL"); - } -#endif // __WITH_DTLS__ - - OIC_LOG(INFO, TAG, "Direct-Papring was successfully completed."); - - // update paired list - OCDirectPairingDev_t *dev = getDev(&g_dp_discover, peer->endpoint.addr, - peer->endpoint.port); - res = addDev2(&g_dp_paired, dev); - if (OC_STACK_OK != res) - { - OIC_LOG(ERROR, TAG, "Error while adding a device to paired list."); - } - - resultCallback(dpairData->userCtx, peer, OC_STACK_OK); - - return OC_STACK_DELETE_TRANSACTION; - } - else - { - OIC_LOG(INFO, TAG, "Direct-Papring received error response."); - } - } - else - { - OIC_LOG(ERROR, TAG, "DirectPairingFinalizeHandler received Null clientResponse"); - } - - resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR); - OICFree(dpairData); - return OC_STACK_DELETE_TRANSACTION; -} - -/** - * Finalize direct-pairing . - * - * @param[in] peer target device to establish direct-pairing. - * @param[in] resultCallback result event callback. - * - * @return OC_STACK_OK on success otherwise error. - */ -OCStackResult FinalizeDirectPairing(void *ctx, OCDirectPairingDev_t* peer, - OCDirectPairingResultCB resultCallback) -{ - if(NULL == peer) - { - return OC_STACK_INVALID_PARAM; - } - - OicUuid_t deviceID = {.id={0}}; - if (OC_STACK_OK != GetDoxmDeviceID(&deviceID)) - { - OIC_LOG(ERROR, TAG, "Error while retrieving device ID"); - return OC_STACK_ERROR; - } - - OicSecDpairing_t dpair; - memset(&dpair, 0, sizeof(OicSecDpairing_t)); - dpair.spm = (OicSecPrm_t)PRM_NOT_ALLOWED; - memcpy(&dpair.pdeviceID, &deviceID, sizeof(OicUuid_t)); - - OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload)); - if(!secPayload) - { - OIC_LOG(ERROR, TAG, "Failed to memory allocation"); - return OC_STACK_NO_MEMORY; - } - secPayload->base.type = PAYLOAD_TYPE_SECURITY; - - OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData), - &(secPayload->payloadSize)); - - if(OC_STACK_OK != ret) - { - OICFree(secPayload); - OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload"); - return OC_STACK_NO_MEMORY; - } - OIC_LOG(INFO, TAG, "DPARING CBOR data:"); - OIC_LOG_BUFFER(INFO, TAG, secPayload->securityData, secPayload->payloadSize); - - char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; - if(!DPGenerateQuery(true, - peer->endpoint.addr, - peer->securePort, - peer->connType, - query, sizeof(query), OIC_RSRC_DPAIRING_URI)) - { - OIC_LOG(ERROR, TAG, "DPDirectPairing : Failed to generate query"); - return OC_STACK_ERROR; - } - OIC_LOG_V(DEBUG, TAG, "Query=%s", query); - - DPairData_t *dpairData = (DPairData_t *) OICCalloc(1, sizeof(DPairData_t)); - if (dpairData == NULL) - { - OICFree(secPayload->securityData); - OICFree(secPayload); - OIC_LOG(ERROR, TAG, "Unable to allocate memory"); - return OC_STACK_NO_MEMORY; - } - dpairData->peer = peer; - dpairData->resultCallback = resultCallback; - dpairData->userCtx = ctx; - - OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL}; - cbData.cb = DirectPairingFinalizeHandler; - cbData.context = (void*)dpairData; - cbData.cd = NULL; - - OCMethod method = OC_REST_PUT; - OCDoHandle handle = NULL; - OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server"); - ret = OCDoResource(&handle, method, query, - &peer->endpoint, (OCPayload*)secPayload, - peer->connType, OC_LOW_QOS, &cbData, NULL, 0); - if(OC_STACK_OK != ret) - { - OIC_LOG(ERROR, TAG, "error in OCDoResource"); - return OC_STACK_ERROR; - } - - return OC_STACK_OK; - } - -/** - * Function to handle the handshake result in Direct-Pairing. - * This function will be invoked after DTLS handshake - * @param endPoint [IN] The remote endpoint. - * @param errorInfo [IN] Error information from the endpoint. - * @return NONE - */ -void DirectPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info) -{ - OIC_LOG_V(INFO, TAG, "IN DirectPairingDTLSHandshakeCB"); - - - if(g_dp_proceed_ctx && g_dp_proceed_ctx->peer && endpoint && info) - { - OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d", - endpoint->addr, endpoint->port, info->result); - - OCDirectPairingDev_t *peer = g_dp_proceed_ctx->peer; - OCDirectPairingResultCB resultCallback = g_dp_proceed_ctx->resultCallback; - OCStackResult res; - - //Make sure the address matches. - if(strncmp(peer->endpoint.addr, endpoint->addr, sizeof(endpoint->addr)) == 0 && - peer->securePort == endpoint->port) - { - //In case of success, send next coaps request. - if(CA_STATUS_OK == info->result) - { - OIC_LOG(INFO, TAG, "Now, finalize Direct-Pairing procedure."); - - res = FinalizeDirectPairing(g_dp_proceed_ctx->userCtx, peer, resultCallback); - if(OC_STACK_OK != res) - { - OIC_LOG(ERROR, TAG, "Failed to finalize direct-pairing"); - resultCallback(g_dp_proceed_ctx->userCtx, peer, res); - } - } - else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result) - { - OIC_LOG(INFO, TAG, "DirectPairingDTLSHandshakeCB - Authentication failed"); - resultCallback(g_dp_proceed_ctx->userCtx, peer, OC_STACK_AUTHENTICATION_FAILURE); - } - -#ifdef __WITH_DTLS__ - CARegisterDTLSHandshakeCallback(NULL); -#endif // __WITH_DTLS__ - res = RemoveCredential(&peer->deviceID); - if(OC_STACK_RESOURCE_DELETED != res) - { - OIC_LOG_V(ERROR, TAG, "Failed to remove temporal PSK : %d", res); - } - - OICFree(g_dp_proceed_ctx); - g_dp_proceed_ctx = NULL; - } - else - { - OIC_LOG_V(INFO, TAG, "DirectPairingDTLSHandshakeCB - Not matched to peer address"); - } - } - - OIC_LOG_V(INFO, TAG, "OUT DirectPairingDTLSHandshakeCB"); -} - -/** - * Callback handler of DPDirectPairing. - * - * @param[in] ctx ctx value passed to callback from calling function. - * @param[in] UNUSED handle to an invocation - * @param[in] clientResponse Response from queries to remote servers. - * @return OC_STACK_DELETE_TRANSACTION to delete the transaction - * and OC_STACK_KEEP_TRANSACTION to keep it. - */ -static OCStackApplicationResult DirectPairingHandler(void *ctx, OCDoHandle UNUSED, - OCClientResponse *clientResponse) -{ - OIC_LOG_V(INFO, TAG, "IN DirectPairingHandler."); - (void)UNUSED; - if(NULL == ctx) - { - OIC_LOG(ERROR, TAG, "Context is Null"); - return OC_STACK_DELETE_TRANSACTION; - } - - OCStackResult res = OC_STACK_ERROR; - DPairData_t *dpairData = (DPairData_t*)ctx; - OCDirectPairingResultCB resultCallback = (OCDirectPairingResultCB)dpairData->resultCallback; - OicUuid_t subjectId = {.id={0}}; - - if (clientResponse) - { - if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) - { - // result - OIC_LOG(INFO, TAG, "DirectPairingHandler : success POST request to /oic/sec/dpairing"); - -#ifdef __WITH_DTLS__ - // Add temporary psk - res = AddTmpPskWithPIN(&dpairData->peer->deviceID, - SYMMETRIC_PAIR_WISE_KEY, - (char*)dpairData->pin, DP_PIN_LENGTH, - &dpairData->peer->rowner, &subjectId); - VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR); - - - // Start to establish a secure channel with Pin-based PSK cipher suite - CAResult_t caresult; - - caresult = CAEnableAnonECDHCipherSuite(false); - VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); - - caresult = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP); - VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); - - //Register proceeding peer info. & DTLS event handler to catch the dtls event while handshake - g_dp_proceed_ctx = dpairData; - res = CARegisterDTLSHandshakeCallback(DirectPairingDTLSHandshakeCB); - VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); - - // initiate dtls - CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t)); - VERIFY_NON_NULL(TAG, endpoint, FATAL); - memcpy(endpoint,&dpairData->peer->endpoint,sizeof(CAEndpoint_t)); - endpoint->port = dpairData->peer->securePort; - OIC_LOG_V(INFO, TAG, "Initiate DTLS handshake to %s(%d)", endpoint->addr, - endpoint->port); - - caresult = CAInitiateHandshake(endpoint); - OICFree(endpoint); - VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); -#endif // __WITH_DTLS__ - - res = OC_STACK_OK; - } - else - { - // result - OIC_LOG(INFO, TAG, "DirectPairingHandler : fail POST request to /oic/sec/dpairing"); - } - } - else - { - OIC_LOG(ERROR, TAG, "DirectPairingHandler received Null clientResponse"); - } - -#ifdef __WITH_DTLS__ -exit: -#endif // __WITH_DTLS__ - - if (OC_STACK_OK != res) - { - if (0 < strlen((const char*)subjectId.id)) - { - RemoveCredential(&dpairData->peer->deviceID); - OICFree(dpairData); - g_dp_proceed_ctx = NULL; - } - - resultCallback(dpairData->userCtx, dpairData->peer, res); - } - OIC_LOG_V(INFO, TAG, "OUT DirectPairingHandler."); - return OC_STACK_DELETE_TRANSACTION; -} - -/** - * Start direct-pairing . - * - * @param[in] peer target device to establish direct-pairing. - * @param[in] pmSel selected pairing method. - * @param[in] pinNumber secret value for dtls connection. - * - * @return OC_STACK_OK on success otherwise error. - */ -OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, - char *pinNumber, OCDirectPairingResultCB resultCallback) -{ - if(NULL == peer || NULL == pinNumber) - { - return OC_STACK_INVALID_PARAM; - } - - OicUuid_t deviceID = {.id={0}}; - if (OC_STACK_OK != GetDoxmDeviceID(&deviceID)) - { - OIC_LOG(ERROR, TAG, "Error while retrieving device ID"); - return OC_STACK_ERROR; - } - - OicSecDpairing_t dpair; - memset(&dpair, 0, sizeof(OicSecDpairing_t)); - dpair.spm = pmSel; - memcpy(&dpair.pdeviceID, &deviceID, sizeof(OicUuid_t)); - - OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload)); - if(!secPayload) - { - OIC_LOG(ERROR, TAG, "Failed to memory allocation"); - return OC_STACK_NO_MEMORY; - } - secPayload->base.type = PAYLOAD_TYPE_SECURITY; - - OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData), - &(secPayload->payloadSize)); - - if(OC_STACK_OK != ret) - { - OICFree(secPayload); - OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload"); - return OC_STACK_NO_MEMORY; - } - OIC_LOG(INFO, TAG, "DPARING CBOR data:"); - OIC_LOG_BUFFER(INFO, TAG, secPayload->securityData, secPayload->payloadSize); - - char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; - if(!DPGenerateQuery(false, - peer->endpoint.addr, - peer->endpoint.port, - //peer->securePort, - peer->connType, - query, sizeof(query), OIC_RSRC_DPAIRING_URI)) - { - OIC_LOG(ERROR, TAG, "DPDirectPairing : Failed to generate query"); - return OC_STACK_ERROR; - } - OIC_LOG_V(DEBUG, TAG, "Query=%s", query); - - DPairData_t *dpairData = (DPairData_t *) OICCalloc(1, sizeof(DPairData_t)); - if (dpairData == NULL) - { - OICFree(secPayload->securityData); - OICFree(secPayload); - OIC_LOG(ERROR, TAG, "Unable to allocate memory"); - return OC_STACK_NO_MEMORY; - } - dpairData->peer = peer; - memcpy(dpairData->pin, pinNumber, DP_PIN_LENGTH); - dpairData->resultCallback = resultCallback; - dpairData->userCtx = ctx; - - OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL}; - cbData.cb = DirectPairingHandler; - cbData.context = (void*)dpairData; - cbData.cd = NULL; - - OCMethod method = OC_REST_POST; - OCDoHandle handle = NULL; - OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server"); - ret = OCDoResource(&handle, method, query, - &peer->endpoint, (OCPayload*)secPayload, - peer->connType, OC_LOW_QOS, &cbData, NULL, 0); - if(OC_STACK_OK != ret) - { - OIC_LOG(ERROR, TAG, "error in OCDoResource"); - return OC_STACK_ERROR; - } - - return OC_STACK_OK; - - } - -/** - * Callback handler for getting secure port information using /oic/res discovery. - * - * @param[in] ctx user context - * @param[in] handle Handle for response - * @param[in] clientResponse Response information(It will contain payload) - * - * @return OC_STACK_KEEP_TRANSACTION to keep transaction and - * OC_STACK_DELETE_TRANSACTION to delete it. - */ -static OCStackApplicationResult DirectPairingPortDiscoveryHandler(void *ctx, OCDoHandle UNUSED, - OCClientResponse *clientResponse) -{ - OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing Secure Port DISCOVER " - "query recvd successfully"); - - (void)ctx; - (void)UNUSED; - if (clientResponse) - { - if (NULL == clientResponse->payload) - { - OIC_LOG(INFO, TAG, "Skiping Null payload"); - } - else - { - if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type) - { - OIC_LOG(INFO, TAG, "Wrong payload type"); - return OC_STACK_DELETE_TRANSACTION; - } - - uint16_t securePort = 0; - OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources; - OIC_LOG_PAYLOAD(INFO, clientResponse->payload); - - if (resPayload && resPayload->secure) - { - securePort = resPayload->port; - } - else - { - OIC_LOG(INFO, TAG, "Can not find secure port information."); - return OC_STACK_DELETE_TRANSACTION; - } - - OCDirectPairingDev_t *ptr = getDev(&g_dp_discover, - clientResponse->devAddr.addr, clientResponse->devAddr.port); - if(!ptr) - { - OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list"); - return OC_STACK_DELETE_TRANSACTION; - } - ptr->securePort = securePort; - - OIC_LOG(INFO, TAG, "Exiting DirectPairingPortDiscoveryHandler."); - } - - return OC_STACK_DELETE_TRANSACTION; - } - else - { - OIC_LOG(INFO, TAG, "Skiping Null response"); - } - return OC_STACK_DELETE_TRANSACTION; -} - -/** - * Callback handler for DPDeviceDiscovery API. - * - * @param[in] ctx User context - * @param[in] handle Handler for response - * @param[in] clientResponse Response information (It will contain payload) - * @return OC_STACK_KEEP_TRANSACTION to keep transaction and - * OC_STACK_DELETE_TRANSACTION to delete it. - */ -static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHandle UNUSED, - OCClientResponse * clientResponse) -{ - OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing DISCOVER query recvd successfully"); - - (void)ctx; - (void)UNUSED; - if (clientResponse) - { - OIC_LOG_V(INFO, TAG, "StackResult: %d", clientResponse->result); - OIC_LOG_V(INFO, TAG, - "Device =============> Discovered @ %s:%d", - clientResponse->devAddr.addr, - clientResponse->devAddr.port); - - if (NULL == clientResponse->payload) - { - OIC_LOG(INFO, TAG, "Skiping Null payload"); - return OC_STACK_KEEP_TRANSACTION; - } - if (OC_STACK_OK != clientResponse->result) - { - OIC_LOG(INFO, TAG, "Error in response"); - return OC_STACK_KEEP_TRANSACTION; - } - - OIC_LOG_PAYLOAD(INFO, clientResponse->payload); - OicSecPconf_t *pconf = NULL; - - OCStackResult res = CBORPayloadToPconf( - ((OCSecurityPayload*)clientResponse->payload)->securityData, - CBOR_SIZE,&pconf); - if (OC_STACK_OK != res ) - { - OIC_LOG(INFO, TAG, "Ignoring malformed CBOR"); - return OC_STACK_KEEP_TRANSACTION; - } - else - { - if(pconf->edp) - { - OCDevAddr endpoint; - memcpy(&endpoint, &clientResponse->devAddr, sizeof(OCDevAddr)); - - OCStackResult res = addDev(&g_dp_discover, &endpoint, - clientResponse->connType, pconf); - DeletePconfBinData(pconf); - if (OC_STACK_OK != res) - { - OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist."); - return OC_STACK_KEEP_TRANSACTION; - } - - - char rsrc_uri[MAX_URI_LENGTH+1] = {0}; - int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s", - OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DPAIRING); - if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri)) - { - OIC_LOG(ERROR, TAG, "rsrc_uri_string_print failed"); - return OC_STACK_KEEP_TRANSACTION; - } - - //Try to the unicast discovery to getting secure port - char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0}; - if(!DPGenerateQuery(false, - clientResponse->devAddr.addr, clientResponse->devAddr.port, - clientResponse->connType, - query, sizeof(query), rsrc_uri)) - { - OIC_LOG(ERROR, TAG, "DirectPairingDiscoveryHandler : Failed to generate query"); - return OC_STACK_KEEP_TRANSACTION; - } - OIC_LOG_V(DEBUG, TAG, "Query=%s", query); - - OCCallbackData cbData; - cbData.cb = &DirectPairingPortDiscoveryHandler; - cbData.context = NULL; - cbData.cd = NULL; - OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0, - clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0); - if(OC_STACK_OK != ret) - { - OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery"); - return OC_STACK_KEEP_TRANSACTION; - } - else - { - OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query); - } - } - return OC_STACK_KEEP_TRANSACTION; - } - } - else - { - OIC_LOG(INFO, TAG, "Skiping Null response"); - } - - return OC_STACK_DELETE_TRANSACTION; -} -#ifndef WITH_ARDUINO -/** - * Discover direct-pairing devices in the same IP subnet. . - * - * @param[in] waittime Timeout in seconds. - * - * @return OC_STACK_OK on success otherwise error. - */ -OCStackResult DPDeviceDiscovery(unsigned short waittime) -{ - OIC_LOG(DEBUG, TAG, "IN DPDeviceDiscovery"); - - if (g_dp_discover) - { - delList(g_dp_discover); - g_dp_discover = NULL; - } - - OCStackResult ret; - - const char DP_DISCOVERY_QUERY[] = "/oic/sec/pconf"; - - OCCallbackData cbData; - cbData.cb = DirectPairingDiscoveryHandler; - cbData.context = NULL; - cbData.cd = NULL; - - /* Start a DP discovery query*/ - OIC_LOG_V(INFO, TAG, "Initiating Direct-Pairing Discovery : %s\n", DP_DISCOVERY_QUERY); - OCDoHandle handle = NULL; - ret = OCDoResource(&handle, OC_REST_DISCOVER, DP_DISCOVERY_QUERY, 0, 0, CT_DEFAULT, - OC_LOW_QOS, &cbData, NULL, 0); - if (ret != OC_STACK_OK) - { - OIC_LOG(ERROR, TAG, "OCStack resource error"); - return ret; - } - - // wait.. - - int clock_res = -1; -#if defined(_MSC_VER) - time_t startTime = NULL; - clock_res = (time(&startTime) == -1); -#else - struct timespec startTime = {.tv_sec=0, .tv_nsec=0}; -#if defined(__ANDROID__) || _POSIX_TIMERS > 0 - clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime); -#endif -#endif - if (0 != clock_res) - { - OIC_LOG(ERROR, TAG, "clock error"); - if(OC_STACK_OK != OCCancel(handle, OC_LOW_QOS, NULL, 0)) - { - OIC_LOG(ERROR, TAG, "Failed to remove registered callback"); - } - return OC_STACK_ERROR; - } - - while (1) - { -#if defined(_MSC_VER) - time_t currTime = NULL; - clock_res = (time(&currTime) == -1); -#else - struct timespec currTime = {.tv_sec=0, .tv_nsec=0}; -#if defined(__ANDROID__) || _POSIX_TIMERS > 0 - clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime); -#endif -#endif - if (0 != clock_res) - { - OIC_LOG(ERROR, TAG, "clock error"); - ret = OC_STACK_ERROR; - break; - } -#if defined(_MSC_VER) - long elapsed = currTime - startTime; -#else - long elapsed = (currTime.tv_sec - startTime.tv_sec); -#endif - if (elapsed > waittime) - { - break; - } - else - { - struct timespec timeout = {.tv_sec=0, .tv_nsec=100000000L}; - OCProcess(); - nanosleep(&timeout, NULL); - } - } - - // Waiting for each response. - ret = OCCancel(handle, OC_LOW_QOS, NULL, 0); - if (OC_STACK_OK != ret) - { - OIC_LOG(ERROR, TAG, "Failed to remove registered callback"); - } - OIC_LOG(DEBUG, TAG, "OUT DPDeviceDiscovery"); - return ret; -} -#endif +/* ***************************************************************** + * + * 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. + * + * *****************************************************************/ +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200112L +#endif +#include "iotivity_config.h" +#ifdef HAVE_UNISTD_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_STRING_H +#include +#endif + +#include "ocstack.h" +#include "oic_malloc.h" +#include "oic_string.h" +#include "logger.h" +#include "cJSON.h" +#include "utlist.h" +#include "ocpayload.h" +#include "payload_logging.h" +#include "cainterface.h" + +#include "directpairing.h" +#include "srmresourcestrings.h" //@note: SRM's internal header +#include "doxmresource.h" //@note: SRM's internal header +#include "pconfresource.h" //@note: SRM's internal header +#include "dpairingresource.h" //@note: SRM's internal header +#include "credresource.h" + +#include "pmtypes.h" +#include "pmutility.h" + +#include "srmutility.h" + +#ifdef __WITH_DTLS__ +#include "global.h" +#endif + + +#define TAG ("DP") +static const uint16_t CBOR_SIZE = 1024; + +/** + * Structure to carry direct-pairing API data to callback. + */ +typedef struct DPairData +{ + OCDirectPairingDev_t *peer; /**< Pointer to pairing target info.**/ + char pin[DP_PIN_LENGTH]; /**< PIN **/ + OCDirectPairingResultCB resultCallback; /**< Pointer to result callback.**/ + void *userCtx; /** < user context to pass in callback **/ +} DPairData_t; + +static OCDirectPairingDev_t *g_dp_paired = NULL; +static OCDirectPairingDev_t *g_dp_discover = NULL; +static DPairData_t *g_dp_proceed_ctx = NULL; + + +/** + * Function to search node in linked list that matches given IP and port. + * + * @param[in] pList List of OCProvisionDev_t. + * @param[in] addr address of target device. + * @param[in] port port of remote server. + * + * @return pointer of OCProvisionDev_t if exist, otherwise NULL + */ +OCDirectPairingDev_t* getDev(OCDirectPairingDev_t **ppList, const char* addr, const uint16_t port) +{ + if(NULL == addr) + { + OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__); + return NULL; + } + + OCDirectPairingDev_t *ptr = NULL; + LL_FOREACH(*ppList, ptr) + { + if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port) + { + return ptr; + } + } + + return NULL; +} + + + +/** + * Add device information to list. + * + * @param[in] pList List of OCProvisionDev_t. + * @param[in] addr address of target device. + * @param[in] port port of remote server. + * @param[in] adapter adapter type of endpoint. + * @param[in] doxm pointer to doxm instance. + * @param[in] connType connectivity type of endpoint + * + * @return OC_STACK_OK for success and errorcode otherwise. + */ +OCStackResult addDev(OCDirectPairingDev_t **ppList, OCDevAddr *endpoint, + OCConnectivityType conn, OicSecPconf_t *pconf) +{ + if(NULL == endpoint || NULL == pconf) + { + OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__); + return OC_STACK_INVALID_PARAM; + } + + OCDirectPairingDev_t *ptr = getDev(ppList, endpoint->addr, endpoint->port); + if(!ptr) + { + ptr = (OCDirectPairingDev_t *)OICCalloc(1, sizeof (OCDirectPairingDev_t)); + if (NULL == ptr) + { + OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!"); + return OC_STACK_NO_MEMORY; + } + + memcpy(&ptr->endpoint, endpoint, sizeof(OCDevAddr)); + ptr->connType = conn; + ptr->securePort = DEFAULT_SECURE_PORT; + ptr->edp = pconf->edp; + ptr->prm = pconf->prm; + pconf->prm = NULL; // to prevent free + ptr->prmLen = pconf->prmLen; + memcpy(&ptr->deviceID, &pconf->deviceID, sizeof(OicUuid_t)); + memcpy(&ptr->rowner, &pconf->rownerID, sizeof(OicUuid_t)); + ptr->next = NULL; + + LL_PREPEND(*ppList, ptr); + OIC_LOG(INFO, TAG, "device added !"); + } + + return OC_STACK_OK; +} + + +/** + * Add device information to list. + * + * @param[in] ppList List of OCProvisionDev_t. + * @param[in] pDev target device. + * + * @return OC_STACK_OK for success and errorcode otherwise. + */ +OCStackResult addDev2(OCDirectPairingDev_t **ppList, OCDirectPairingDev_t *pDev) +{ + if(NULL == pDev) + { + OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__); + return OC_STACK_INVALID_PARAM; + } + + OCDirectPairingDev_t *ptr = getDev(ppList, pDev->endpoint.addr, pDev->endpoint.port); + if(!ptr) + { + ptr = (OCDirectPairingDev_t *)OICCalloc(1, sizeof (OCDirectPairingDev_t)); + if (NULL == ptr) + { + OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!"); + return OC_STACK_NO_MEMORY; + } + + memcpy(&ptr->endpoint, &pDev->endpoint, sizeof(OCDevAddr)); + ptr->connType = pDev->connType; + ptr->securePort = pDev->securePort; + ptr->edp = pDev->edp; + ptr->prmLen = pDev->prmLen; + ptr->prm = (OicSecPrm_t*)OICCalloc(ptr->prmLen, sizeof (OicSecPrm_t)); + if (NULL == ptr->prm) + { + OIC_LOG(ERROR, TAG, "Error while allocating memory for prm !!"); + return OC_STACK_NO_MEMORY; + } + memcpy(ptr->prm, pDev->prm, sizeof(OicSecPrm_t)*ptr->prmLen); + memcpy(&ptr->deviceID, &pDev->deviceID, sizeof(OicUuid_t)); + memcpy(&ptr->rowner, &pDev->rowner, sizeof(OicUuid_t)); + ptr->next = NULL; + + LL_PREPEND(*ppList, ptr); + OIC_LOG(INFO, TAG, "device added !"); + } + + return OC_STACK_OK; +} + + + +/** + * This function deletes list of provision target devices + * + * @param[in] pDevicesList List of OCProvisionDev_t. + */ +void delList(OCDirectPairingDev_t *pList) +{ + if(pList) + { + OCDirectPairingDev_t *del = NULL, *tmp = NULL; + LL_FOREACH_SAFE(pList, del, tmp) + { + LL_DELETE(pList, del); + if (del && del->prm) + { + OICFree(del->prm); + } + } + } +} + +bool DPGenerateQuery(bool isSecure, + const char* address, const uint16_t port, + const OCConnectivityType connType, + char* buffer, size_t bufferSize, const char* uri) +{ + if(!address || !buffer || !uri) + { + OIC_LOG(ERROR, TAG, "DPGenerateQuery : Invalid parameters."); + return false; + } + + static char QPREFIX_COAP[] = "coap://"; + static char QPREFIX_COAPS[] = "coaps://"; + static char QPREFIX_COAP_TCP[] = "coap+tcp://"; + static char QPREFIX_COAPS_TCP[] = "coaps+tcp://"; + + int snRet = 0; + char* prefix = (isSecure == true) ? QPREFIX_COAPS : QPREFIX_COAP; + + switch(connType & CT_MASK_ADAPTER) + { +// @todo: Remove this ifdef. On Arduino, CT_ADAPTER_TCP resolves to the same value +// as CT_ADAPTER_IP, resulting in a compiler error. +#ifdef WITH_TCP +#ifndef WITH_ARDUINO + case CT_ADAPTER_TCP: + prefix = (isSecure == true) ? QPREFIX_COAPS_TCP : QPREFIX_COAP_TCP; +#endif +#endif + case CT_ADAPTER_IP: + switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE) + { + case CT_IP_USE_V4: + snRet = snprintf(buffer, bufferSize, "%s%s:%d%s", + prefix, address, port, uri); + break; + case CT_IP_USE_V6: + snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s", + prefix, address, port, uri); + break; + default: + OIC_LOG(ERROR, TAG, "Unknown address format."); + return false; + } + // snprintf return value check + if (snRet < 0) + { + OIC_LOG_V(ERROR, TAG, "DPGenerateQuery : Error (snprintf) %d\n", snRet); + return false; + } + else if ((size_t)snRet >= bufferSize) + { + OIC_LOG_V(ERROR, TAG, "DPGenerateQuery : Truncated (snprintf) %d\n", snRet); + return false; + } + + break; +#ifndef WITH_ARDUINO + // TODO: We need to verify tinyDTLS in below cases + case CT_ADAPTER_GATT_BTLE: + case CT_ADAPTER_RFCOMM_BTEDR: + OIC_LOG(ERROR, TAG, "Not supported connectivity adapter."); + return false; + break; +#endif + default: + OIC_LOG(ERROR, TAG, "Unknown connectivity adapter."); + return false; + } + + return true; +} + +const OCDirectPairingDev_t* DPGetDiscoveredDevices() +{ + return g_dp_discover; +} + +const OCDirectPairingDev_t* DPGetPairedDevices() +{ + return g_dp_paired; +} + +void DPDeleteLists() +{ + delList(g_dp_discover); + delList(g_dp_paired); +} + +/** + * Callback handler of FinalizeDirectPairing. + * + * @param[in] ctx ctx value passed to callback from calling function. + * @param[in] UNUSED handle to an invocation + * @param[in] clientResponse Response from queries to remote servers. + * @return OC_STACK_DELETE_TRANSACTION to delete the transaction + * and OC_STACK_KEEP_TRANSACTION to keep it. + */ +static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHandle UNUSED, + OCClientResponse *clientResponse) +{ + OIC_LOG_V(INFO, TAG, "IN DirectPairingFinalizeHandler()"); + (void)UNUSED; + if(NULL == ctx) + { + OIC_LOG(ERROR, TAG, "Context is Null"); + return OC_STACK_DELETE_TRANSACTION; + } + + OCStackResult res; + DPairData_t *dpairData = (DPairData_t*)ctx; + OCDirectPairingDev_t *peer = dpairData->peer; + OCDirectPairingResultCB resultCallback = dpairData->resultCallback; + + if (clientResponse) + { + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) + { + // result + OIC_LOG(INFO, TAG, "DirectPairingFinalizeHandler : success PUT" + " request to /oic/sec/dpairing"); + + CAEndpoint_t endpoint; + memset(&endpoint, 0x00, sizeof(CAEndpoint_t)); + OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, peer->endpoint.addr); + endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0'; + endpoint.port = peer->securePort; + + OicUuid_t ptDeviceID = {.id={0}}; + if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID)) + { + OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID"); + resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR); + return OC_STACK_DELETE_TRANSACTION; + } + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + res = SavePairingPSK((OCDevAddr*)&endpoint, &peer->deviceID, &ptDeviceID, false); + if(OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "Failed to PairingPSK generation"); + resultCallback(dpairData->userCtx, peer, res); + return OC_STACK_DELETE_TRANSACTION; + } + + // close temporary sesion + CAResult_t caResult = CAcloseSslSession((const CAEndpoint_t*)&endpoint); + if(CA_STATUS_OK != caResult) + { + OIC_LOG(INFO, TAG, "Fail to close temporary dtls session"); + } + + caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, CA_ADAPTER_IP); + if(CA_STATUS_OK != caResult) + { + OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL"); + } +#endif // __WITH_DTLS__ or __WITH_TLS__ + + OIC_LOG(INFO, TAG, "Direct-Papring was successfully completed."); + + // update paired list + OCDirectPairingDev_t *dev = getDev(&g_dp_discover, peer->endpoint.addr, + peer->endpoint.port); + res = addDev2(&g_dp_paired, dev); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "Error while adding a device to paired list."); + } + + resultCallback(dpairData->userCtx, peer, OC_STACK_OK); + + return OC_STACK_DELETE_TRANSACTION; + } + else + { + OIC_LOG(INFO, TAG, "Direct-Papring received error response."); + } + } + else + { + OIC_LOG(ERROR, TAG, "DirectPairingFinalizeHandler received Null clientResponse"); + } + + resultCallback(dpairData->userCtx, peer, OC_STACK_ERROR); + OICFree(dpairData); + return OC_STACK_DELETE_TRANSACTION; +} + +/** + * Finalize direct-pairing . + * + * @param[in] peer target device to establish direct-pairing. + * @param[in] resultCallback result event callback. + * + * @return OC_STACK_OK on success otherwise error. + */ +OCStackResult FinalizeDirectPairing(void *ctx, OCDirectPairingDev_t* peer, + OCDirectPairingResultCB resultCallback) +{ + if(NULL == peer) + { + return OC_STACK_INVALID_PARAM; + } + + OicUuid_t deviceID = {.id={0}}; + if (OC_STACK_OK != GetDoxmDeviceID(&deviceID)) + { + OIC_LOG(ERROR, TAG, "Error while retrieving device ID"); + return OC_STACK_ERROR; + } + + OicSecDpairing_t dpair; + memset(&dpair, 0, sizeof(OicSecDpairing_t)); + dpair.spm = (OicSecPrm_t)PRM_NOT_ALLOWED; + memcpy(&dpair.pdeviceID, &deviceID, sizeof(OicUuid_t)); + + OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload)); + if(!secPayload) + { + OIC_LOG(ERROR, TAG, "Failed to memory allocation"); + return OC_STACK_NO_MEMORY; + } + secPayload->base.type = PAYLOAD_TYPE_SECURITY; + + OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData), + &(secPayload->payloadSize)); + + if(OC_STACK_OK != ret) + { + OICFree(secPayload); + OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload"); + return OC_STACK_NO_MEMORY; + } + OIC_LOG(INFO, TAG, "DPARING CBOR data:"); + OIC_LOG_BUFFER(INFO, TAG, secPayload->securityData, secPayload->payloadSize); + + char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; + if(!DPGenerateQuery(true, + peer->endpoint.addr, + peer->securePort, + peer->connType, + query, sizeof(query), OIC_RSRC_DPAIRING_URI)) + { + OIC_LOG(ERROR, TAG, "DPDirectPairing : Failed to generate query"); + return OC_STACK_ERROR; + } + OIC_LOG_V(DEBUG, TAG, "Query=%s", query); + + DPairData_t *dpairData = (DPairData_t *) OICCalloc(1, sizeof(DPairData_t)); + if (dpairData == NULL) + { + OICFree(secPayload->securityData); + OICFree(secPayload); + OIC_LOG(ERROR, TAG, "Unable to allocate memory"); + return OC_STACK_NO_MEMORY; + } + dpairData->peer = peer; + dpairData->resultCallback = resultCallback; + dpairData->userCtx = ctx; + + OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL}; + cbData.cb = DirectPairingFinalizeHandler; + cbData.context = (void*)dpairData; + cbData.cd = NULL; + + OCMethod method = OC_REST_PUT; + OCDoHandle handle = NULL; + OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server"); + ret = OCDoResource(&handle, method, query, + &peer->endpoint, (OCPayload*)secPayload, + peer->connType, OC_LOW_QOS, &cbData, NULL, 0); + if(OC_STACK_OK != ret) + { + OIC_LOG(ERROR, TAG, "error in OCDoResource"); + return OC_STACK_ERROR; + } + + return OC_STACK_OK; + } + +/** + * Function to handle the handshake result in Direct-Pairing. + * This function will be invoked after DTLS handshake + * @param endPoint [IN] The remote endpoint. + * @param errorInfo [IN] Error information from the endpoint. + * @return NONE + */ +void DirectPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info) +{ + OIC_LOG_V(INFO, TAG, "IN DirectPairingDTLSHandshakeCB"); + + + if(g_dp_proceed_ctx && g_dp_proceed_ctx->peer && endpoint && info) + { + OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d", + endpoint->addr, endpoint->port, info->result); + + OCDirectPairingDev_t *peer = g_dp_proceed_ctx->peer; + OCDirectPairingResultCB resultCallback = g_dp_proceed_ctx->resultCallback; + OCStackResult res; + + //Make sure the address matches. + if(strncmp(peer->endpoint.addr, endpoint->addr, sizeof(endpoint->addr)) == 0 && + peer->securePort == endpoint->port) + { + //In case of success, send next coaps request. + if(CA_STATUS_OK == info->result) + { + OIC_LOG(INFO, TAG, "Now, finalize Direct-Pairing procedure."); + + res = FinalizeDirectPairing(g_dp_proceed_ctx->userCtx, peer, resultCallback); + if(OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "Failed to finalize direct-pairing"); + resultCallback(g_dp_proceed_ctx->userCtx, peer, res); + } + } + else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result) + { + OIC_LOG(INFO, TAG, "DirectPairingDTLSHandshakeCB - Authentication failed"); + resultCallback(g_dp_proceed_ctx->userCtx, peer, OC_STACK_AUTHENTICATION_FAILURE); + } + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + CAregisterSslHandshakeCallback(NULL); +#endif // __WITH_DTLS__ or __WITH_TLS__ + res = RemoveCredential(&peer->deviceID); + if(OC_STACK_RESOURCE_DELETED != res) + { + OIC_LOG_V(ERROR, TAG, "Failed to remove temporal PSK : %d", res); + } + + OICFree(g_dp_proceed_ctx); + g_dp_proceed_ctx = NULL; + } + else + { + OIC_LOG_V(INFO, TAG, "DirectPairingDTLSHandshakeCB - Not matched to peer address"); + } + } + + OIC_LOG_V(INFO, TAG, "OUT DirectPairingDTLSHandshakeCB"); +} + +/** + * Callback handler of DPDirectPairing. + * + * @param[in] ctx ctx value passed to callback from calling function. + * @param[in] UNUSED handle to an invocation + * @param[in] clientResponse Response from queries to remote servers. + * @return OC_STACK_DELETE_TRANSACTION to delete the transaction + * and OC_STACK_KEEP_TRANSACTION to keep it. + */ +static OCStackApplicationResult DirectPairingHandler(void *ctx, OCDoHandle UNUSED, + OCClientResponse *clientResponse) +{ + OIC_LOG_V(INFO, TAG, "IN DirectPairingHandler."); + (void)UNUSED; + if(NULL == ctx) + { + OIC_LOG(ERROR, TAG, "Context is Null"); + return OC_STACK_DELETE_TRANSACTION; + } + + OCStackResult res = OC_STACK_ERROR; + DPairData_t *dpairData = (DPairData_t*)ctx; + OCDirectPairingResultCB resultCallback = (OCDirectPairingResultCB)dpairData->resultCallback; + OicUuid_t subjectId = {.id={0}}; + + if (clientResponse) + { + if(OC_STACK_RESOURCE_CHANGED == clientResponse->result) + { + // result + OIC_LOG(INFO, TAG, "DirectPairingHandler : success POST request to /oic/sec/dpairing"); + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + // Add temporary psk + res = AddTmpPskWithPIN(&dpairData->peer->deviceID, + SYMMETRIC_PAIR_WISE_KEY, + (char*)dpairData->pin, DP_PIN_LENGTH, + &dpairData->peer->rowner, &subjectId); + VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR); + + + // Start to establish a secure channel with Pin-based PSK cipher suite + CAResult_t caresult; + + caresult = CAEnableAnonECDHCipherSuite(false); + VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); + + caresult = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP); + VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); + + //Register proceeding peer info. & DTLS event handler to catch the dtls event while handshake + g_dp_proceed_ctx = dpairData; + res = CAregisterSslHandshakeCallback(DirectPairingDTLSHandshakeCB); + VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); + + // initiate dtls + CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t)); + VERIFY_NON_NULL(TAG, endpoint, FATAL); + memcpy(endpoint,&dpairData->peer->endpoint,sizeof(CAEndpoint_t)); + endpoint->port = dpairData->peer->securePort; + OIC_LOG_V(INFO, TAG, "Initiate DTLS handshake to %s(%d)", endpoint->addr, + endpoint->port); + + caresult = CAInitiateHandshake(endpoint); + OICFree(endpoint); + VERIFY_SUCCESS(TAG, CA_STATUS_OK == caresult, ERROR); +#endif // __WITH_DTLS__ or __WITH_TLS__ + + res = OC_STACK_OK; + } + else + { + // result + OIC_LOG(INFO, TAG, "DirectPairingHandler : fail POST request to /oic/sec/dpairing"); + } + } + else + { + OIC_LOG(ERROR, TAG, "DirectPairingHandler received Null clientResponse"); + } + +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) +exit: +#endif // __WITH_DTLS__ or __WITH_TLS__ + + if (OC_STACK_OK != res) + { + if (0 < strlen((const char*)subjectId.id)) + { + RemoveCredential(&dpairData->peer->deviceID); + OICFree(dpairData); + g_dp_proceed_ctx = NULL; + } + + resultCallback(dpairData->userCtx, dpairData->peer, res); + } + OIC_LOG_V(INFO, TAG, "OUT DirectPairingHandler."); + return OC_STACK_DELETE_TRANSACTION; +} + +/** + * Start direct-pairing . + * + * @param[in] peer target device to establish direct-pairing. + * @param[in] pmSel selected pairing method. + * @param[in] pinNumber secret value for dtls connection. + * + * @return OC_STACK_OK on success otherwise error. + */ +OCStackResult DPDirectPairing(void *ctx, OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, + char *pinNumber, OCDirectPairingResultCB resultCallback) +{ + if(NULL == peer || NULL == pinNumber) + { + return OC_STACK_INVALID_PARAM; + } + + OicUuid_t deviceID = {.id={0}}; + if (OC_STACK_OK != GetDoxmDeviceID(&deviceID)) + { + OIC_LOG(ERROR, TAG, "Error while retrieving device ID"); + return OC_STACK_ERROR; + } + + OicSecDpairing_t dpair; + memset(&dpair, 0, sizeof(OicSecDpairing_t)); + dpair.spm = pmSel; + memcpy(&dpair.pdeviceID, &deviceID, sizeof(OicUuid_t)); + + OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload)); + if(!secPayload) + { + OIC_LOG(ERROR, TAG, "Failed to memory allocation"); + return OC_STACK_NO_MEMORY; + } + secPayload->base.type = PAYLOAD_TYPE_SECURITY; + + OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData), + &(secPayload->payloadSize)); + + if(OC_STACK_OK != ret) + { + OICFree(secPayload); + OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload"); + return OC_STACK_NO_MEMORY; + } + OIC_LOG(INFO, TAG, "DPARING CBOR data:"); + OIC_LOG_BUFFER(INFO, TAG, secPayload->securityData, secPayload->payloadSize); + + char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0}; + if(!DPGenerateQuery(false, + peer->endpoint.addr, + peer->endpoint.port, + //peer->securePort, + peer->connType, + query, sizeof(query), OIC_RSRC_DPAIRING_URI)) + { + OIC_LOG(ERROR, TAG, "DPDirectPairing : Failed to generate query"); + return OC_STACK_ERROR; + } + OIC_LOG_V(DEBUG, TAG, "Query=%s", query); + + DPairData_t *dpairData = (DPairData_t *) OICCalloc(1, sizeof(DPairData_t)); + if (dpairData == NULL) + { + OICFree(secPayload->securityData); + OICFree(secPayload); + OIC_LOG(ERROR, TAG, "Unable to allocate memory"); + return OC_STACK_NO_MEMORY; + } + dpairData->peer = peer; + memcpy(dpairData->pin, pinNumber, DP_PIN_LENGTH); + dpairData->resultCallback = resultCallback; + dpairData->userCtx = ctx; + + OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL}; + cbData.cb = DirectPairingHandler; + cbData.context = (void*)dpairData; + cbData.cd = NULL; + + OCMethod method = OC_REST_POST; + OCDoHandle handle = NULL; + OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server"); + ret = OCDoResource(&handle, method, query, + &peer->endpoint, (OCPayload*)secPayload, + peer->connType, OC_LOW_QOS, &cbData, NULL, 0); + if(OC_STACK_OK != ret) + { + OIC_LOG(ERROR, TAG, "error in OCDoResource"); + return OC_STACK_ERROR; + } + + return OC_STACK_OK; + + } + +/** + * Callback handler for getting secure port information using /oic/res discovery. + * + * @param[in] ctx user context + * @param[in] handle Handle for response + * @param[in] clientResponse Response information(It will contain payload) + * + * @return OC_STACK_KEEP_TRANSACTION to keep transaction and + * OC_STACK_DELETE_TRANSACTION to delete it. + */ +static OCStackApplicationResult DirectPairingPortDiscoveryHandler(void *ctx, OCDoHandle UNUSED, + OCClientResponse *clientResponse) +{ + OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing Secure Port DISCOVER " + "query recvd successfully"); + + (void)ctx; + (void)UNUSED; + if (clientResponse) + { + if (NULL == clientResponse->payload) + { + OIC_LOG(INFO, TAG, "Skiping Null payload"); + } + else + { + if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type) + { + OIC_LOG(INFO, TAG, "Wrong payload type"); + return OC_STACK_DELETE_TRANSACTION; + } + + uint16_t securePort = 0; + OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources; + OIC_LOG_PAYLOAD(INFO, clientResponse->payload); + + if (resPayload && resPayload->secure) + { + securePort = resPayload->port; + } + else + { + OIC_LOG(INFO, TAG, "Can not find secure port information."); + return OC_STACK_DELETE_TRANSACTION; + } + + OCDirectPairingDev_t *ptr = getDev(&g_dp_discover, + clientResponse->devAddr.addr, clientResponse->devAddr.port); + if(!ptr) + { + OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list"); + return OC_STACK_DELETE_TRANSACTION; + } + ptr->securePort = securePort; + + OIC_LOG(INFO, TAG, "Exiting DirectPairingPortDiscoveryHandler."); + } + + return OC_STACK_DELETE_TRANSACTION; + } + else + { + OIC_LOG(INFO, TAG, "Skiping Null response"); + } + return OC_STACK_DELETE_TRANSACTION; +} + +/** + * Callback handler for DPDeviceDiscovery API. + * + * @param[in] ctx User context + * @param[in] handle Handler for response + * @param[in] clientResponse Response information (It will contain payload) + * @return OC_STACK_KEEP_TRANSACTION to keep transaction and + * OC_STACK_DELETE_TRANSACTION to delete it. + */ +static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHandle UNUSED, + OCClientResponse * clientResponse) +{ + OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing DISCOVER query recvd successfully"); + + (void)ctx; + (void)UNUSED; + if (clientResponse) + { + OIC_LOG_V(INFO, TAG, "StackResult: %d", clientResponse->result); + OIC_LOG_V(INFO, TAG, + "Device =============> Discovered @ %s:%d", + clientResponse->devAddr.addr, + clientResponse->devAddr.port); + + if (NULL == clientResponse->payload) + { + OIC_LOG(INFO, TAG, "Skiping Null payload"); + return OC_STACK_KEEP_TRANSACTION; + } + if (OC_STACK_OK != clientResponse->result) + { + OIC_LOG(INFO, TAG, "Error in response"); + return OC_STACK_KEEP_TRANSACTION; + } + + OIC_LOG_PAYLOAD(INFO, clientResponse->payload); + OicSecPconf_t *pconf = NULL; + + OCStackResult res = CBORPayloadToPconf( + ((OCSecurityPayload*)clientResponse->payload)->securityData, + CBOR_SIZE,&pconf); + if (OC_STACK_OK != res ) + { + OIC_LOG(INFO, TAG, "Ignoring malformed CBOR"); + return OC_STACK_KEEP_TRANSACTION; + } + else + { + if(pconf->edp) + { + OCDevAddr endpoint; + memcpy(&endpoint, &clientResponse->devAddr, sizeof(OCDevAddr)); + + OCStackResult res = addDev(&g_dp_discover, &endpoint, + clientResponse->connType, pconf); + DeletePconfBinData(pconf); + if (OC_STACK_OK != res) + { + OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist."); + return OC_STACK_KEEP_TRANSACTION; + } + + + char rsrc_uri[MAX_URI_LENGTH+1] = {0}; + int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s", + OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DPAIRING); + if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri)) + { + OIC_LOG(ERROR, TAG, "rsrc_uri_string_print failed"); + return OC_STACK_KEEP_TRANSACTION; + } + + //Try to the unicast discovery to getting secure port + char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0}; + if(!DPGenerateQuery(false, + clientResponse->devAddr.addr, clientResponse->devAddr.port, + clientResponse->connType, + query, sizeof(query), rsrc_uri)) + { + OIC_LOG(ERROR, TAG, "DirectPairingDiscoveryHandler : Failed to generate query"); + return OC_STACK_KEEP_TRANSACTION; + } + OIC_LOG_V(DEBUG, TAG, "Query=%s", query); + + OCCallbackData cbData; + cbData.cb = &DirectPairingPortDiscoveryHandler; + cbData.context = NULL; + cbData.cd = NULL; + OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0, + clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0); + if(OC_STACK_OK != ret) + { + OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery"); + return OC_STACK_KEEP_TRANSACTION; + } + else + { + OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query); + } + } + return OC_STACK_KEEP_TRANSACTION; + } + } + else + { + OIC_LOG(INFO, TAG, "Skiping Null response"); + } + + return OC_STACK_DELETE_TRANSACTION; +} +#ifndef WITH_ARDUINO +/** + * Discover direct-pairing devices in the same IP subnet. . + * + * @param[in] waittime Timeout in seconds. + * + * @return OC_STACK_OK on success otherwise error. + */ +OCStackResult DPDeviceDiscovery(unsigned short waittime) +{ + OIC_LOG(DEBUG, TAG, "IN DPDeviceDiscovery"); + + if (g_dp_discover) + { + delList(g_dp_discover); + g_dp_discover = NULL; + } + + OCStackResult ret; + + const char DP_DISCOVERY_QUERY[] = "/oic/sec/pconf"; + + OCCallbackData cbData; + cbData.cb = DirectPairingDiscoveryHandler; + cbData.context = NULL; + cbData.cd = NULL; + + /* Start a DP discovery query*/ + OIC_LOG_V(INFO, TAG, "Initiating Direct-Pairing Discovery : %s\n", DP_DISCOVERY_QUERY); + OCDoHandle handle = NULL; + ret = OCDoResource(&handle, OC_REST_DISCOVER, DP_DISCOVERY_QUERY, 0, 0, CT_DEFAULT, + OC_LOW_QOS, &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OIC_LOG(ERROR, TAG, "OCStack resource error"); + return ret; + } + + // wait.. + + int clock_res = -1; +#if defined(_MSC_VER) + time_t startTime = NULL; + clock_res = (time(&startTime) == -1); +#else + struct timespec startTime = {.tv_sec=0, .tv_nsec=0}; +#if defined(__ANDROID__) || _POSIX_TIMERS > 0 + clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime); +#endif +#endif + if (0 != clock_res) + { + OIC_LOG(ERROR, TAG, "clock error"); + if(OC_STACK_OK != OCCancel(handle, OC_LOW_QOS, NULL, 0)) + { + OIC_LOG(ERROR, TAG, "Failed to remove registered callback"); + } + return OC_STACK_ERROR; + } + + while (1) + { +#if defined(_MSC_VER) + time_t currTime = NULL; + clock_res = (time(&currTime) == -1); +#else + struct timespec currTime = {.tv_sec=0, .tv_nsec=0}; +#if defined(__ANDROID__) || _POSIX_TIMERS > 0 + clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime); +#endif +#endif + if (0 != clock_res) + { + OIC_LOG(ERROR, TAG, "clock error"); + ret = OC_STACK_ERROR; + break; + } +#if defined(_MSC_VER) + long elapsed = currTime - startTime; +#else + long elapsed = (currTime.tv_sec - startTime.tv_sec); +#endif + if (elapsed > waittime) + { + break; + } + else + { + struct timespec timeout = {.tv_sec=0, .tv_nsec=100000000L}; + OCProcess(); + nanosleep(&timeout, NULL); + } + } + + // Waiting for each response. + ret = OCCancel(handle, OC_LOW_QOS, NULL, 0); + if (OC_STACK_OK != ret) + { + OIC_LOG(ERROR, TAG, "Failed to remove registered callback"); + } + OIC_LOG(DEBUG, TAG, "OUT DPDeviceDiscovery"); + return ret; +} +#endif diff --git a/resource/csdk/security/src/doxmresource.c b/resource/csdk/security/src/doxmresource.c index 2227500..4955acd 100644 --- a/resource/csdk/security/src/doxmresource.c +++ b/resource/csdk/security/src/doxmresource.c @@ -752,14 +752,14 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0) { OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite"); -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR; -#endif //__WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ goto exit; } else { -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) //Save the owner's UUID to derive owner credential memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)); @@ -783,12 +783,7 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR); OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED"); -#ifdef __WITH_X509__ -#define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE - CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, - ehRequest->devAddr.adapter); -#endif //__WITH_X509__ -#endif //__WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ } } else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel) @@ -812,7 +807,7 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest ehRet = OC_EH_ERROR; } -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) CAResult_t caRes = CA_STATUS_OK; caRes = CAEnableAnonECDHCipherSuite(false); @@ -837,7 +832,7 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * Credential should not be saved into SVR. * For this reason, use a temporary get_psk_info callback to random PIN OxM. */ - caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm); + caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm); VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR); ehRet = OC_EH_OK; } @@ -860,7 +855,7 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * For this reason, use a temporary get_psk_info callback to random PIN OxM. */ #ifdef __WITH_TLS__ - caRes = CAregisterTlsCredentialsHandler(GetDtlsPskForRandomPinOxm); + caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm); #endif VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR); ehRet = OC_EH_OK; @@ -872,11 +867,11 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest } } -#endif //__WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ } else { -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) //Save the owner's UUID to derive owner credential memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)); @@ -890,7 +885,7 @@ static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage"); ehRet = OC_EH_ERROR; } -#endif +#endif // __WITH_DTLS__ or __WITH_TLS__ } } } diff --git a/resource/csdk/security/src/dpairingresource.c b/resource/csdk/security/src/dpairingresource.c index 534dcea..53b8fd6 100644 --- a/resource/csdk/security/src/dpairingresource.c +++ b/resource/csdk/security/src/dpairingresource.c @@ -104,7 +104,7 @@ void SetDpairingResourceOwner(OicUuid_t *rowner) } } -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * Function to save PairingPSK. * @@ -172,7 +172,7 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint, exit: return res; } -#endif // __WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size) { @@ -384,9 +384,9 @@ void DPairingDTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t * } -#ifdef __WITH_DTLS__ - CARegisterDTLSHandshakeCallback(NULL); -#endif // __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + CAregisterSslHandshakeCallback(NULL); +#endif // __WITH_DTLS__ or __WITH_TLS__ // delete temporary key RemoveCredential(&gDpair->pdeviceID); @@ -444,7 +444,7 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq memcpy(&gDpair->pdeviceID, &newDpair->pdeviceID, sizeof(OicUuid_t)); memcpy(&gDpair->rownerID, &pconf->rownerID, sizeof(OicUuid_t)); -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) // Add temporary psk OCStackResult res; OicUuid_t subjectId = {.id={0}}; @@ -467,13 +467,13 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq goto exit; } - if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DPairingDTLSHandshakeCB)) + if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DPairingDTLSHandshakeCB)) { OIC_LOG(WARNING, TAG, "DirectPairingHandler : Failed to register" " DTLS handshake callback."); goto exit; } -#endif // __WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ // should be lock /oic/sec/dpairing resource if Direct-Pairing starts normally ? OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource created"); @@ -487,9 +487,9 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq } -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) exit: -#endif // __WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ // Send payload to request originator if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0)) @@ -545,7 +545,7 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ const OicSecPconf_t *pconf = GetPconfResourceData(); VERIFY_NON_NULL(TAG, pconf, ERROR); -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) OCServerRequest * request = (OCServerRequest *)ehRequest->requestHandle; VERIFY_SUCCESS(TAG, (request->devAddr.flags | OC_FLAG_SECURE), ERROR); @@ -555,7 +555,7 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ OCStackResult res = SavePairingPSK(&request->devAddr, &newDpair->pdeviceID, (OicUuid_t *)&pconf->rownerID, true); VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR); -#endif //__WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ //Generate new acl OicSecPdAcl_t *pdAcl; diff --git a/resource/csdk/security/src/oxmpincommon.c b/resource/csdk/security/src/oxmpincommon.c index f1354aa..5e6b650 100644 --- a/resource/csdk/security/src/oxmpincommon.c +++ b/resource/csdk/security/src/oxmpincommon.c @@ -126,7 +126,7 @@ OCStackResult InputPin(char* pinBuffer, size_t bufferSize) return OC_STACK_OK; } -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) void SetUuidForRandomPinOxm(const OicUuid_t* uuid) { @@ -203,4 +203,4 @@ int32_t GetDtlsPskForRandomPinOxm( CADtlsPskCredType_t type, return ret; } -#endif //__WITH_DTLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ diff --git a/resource/csdk/security/src/resourcemanager.c b/resource/csdk/security/src/resourcemanager.c index f4b6ecf..c0246a8 100644 --- a/resource/csdk/security/src/resourcemanager.c +++ b/resource/csdk/security/src/resourcemanager.c @@ -40,9 +40,9 @@ #define TAG "SRM-RM" -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) #include "crlresource.h" -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest, OCEntityHandlerResult ehRet, uint8_t *cborPayload, size_t size) @@ -92,12 +92,12 @@ OCStackResult InitSecureResources( ) { ret = InitCredResource(); } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) if(OC_STACK_OK == ret) { ret = InitCRLResource(); } -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ if(OC_STACK_OK == ret) { ret = InitSVCResource(); @@ -134,9 +134,9 @@ OCStackResult DestroySecureResources( ) DeInitCredResource(); DeInitDoxmResource(); DeInitPstatResource(); -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) DeInitCRLResource(); -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ DeInitSVCResource(); DeInitAmaclResource(); //#ifdef DIRECT_PAIRING diff --git a/resource/csdk/security/src/secureresourcemanager.c b/resource/csdk/security/src/secureresourcemanager.c index 694c646..0dcb503 100644 --- a/resource/csdk/security/src/secureresourcemanager.c +++ b/resource/csdk/security/src/secureresourcemanager.c @@ -34,15 +34,11 @@ #include "srmresourcestrings.h" #include "ocresourcehandler.h" -#ifdef __WITH_TLS__ +#if defined( __WITH_TLS__) || defined(__WITH_DTLS__) #include "pkix_interface.h" -#endif //__WITH_TLS__ +#endif //__WITH_TLS__ or __WITH_DTLS__ #define TAG "SRM" -#ifdef __WITH_X509__ -#include "crlresource.h" -#endif // __WITH_X509__ - //Request Callback handler static CARequestCallback gRequestHandler = NULL; //Response Callback handler @@ -351,27 +347,15 @@ OCStackResult SRMInitSecureResources() // behavior (for when SVR DB is missing) is settled. InitSecureResources(); OCStackResult ret = OC_STACK_OK; -#if defined(__WITH_DTLS__) - if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials)) - { - OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler."); - ret = OC_STACK_ERROR; - } -#endif -#ifdef __WITH_TLS__ - if (CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials)) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) + if (CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials)) { OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler."); ret = OC_STACK_ERROR; } CAregisterPkixInfoHandler(GetPkixInfo); CAregisterGetCredentialTypesHandler(InitCipherSuiteList); -#endif -#if defined(__WITH_X509__) - CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials); - CARegisterDTLSCrlHandler(GetDerCrl); -#endif // (__WITH_X509__) - +#endif // __WITH_DTLS__ or __WITH_TLS__ return ret; } diff --git a/resource/csdk/security/tool/json2cbor.c b/resource/csdk/security/tool/json2cbor.c index c73aa9d..46ee4b3 100644 --- a/resource/csdk/security/tool/json2cbor.c +++ b/resource/csdk/security/tool/json2cbor.c @@ -846,7 +846,7 @@ OicSecCred_t * JSONToCredBin(const char * jsonStr) cred->privateData.encoding = OIC_ENCODING_RAW; } } -#ifdef __WITH_X509__ +#ifdef __WITH_DTLS__ //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type. jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME); @@ -860,7 +860,7 @@ OicSecCred_t * JSONToCredBin(const char * jsonStr) memcpy(cred->publicData.data, jsonPub->valuestring, jsonObjLen); cred->publicData.len = jsonObjLen; } -#endif // __WITH_X509__ +#endif // __WITH_DTLS__ //Period -- Not Mandatory jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME); if(jsonObj && cJSON_String == jsonObj->type) diff --git a/resource/csdk/security/unittest/SConscript b/resource/csdk/security/unittest/SConscript index 242e93c..b94a5e0 100644 --- a/resource/csdk/security/unittest/SConscript +++ b/resource/csdk/security/unittest/SConscript @@ -62,19 +62,19 @@ srmtest_env.PrependUnique(LIBS = ['ocsrm', 'coap']) if srmtest_env.get('SECURED') == '1': - srmtest_env.AppendUnique(LIBS = ['tinydtls', 'timer']) - -if srmtest_env.get('WITH_TCP') == True: - srmtest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) + srmtest_env.AppendUnique(LIBS = ['mbedtls','mbedx509','mbedcrypto']) + srmtest_env.AppendUnique(LIBS = ['tinydtls']) if srmtest_env.get('LOGGING') == '1': srmtest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) if target_os == 'windows': - srmtest_env.AppendUnique(LIBS = ['advapi32', 'bcrypt', 'kernel32', 'ws2_32', 'iphlpapi']) + srmtest_env.AppendUnique(LINKFLAGS = ['/subsystem:CONSOLE']) + srmtest_env.AppendUnique(LIBS = ['advapi32', 'bcrypt', 'kernel32', 'ws2_32', 'iphlpapi', 'octbstack_static']) else: # TODO: Implement feature check. srmtest_env.AppendUnique(CPPDEFINES = ['HAVE_LOCALTIME_R']) + srmtest_env.AppendUnique(LIBS = ['octbstack']) ###################################################################### # Source files and Targets diff --git a/resource/csdk/security/unittest/credentialresource.cpp b/resource/csdk/security/unittest/credentialresource.cpp index 13fce86..191cc67 100644 --- a/resource/csdk/security/unittest/credentialresource.cpp +++ b/resource/csdk/security/unittest/credentialresource.cpp @@ -106,12 +106,12 @@ static void printCred(const OicSecCred_t * cred) { OIC_LOG_V(INFO, TAG, "cred->privateData.data = %s", credTmp1->privateData.data); } -#ifdef __WITH_X509__ +#ifdef __WITH_DTLS__ if(credTmp1->publicData.data) { OIC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data); } -#endif /* __WITH_X509__ */ +#endif /* __WITH_DTLS__ */ OIC_LOG_V(INFO, TAG, "cred->rownerID = %s", credTmp1->rownerID.id); } } @@ -391,48 +391,7 @@ TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject) } #endif -#ifdef __WITH_X509__ -#include - -static char PROV_TOOL_DB_FILE[] = "/oic_svr_db_prov.dat"; - -#define STRINGIZE2(x) #x -#define STRINGIZE(x) STRINGIZE2(x) - -static FILE *client_fopen(const char* UNUSED_PARAM , const char *mode) -{ - (void)UNUSED_PARAM; - - int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(PROV_TOOL_DB_FILE) + 1; - char *filepath = (char *)OICCalloc(1, len); - - if (!filepath) - { - printf("filepath memory allocation failed. \n"); - return NULL; - } - - snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), PROV_TOOL_DB_FILE); - - FILE* file = fopen(filepath, mode); - OICFree(filepath); - return file; -} - -static OCPersistentStorage ps = { client_fopen, fread, fwrite, fclose, unlink }; - -//GetDtlsX509Credentials Test -TEST(CredResourceTest, GetDtlsX509Credentials) -{ - ASSERT_EQ(OC_STACK_OK, OCInit(NULL, 0, OC_CLIENT_SERVER)); - OCRegisterPersistentStorageHandler(&ps); - InitCredResource(); - CADtlsX509Creds_t g_X509Cred = {{0}, 0, 0, {0}, {0}, {0}}; - EXPECT_EQ(0, GetDtlsX509Credentials(&g_X509Cred)); -} - -#endif -#if defined(__WITH_DTLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) TEST(CredGetDtlsPskCredentialsTest, NullResult) { EXPECT_EQ(-1, GetDtlsPskCredentials(CA_DTLS_PSK_KEY, NULL, 0, NULL, 0)); @@ -443,7 +402,7 @@ TEST(CredAddTmpPskWithPINTest, NullSubject) EXPECT_EQ(OC_STACK_INVALID_PARAM, AddTmpPskWithPIN(NULL, SYMMETRIC_PAIR_WISE_KEY, NULL, 0, NULL, NULL)); } -#endif +#endif // __WITH_DTLS__ or __WITH_TLS__ TEST(CredCBORPayloadToCredTest, NullPayload) { EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL)); diff --git a/resource/csdk/security/unittest/crlresourcetest.cpp b/resource/csdk/security/unittest/crlresourcetest.cpp index d7c17ef..c617a70 100644 --- a/resource/csdk/security/unittest/crlresourcetest.cpp +++ b/resource/csdk/security/unittest/crlresourcetest.cpp @@ -17,7 +17,7 @@ * limitations under the License. * ******************************************************************/ -#ifdef __WITH_X509__ +#ifdef __WITH_DTLS__ #include "gtest/gtest.h" #include "logger.h" @@ -32,26 +32,9 @@ #include "srmutility.h" #include "psinterface.h" #include "security_internals.h" -#include "crl.h" #define TAG "SRM-CRL-UT" -void DeleteCrl(OicSecCrl_t *crl) -{ - if (crl) - { - //Clean ThisUpdate - OICFree(crl->ThisUpdate.data); - crl->ThisUpdate.data = NULL; - //clean CrlData - OICFree(crl->CrlData.data); - crl->CrlData.data = NULL; - //Clean crl itself - OICFree(crl); - crl = NULL; - } -} - //InitCRLResource Tests TEST(CRLResourceTest, InitCRLResource) { @@ -79,8 +62,8 @@ TEST(CRLResourceTest, CrlToCBORPayload) size_t size; OicSecCrl_t *crl = GetCRLResource(); ASSERT_TRUE(NULL != crl); - size = crl->CrlData.len; - EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size)); + size = 0; + EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size, NULL)); DeleteCrl(crl); OICFree(payload); } @@ -92,8 +75,8 @@ TEST(CRLResourceTest, CBORPayloadToCrl) size_t size; OicSecCrl_t *crl = GetCRLResource(); ASSERT_TRUE(NULL != crl); - size = crl->CrlData.len; - EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size)); + size = 0; + EXPECT_EQ(OC_STACK_OK, CrlToCBORPayload(crl, &payload, &size, NULL)); DeleteCrl(crl); crl = NULL; EXPECT_EQ(OC_STACK_OK, CBORPayloadToCrl(payload, size, &crl)); @@ -104,6 +87,7 @@ TEST(CRLResourceTest, CBORPayloadToCrl) //GetDerCrl Tests TEST(CRLResourceTest, GetDerCrl) { +#define CRL_MAX_LEN 1024 uint8_t crlData[CRL_MAX_LEN] = {0}; ByteArray crlArray = {crlData, CRL_MAX_LEN}; GetDerCrl(&crlArray); diff --git a/resource/csdk/stack/include/ocpayload.h b/resource/csdk/stack/include/ocpayload.h index ad703c5..22afad3 100644 --- a/resource/csdk/stack/include/ocpayload.h +++ b/resource/csdk/stack/include/ocpayload.h @@ -33,7 +33,7 @@ #include "octypes.h" #include -#ifdef __WITH_TLS__ +#if defined(__WITH_TLS__) || defined(__WITH_DTLS__) #include "securevirtualresourcetypes.h" #endif diff --git a/resource/csdk/stack/include/octypes.h b/resource/csdk/stack/include/octypes.h index 6c96945..91cb461 100644 --- a/resource/csdk/stack/include/octypes.h +++ b/resource/csdk/stack/include/octypes.h @@ -878,7 +878,7 @@ typedef enum * processing its requests from clients.*/ OC_SLOW = (1 << 3), -#ifdef __WITH_DTLS__ +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** When this bit is set, the resource is a secure resource.*/ OC_SECURE = (1 << 4), #else diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript b/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript index 9b52f2d..020be7c 100644 --- a/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/SConscript @@ -37,6 +37,7 @@ else: samples_env.PrependUnique(CPPPATH = [ '../../../../logger/include', '../../../../stack/include', + '../../../../security/include', '../../../../../../extlibs/cjson', '../../../../../../extlibs/boost/boost', '../../../../../oc_logger/include', diff --git a/resource/csdk/stack/samples/linux/secure/SConscript b/resource/csdk/stack/samples/linux/secure/SConscript index 8f9d6fd..b271acd 100644 --- a/resource/csdk/stack/samples/linux/secure/SConscript +++ b/resource/csdk/stack/samples/linux/secure/SConscript @@ -29,6 +29,7 @@ samples_env.PrependUnique(CPPPATH = [ '../../../../stack/include', '../../../../security/include', '../../../../../../extlibs/cjson', + '../../../../../../extlibs/tinydtls', '../../../../../oc_logger/include' ]) @@ -48,9 +49,7 @@ else: samples_env.PrependUnique(LIBS = ['m']) samples_env.PrependUnique(LIBS = ['octbstack', 'connectivity_abstraction', 'coap']) if env.get('SECURED') == '1': - samples_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - samples_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) + samples_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) if target_os == 'android': diff --git a/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp b/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp index 5e8ca99..9890e39 100644 --- a/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp +++ b/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp @@ -273,6 +273,10 @@ int InitGetRequest(OCQualityOfService qos) OIC_LOG_V(INFO, TAG, "Executing %s", __func__); std::ostringstream query; query << coapServerResource; + if(WithTcp) + { + endpoint.adapter = OC_ADAPTER_TCP; + } endpoint.flags = (OCTransportFlags)(endpoint.flags|OC_SECURE); return (InvokeOCDoResource(query, OC_REST_GET, &endpoint, diff --git a/resource/csdk/stack/samples/tizen/SimpleClientServer/scons/SConscript b/resource/csdk/stack/samples/tizen/SimpleClientServer/scons/SConscript index 5237143..ca1d2de 100644 --- a/resource/csdk/stack/samples/tizen/SimpleClientServer/scons/SConscript +++ b/resource/csdk/stack/samples/tizen/SimpleClientServer/scons/SConscript @@ -44,7 +44,7 @@ env.Append(LIBS=[ if secured == '1': env.PrependUnique(CPPPATH = [root_dir + '/external/inc/']) env.AppendUnique(CPPDEFINES = ['__WITH_DTLS__']) - env.Append(LIBS=['tinydtls']) + env.Append(LIBS=['mbedtls', 'mbedx509','mbedcrypto']) if 'ALL' in transport: env.AppendUnique(CPPDEFINES = ['IP_ADAPTER','EDR_ADAPTER','LE_ADAPTER','BT_ADAPTER_TEST','BLE_ADAPTER_TEST']) diff --git a/resource/csdk/stack/samples/tizen/build/gbsbuild.sh b/resource/csdk/stack/samples/tizen/build/gbsbuild.sh index 72aa019..84c1b72 100644 --- a/resource/csdk/stack/samples/tizen/build/gbsbuild.sh +++ b/resource/csdk/stack/samples/tizen/build/gbsbuild.sh @@ -49,7 +49,6 @@ mkdir ./tmp/packaging cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git cp -Rf ./extlibs/mbedtls $sourcedir/tmp/extlibs -rm -rf $sourcedir/tmp/extlibs/mbedtls/mbedtls/.git cp -R ./extlibs/cjson $sourcedir/tmp/extlibs cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs cp -R ./extlibs/timer $sourcedir/tmp/extlibs @@ -87,6 +86,13 @@ 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 if [ ! -d .git ]; then diff --git a/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec b/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec index 7ed5135..e8bd664 100644 --- a/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec +++ b/resource/csdk/stack/samples/tizen/build/packaging/com.oic.ri.spec @@ -56,9 +56,14 @@ cp -f %{ROOTDIR}/extlibs/libcoap/libcoap.a %{buildroot}/%{_libdir} cp /usr/lib/libuuid.so.1 %{buildroot}%{_libdir} if echo %{SECURED}|grep -qi '1'; then cp -f %{ROOTDIR}/out/tizen/*/*/extlibs/tinydtls/libtinydtls.a %{buildroot}/%{_libdir} + cp -f %{ROOTDIR}/out/tizen/*/*/libmbedcrypto.a %{buildroot}/%{_libdir} + cp -f %{ROOTDIR}/out/tizen/*/*/libmbedtls.a %{buildroot}/%{_libdir} + cp -f %{ROOTDIR}/out/tizen/*/*/libmbedx509.a %{buildroot}/%{_libdir} fi cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstack.h* %{DEST_INC_DIR}/ +cp -rf %{ROOTDIR}/resource/csdk/security/include/securevirtualresourcetypes.h* %{DEST_INC_DIR}/ +cp -rf %{ROOTDIR}/resource/c_common/byte_array.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/resource/csdk/stack/include/ocstackconfig.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/resource/csdk/stack/include/octypes.h* %{DEST_INC_DIR}/ cp -rf %{ROOTDIR}/resource/csdk/logger/include/logger.h* %{DEST_INC_DIR}/ diff --git a/resource/csdk/stack/test/SConscript b/resource/csdk/stack/test/SConscript index 45b218e..cf34456 100644 --- a/resource/csdk/stack/test/SConscript +++ b/resource/csdk/stack/test/SConscript @@ -52,9 +52,8 @@ if target_os != 'darwin': stacktest_env.PrependUnique(LIBS = ['oc_logger']) if stacktest_env.get('SECURED') == '1': + stacktest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) stacktest_env.AppendUnique(LIBS = ['tinydtls']) - if stacktest_env.get('WITH_TCP') == True: - stacktest_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) if stacktest_env.get('LOGGING'): stacktest_env.AppendUnique(CPPDEFINES = ['TB_LOG']) diff --git a/resource/examples/SConscript b/resource/examples/SConscript index 8c23c83..e25cabf 100644 --- a/resource/examples/SConscript +++ b/resource/examples/SConscript @@ -55,7 +55,7 @@ if target_os in ['msys_nt', 'windows']: examples_env.PrependUnique(LIBS = ['mswsock', 'ws2_32', 'iphlpapi', 'ole32']) if examples_env.get('SECURED') == '1': - examples_env.AppendUnique(LIBS = ['tinydtls']) + examples_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) examples_env.AppendUnique(CPPDEFINES = ['_WITH_DTLS_']) if target_os in ['msys_nt', 'windows']: examples_env.AppendUnique(LIBS = ['advapi32']) diff --git a/resource/include/OCProvisioningManager.h b/resource/include/OCProvisioningManager.h index 3f1a004..f23e39b 100755 --- a/resource/include/OCProvisioningManager.h +++ b/resource/include/OCProvisioningManager.h @@ -27,9 +27,6 @@ #include "ocprovisioningmanager.h" #include "OCApi.h" #include "OCPlatform_impl.h" -#ifdef __WITH_TLS__ -#include "OCCloudProvisioning.h" -#endif namespace OC { @@ -211,7 +208,7 @@ namespace OC std::string uuid, ResultCallBack resultCallback); -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * API to save Trust certificate chain into Cred of SVR. * @@ -223,7 +220,7 @@ namespace OC */ static OCStackResult saveTrustCertChain(uint8_t *trustCertChain, size_t chainSize, OicEncodingType_t encodingType, uint16_t *credId); -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ }; @@ -326,7 +323,7 @@ namespace OC OCStackResult provisionDirectPairing(const OicSecPconf_t *pconf, ResultCallBack resultCallback); -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) /** * API to provision cert. * @@ -339,7 +336,7 @@ namespace OC OCStackResult provisionTrustCertChain(OicSecCredType_t type, uint16_t credId, ResultCallBack resultCallback); -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ /** * This method is used to get linked devices' IDs. diff --git a/resource/provisioning/examples/SConscript b/resource/provisioning/examples/SConscript index 4dbaf3c..ec21321 100644 --- a/resource/provisioning/examples/SConscript +++ b/resource/provisioning/examples/SConscript @@ -38,8 +38,8 @@ examples_env = lib_env.Clone() ###################################################################### examples_env.AppendUnique(CPPPATH = [ '../../include/', - '../../../extlibs/cjson', '../../csdk/stack/include', + '../../../extlibs/cjson', '../../csdk/logger/include', '../../oc_logger/include', '../../csdk/connectivity/api', @@ -48,9 +48,9 @@ examples_env.AppendUnique(CPPPATH = [ '../../csdk/connectivity/lib/libcoap-4.1.1/include', '../../csdk/security/include', '../../csdk/security/include/internal', + '../../csdk/security/provisioning/include/cloud', '../../csdk/security/provisioning/include', '../../csdk/security/provisioning/include/oxm', - '../../csdk/security/provisioning/include/cloud', '../../csdk/security/provisioning/include/internal' ]) @@ -69,11 +69,7 @@ else : examples_env.AppendUnique(LIBS = ['ra_xmpp']) if examples_env.get('SECURED') == '1': - examples_env.AppendUnique(LIBS = ['tinydtls']) - examples_env.AppendUnique(LIBS = ['timer']) -if examples_env.get('DTLS_WITH_X509') == '1': - examples_env.AppendUnique(LIBS = ['CKManager']) - examples_env.AppendUnique(LIBS = ['asn1']) + examples_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) if 'g++' in examples_env.get('CXX'): examples_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) @@ -98,7 +94,7 @@ if target_os == 'tizen': provisioningclient = examples_env.Program('provisioningclient', 'provisioningclient.cpp') if examples_env.get('WITH_TCP') == True: - cloudClient = examples_env.Program('cloudClient',['cloudClient.cpp', 'cloudAuth.cpp', 'cloudWrapper.cpp']) + cloudClient = examples_env.Program('cloudClient',['cloudClient.cpp', 'cloudAuth.cpp', 'cloudWrapper.cpp']) src_dir = examples_env.get('SRC_DIR') svr_db_src_dir = src_dir + '/resource/provisioning/examples/' @@ -108,12 +104,13 @@ clientjson = examples_env.Install(svr_db_build_dir, svr_db_src_dir + 'oic_svr_db clientdat = examples_env.Install(svr_db_build_dir, svr_db_src_dir + 'oic_svr_db_client.dat') if examples_env.get('WITH_TCP') == True: - clouddat = examples_env.Install(svr_db_build_dir, - svr_db_src_dir + 'cloud.dat') - rootcert = examples_env.Install(svr_db_build_dir, - svr_db_src_dir + 'rootca.crt') - Alias("cloud", [clouddat, rootcert, cloudClient]) - examples_env.AppendTarget("cloud") + clouddat = examples_env.Install(svr_db_build_dir, + svr_db_src_dir + 'cloud.dat') + rootcert = examples_env.Install(svr_db_build_dir, + svr_db_src_dir + 'rootca.crt') + Alias("cloud", [clouddat, rootcert, cloudClient]) + examples_env.AppendTarget("cloud") Alias("examples", [provisioningclient, clientjson,clientdat]) examples_env.AppendTarget('examples') + diff --git a/resource/provisioning/src/OCProvisioningManager.cpp b/resource/provisioning/src/OCProvisioningManager.cpp index 31700cb..f2e714c 100755 --- a/resource/provisioning/src/OCProvisioningManager.cpp +++ b/resource/provisioning/src/OCProvisioningManager.cpp @@ -308,7 +308,7 @@ namespace OC return result; } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) OCStackResult OCSecure::saveTrustCertChain(uint8_t *trustCertChain, size_t chainSize, OicEncodingType_t encodingType, uint16_t *credId) { @@ -338,7 +338,7 @@ namespace OC } return result; } -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ || __WITH_TLS__ void OCSecureResource::callbackWrapper(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError) { @@ -632,7 +632,7 @@ namespace OC return result; } -#if defined(__WITH_X509__) || defined(__WITH_TLS__) +#if defined(__WITH_DTLS__) || defined(__WITH_TLS__) OCStackResult OCSecureResource::provisionTrustCertChain(OicSecCredType_t type, uint16_t credId, ResultCallBack resultCallback) { @@ -666,7 +666,7 @@ namespace OC } return result; } -#endif // __WITH_X509__ || __WITH_TLS__ +#endif // __WITH_DTLS__ or __WITH_TLS__ std::string OCSecureResource::getDeviceID() { diff --git a/resource/provisioning/unittests/OCCloudProvisioningTest.cpp b/resource/provisioning/unittests/OCCloudProvisioningTest.cpp index 304369a..81b0ac2 100755 --- a/resource/provisioning/unittests/OCCloudProvisioningTest.cpp +++ b/resource/provisioning/unittests/OCCloudProvisioningTest.cpp @@ -25,6 +25,7 @@ #include #include #include +#include "OCCloudProvisioning.h" #include #define TIMEOUT 5 diff --git a/resource/provisioning/unittests/SConscript b/resource/provisioning/unittests/SConscript index b3abc6c..c7a4561 100755 --- a/resource/provisioning/unittests/SConscript +++ b/resource/provisioning/unittests/SConscript @@ -75,14 +75,7 @@ else : provisiontests_env.AppendUnique(LIBS = ['ra_xmpp']) if provisiontests_env.get('SECURED') == '1': - provisiontests_env.AppendUnique(LIBS = ['tinydtls']) - provisiontests_env.AppendUnique(LIBS = ['timer']) - if provisiontests_env.get('WITH_TCP') == True: - provisiontests_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) - -if provisiontests_env.get('DTLS_WITH_X509') == '1': - provisiontests_env.AppendUnique(LIBS = ['CKManager']) - provisiontests_env.AppendUnique(LIBS = ['asn1']) + provisiontests_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) if provisiontests_env.get('LOGGING'): @@ -92,13 +85,13 @@ if provisiontests_env.get('LOGGING'): # Source files and Targets ###################################################################### ocprovisiontest_src = [ - 'OCProvisioningTest.cpp' - ] + 'OCProvisioningTest.cpp' + ] if provisiontests_env.get('WITH_TCP') == True: - ocprovisiontest_src = ocprovisiontest_src + [ - 'OCCloudProvisioningTest.cpp' - ] + ocprovisiontest_src = ocprovisiontest_src + [ + 'OCCloudProvisioningTest.cpp' + ] unittests = provisiontests_env.Program('provisiontests', ocprovisiontest_src) diff --git a/resource/src/SConscript b/resource/src/SConscript index 514b0b5..cfec587 100644 --- a/resource/src/SConscript +++ b/resource/src/SConscript @@ -85,7 +85,7 @@ if target_os in ['msys_nt', 'windows']: oclib_env.AppendUnique(LIBS=['octbstack', 'logger', 'oc_logger','connectivity_abstraction', 'ocsrm', 'c_common', 'routingmanager']) oclib_env.AppendUnique(LIBS=[ 'coap', 'ws2_32' ,'iphlpapi']) if secured == '1': - oclib_env.AppendUnique(LIBS=['tinydtls']) + oclib_env.AppendUnique(LIBS=['mbedtls', 'mbedx509','mbedcrypto']) if with_cloud: oclib_env.AppendUnique(CPPDEFINES = ['WITH_CLOUD']) diff --git a/resource/unittests/SConscript b/resource/unittests/SConscript index 04c9043..afaaeff 100644 --- a/resource/unittests/SConscript +++ b/resource/unittests/SConscript @@ -63,9 +63,8 @@ unittests_env.PrependUnique(LIBS = [ ]) if unittests_env.get('SECURED') == '1': + unittests_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) unittests_env.AppendUnique(LIBS = ['tinydtls']) - if unittests_env.get('WITH_TCP') == True: - unittests_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) if unittests_env.get('LOGGING'): unittests_env.AppendUnique(CPPDEFINES = ['TB_LOG']) diff --git a/service/coap-http-proxy/samples/SConscript b/service/coap-http-proxy/samples/SConscript index 963b509..2eb3b6f 100644 --- a/service/coap-http-proxy/samples/SConscript +++ b/service/coap-http-proxy/samples/SConscript @@ -42,13 +42,13 @@ proxy_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) proxy_sample_app_env.PrependUnique(LIBS = ['coap_http_proxy', 'oc', 'octbstack', 'curl', 'connectivity_abstraction']) if env.get('SECURED') == '1': - proxy_sample_app_env.AppendUnique(LIBS = ['tinydtls']) + proxy_sample_app_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) #################################################################### # Source files and Targets ###################################################################### proxy_server = proxy_sample_app_env.Program('proxy_main', 'proxy_main.c') -proxy_client = proxy_sample_app_env.Program('proxy_client', 'proxy_client.c') + Alias("coap_http_proxy", [proxy_server]) env.AppendTarget('coap_http_proxy') diff --git a/service/easy-setup/enrollee/SConscript b/service/easy-setup/enrollee/SConscript index 5f08051..400ff7a 100644 --- a/service/easy-setup/enrollee/SConscript +++ b/service/easy-setup/enrollee/SConscript @@ -57,8 +57,7 @@ if enrollee_env.get('SECURED') == '1': enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include', enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal', enrollee_env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/oxm']) - if enrollee_env.get('WITH_TCP') == True: - enrollee_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + enrollee_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) if target_os not in ['windows']: enrollee_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x']) diff --git a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh index 8e72b50..dfcadac 100644 --- a/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh +++ b/service/easy-setup/sampleapp/enrollee/tizen-sdb/EnrolleeSample/build/tizen/gbsbuild.sh @@ -61,18 +61,9 @@ cd $sourcedir/tmp echo `pwd` if [ -d ./extlibs/mbedtls/mbedtls ];then cd ./extlibs/mbedtls/mbedtls - git reset --hard ad249f509fd62a3bbea7ccd1fef605dbd482a7bd ; git apply ../ocf.patch + git reset --hard ad249f509fd62a3bbea7ccd1fef605dbd482a7bd ; git apply --whitespace=fix ../ocf.patch cd - rm -rf ./extlibs/mbedtls/mbedtls/.git* - -else - echo "" - echo "*********************************** Error: ****************************************" - echo "* Please download mbedtls using the following command: *" - echo "* $ git clone https://github.com/ARMmbed/mbedtls.git extlibs/mbedtls/mbedtls *" - echo "***********************************************************************************" - echo "" - exit fi rm -rf ./extlibs/tinycbor/tinycbor/.git* diff --git a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript index 9b17f05..2f422a2 100644 --- a/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript +++ b/service/easy-setup/sampleapp/mediator/linux/richsdk_sample/SConscript @@ -50,7 +50,6 @@ mediator_env.PrependUnique(CPPPATH = [ env.get('SRC_DIR') + '/resource/csdk/stack/include', env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include', env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/internal', - env.get('SRC_DIR') + '/resource/csdk/security/provisioning/include/cloud', env.get('SRC_DIR') + '/resource/csdk/logger/include', env.get('SRC_DIR') + '/resource/csdk/security/include', env.get('SRC_DIR') + '/resource/csdk/connectivity/api', @@ -60,14 +59,12 @@ mediator_env.PrependUnique(CPPPATH = [ env.get('SRC_DIR') + '/service/easy-setup/inc']) if env.get('SECURED') == '1': - mediator_env.PrependUnique(LIBS = ['tinydtls', 'timer']) + mediator_env.PrependUnique(LIBS = ['mbedtls', 'mbedx509','mbedcrypto']) mediator_env.PrependUnique(LIBS = ['ESMediatorRich', 'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction']) if env.get('SECURED') == '1': mediator_env.PrependUnique(LIBS = ['ocpmapi', 'ocprovision']) - if env.get('WITH_TCP') == True: - mediator_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) mediator = mediator_env.Program('mediator_rich', 'mediator_cpp.cpp') diff --git a/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript b/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript index adf1471..7548813 100644 --- a/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript +++ b/service/resource-container/examples/BMISensorBundle/src/inputSensors/HeightSensorApp/SConscript @@ -24,9 +24,7 @@ linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': - linux_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) # On some platforms link order can miss functions so librt needs to be # re-scanned at the end if present. gcc 4.6 is one with this issue. diff --git a/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript b/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript index ca33f95..10cd7d6 100644 --- a/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript +++ b/service/resource-container/examples/BMISensorBundle/src/inputSensors/WeightSensorApp/SConscript @@ -24,9 +24,7 @@ linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': - linux_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) # On some platforms link order can miss functions so librt needs to be # re-scanned at the end if present. gcc 4.6 is one with this issue. diff --git a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript index 8ef7f09..9cb35f7 100644 --- a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript +++ b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp/SConscript @@ -24,9 +24,7 @@ linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': - linux_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) # # On some platforms link order can miss functions so librt needs to be # re-scanned at the end if present. gcc 4.6 is one with this issue. diff --git a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript index 00c7210..7643066 100644 --- a/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript +++ b/service/resource-container/examples/DiscomfortIndexSensorBundle/src/inputSensors/THSensorApp1/SConscript @@ -24,9 +24,7 @@ linux_sample_env.AppendUnique(LIBS = ['oc']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': - linux_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) # On some platforms link order can miss functions so librt needs to be # re-scanned at the end if present. gcc 4.6 is one with this issue. diff --git a/service/resource-encapsulation/examples/linux/SConscript b/service/resource-encapsulation/examples/linux/SConscript index 4943374..90fbd58 100644 --- a/service/resource-encapsulation/examples/linux/SConscript +++ b/service/resource-encapsulation/examples/linux/SConscript @@ -42,9 +42,7 @@ sample_env.AppendUnique(LIBS = [ sample_env.AppendUnique(CPPPATH = ['../../include']) if env.get('SECURED') == '1': - sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) if 'rt' in sample_env.get('LIBS'): sample_env.Append(LIBS = ['rt']) diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript b/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript index 48e297e..0eef19a 100644 --- a/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript +++ b/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript @@ -38,7 +38,7 @@ sample_env.AppendUnique(LIBS = [ 'oc', 'rcs_common', 'pthread', - 'tinydtls' + 'mbedtls', 'mbedx509', 'mbedcrypto' ]) sample_env.AppendUnique(CPPPATH = ['../../../include']) diff --git a/service/resource-hosting/SampleApp/linux/SConscript b/service/resource-hosting/SampleApp/linux/SConscript index 5806f59..71860b5 100644 --- a/service/resource-hosting/SampleApp/linux/SConscript +++ b/service/resource-hosting/SampleApp/linux/SConscript @@ -38,11 +38,8 @@ resourcehosting_sample_env.AppendUnique(LIBS = [ ]) if env.get('SECURED') == '1': - resourcehosting_env.AppendUnique(LIBS = ['tinydtls']) - resourcehosting_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - resourcehosting_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) - resourcehosting_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + resourcehosting_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + if 'rt' in resourcehosting_env.get('LIBS'): resourcehosting_env.Append(LIBS = ['rt']) if 'rt' in resourcehosting_sample_env.get('LIBS'): diff --git a/service/scene-manager/sampleapp/linux/SConscript b/service/scene-manager/sampleapp/linux/SConscript index 47afe65..6853e4b 100644 --- a/service/scene-manager/sampleapp/linux/SConscript +++ b/service/scene-manager/sampleapp/linux/SConscript @@ -28,9 +28,7 @@ scenemanager_sample_env.AppendUnique(LIBS = ['connectivity_abstraction']) scenemanager_sample_env.AppendUnique(LIBS = ['coap']) if env.get('SECURED') == '1': - scenemanager_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - scenemanager_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + scenemanager_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) if 'rt' in scenemanager_sample_env.get('LIBS'): scenemanager_sample_env.Append(LIBS = ['rt']) diff --git a/service/simulator/examples/client/SConscript b/service/simulator/examples/client/SConscript index 76bb3e8..e5f7676 100644 --- a/service/simulator/examples/client/SConscript +++ b/service/simulator/examples/client/SConscript @@ -17,7 +17,7 @@ sim_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) sim_env.PrependUnique(LIBS = ['SimulatorManager']) if sim_env.get('SECURED') == '1': - sim_env.AppendUnique(LIBS = ['tinydtls']) + sim_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) ###################################################################### # Source files and Targets diff --git a/service/simulator/examples/server/SConscript b/service/simulator/examples/server/SConscript index c86ba32..b5b8a39 100644 --- a/service/simulator/examples/server/SConscript +++ b/service/simulator/examples/server/SConscript @@ -17,7 +17,7 @@ sim_env.AppendUnique(RPATH = [env.get('BUILD_DIR')]) sim_env.PrependUnique(LIBS = ['SimulatorManager']) if sim_env.get('SECURED') == '1': - sim_env.AppendUnique(LIBS = ['tinydtls']) + sim_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) ###################################################################### # Source files and Targets diff --git a/service/things-manager/sampleapp/linux/configuration/SConscript b/service/things-manager/sampleapp/linux/configuration/SConscript index e79f01f..36d95c9 100644 --- a/service/things-manager/sampleapp/linux/configuration/SConscript +++ b/service/things-manager/sampleapp/linux/configuration/SConscript @@ -49,9 +49,7 @@ linux_sample_env.AppendUnique(LIBS = ['dl']) linux_sample_env.AppendUnique(LIBS = ['pthread']) if env.get('SECURED') == '1': - linux_sample_env.AppendUnique(LIBS = ['tinydtls']) - if env.get('WITH_TCP') == True: - linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) + linux_sample_env.AppendUnique(LIBS = ['mbedtls', 'mbedx509', 'mbedcrypto']) # On some platforms link order can miss functions so librt needs to be # re-scanned at the end if present. gcc 4.6 is one with this issue.