Commit e6fec04b authored by Dmitriy Zhuravlev's avatar Dmitriy Zhuravlev Committed by Randeep

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: default avatarDmitriy Zhuravlev <d.zhuravlev@samsung.com>
X-Origin-Change-Id: I6b47f7b3439b923ec12f26b0e159e3b7a1144658
Signed-off-by: default avatarPhilippe Coval <philippe.coval@osg.samsung.com>
Signed-off-by: default avatarOleksii Beketov <ol.beketov@samsung.com>
Signed-off-by: default avatarDmitriy Zhuravlev <d.zhuravlev@samsung.com>
Signed-off-by: default avatarTrevor Bramwell <tbramwell@linuxfoundation.org>
Reviewed-on: https://gerrit.iotivity.org/gerrit/12029Tested-by: default avatarjenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Randeep's avatarRandeep Singh <randeep.s@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/13095Reviewed-by: default avatarKevin Kane <kkane@microsoft.com>
parent 96baeeea
......@@ -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)
......
......@@ -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
......
......@@ -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'])
......
##
# 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')
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
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
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
......@@ -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)
......
......@@ -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'])
......
......@@ -32,18 +32,18 @@ extern "C" {
#include <stdint.h>
/**
* @struct ByteArray
* @struct ByteArray_t
*
* General purpose byte array structure.
*
* Contains pointer to array of bytes and it's length.
*/
typedef struct
typedef struct ByteArray
{
uint8_t *data; /**< Pointer to the byte array */
size_t len; /**< Data size */
} ByteArray;
} ByteArray_t;
/**@def BYTE_ARRAY_INITIALIZER
......@@ -57,7 +57,7 @@ typedef struct
*
* Initializes of existing byte array \a array.
*
* @param array ByteArray
* @param array ByteArray_t
*/
#undef INIT_BYTE_ARRAY
#define INIT_BYTE_ARRAY(array) do{ \
......
......@@ -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'])
......
......@@ -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']:
......
......@@ -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" */
......
......@@ -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
......
......@@ -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/