[entropy] allow for entropy source sharing (#3818)

This commit is contained in:
Kamil Sroka
2019-05-17 12:41:03 -07:00
committed by Jonathan Hui
parent fc580c39e6
commit 56fa9ac9cd
110 changed files with 1510 additions and 598 deletions
+5 -1
View File
@@ -113,10 +113,14 @@ LOCAL_SRC_FILES := \
src/core/coap/coap_message.cpp \
src/core/coap/coap_secure.cpp \
src/core/common/crc16.cpp \
src/core/common/entropy.cpp \
src/core/common/instance.cpp \
src/core/common/logging.cpp \
src/core/common/message.cpp \
src/core/common/notifier.cpp \
src/core/common/random_crypto.cpp \
src/core/common/random_manager.cpp \
src/core/common/random_noncrypto.cpp \
src/core/common/settings.cpp \
src/core/common/string.cpp \
src/core/common/tasklet.cpp \
@@ -205,11 +209,11 @@ LOCAL_SRC_FILES := \
src/ncp/spinel_decoder.cpp \
src/ncp/spinel_encoder.cpp \
src/posix/platform/alarm.c \
src/posix/platform/entropy.c \
src/posix/platform/hdlc_interface.cpp \
src/posix/platform/logging.c \
src/posix/platform/misc.c \
src/posix/platform/radio_spinel.cpp \
src/posix/platform/random.c \
src/posix/platform/settings.cpp \
src/posix/platform/system.c \
src/posix/platform/uart.c \
@@ -56,11 +56,11 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\..\examples\platforms\posix\alarm.c" />
<ClCompile Include="..\..\examples\platforms\posix\entropy.c" />
<ClCompile Include="..\..\examples\platforms\posix\flash-windows-stubs.c" />
<ClCompile Include="..\..\examples\platforms\posix\logging.c" />
<ClCompile Include="..\..\examples\platforms\posix\misc.c" />
<ClCompile Include="..\..\examples\platforms\posix\radio.c" />
<ClCompile Include="..\..\examples\platforms\posix\random.c" />
<ClCompile Include="..\..\examples\platforms\posix\spi-stubs.c" />
<ClCompile Include="..\..\examples\platforms\posix\system.c" />
<ClCompile Include="..\..\examples\platforms\posix\uart-windows.c" />
@@ -22,7 +22,7 @@
<ClCompile Include="..\..\examples\platforms\posix\misc.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\examples\platforms\posix\random.c">
<ClCompile Include="..\..\examples\platforms\posix\entropy.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\examples\platforms\posix\radio.c">
+8
View File
@@ -69,6 +69,8 @@
<ClCompile Include="..\..\src\core\api\logging_api.cpp" />
<ClCompile Include="..\..\src\core\api\message_api.cpp" />
<ClCompile Include="..\..\src\core\api\netdata_api.cpp" />
<ClCompile Include="..\..\src\core\api\random_crypto_api.cpp" />
<ClCompile Include="..\..\src\core\api\random_noncrypto_api.cpp" />
<ClCompile Include="..\..\src\core\api\tasklet_api.cpp" />
<ClCompile Include="..\..\src\core\api\thread_api.cpp" />
<ClCompile Include="..\..\src\core\api\thread_ftd_api.cpp" />
@@ -77,10 +79,14 @@
<ClCompile Include="..\..\src\core\coap\coap_message.cpp" />
<ClCompile Include="..\..\src\core\coap\coap_secure.cpp" />
<ClCompile Include="..\..\src\core\common\crc16.cpp" />
<ClCompile Include="..\..\src\core\common\entropy.cpp" />
<ClCompile Include="..\..\src\core\common\instance.cpp" />
<ClCompile Include="..\..\src\core\common\logging.cpp" />
<ClCompile Include="..\..\src\core\common\message.cpp" />
<ClCompile Include="..\..\src\core\common\notifier.cpp" />
<ClCompile Include="..\..\src\core\common\random_crypto.cpp" />
<ClCompile Include="..\..\src\core\common\random_manager.cpp" />
<ClCompile Include="..\..\src\core\common\random_noncrypto.cpp" />
<ClCompile Include="..\..\src\core\common\settings.cpp" />
<ClCompile Include="..\..\src\core\common\string.cpp" />
<ClCompile Include="..\..\src\core\common\tasklet.cpp" />
@@ -169,6 +175,7 @@
<ClInclude Include="..\..\src\core\common\context.hpp" />
<ClInclude Include="..\..\src\core\common\debug.hpp" />
<ClInclude Include="..\..\src\core\common\encoding.hpp" />
<ClInclude Include="..\..\src\core\common\entropy.hpp" />
<ClInclude Include="..\..\src\core\common\instance.hpp" />
<ClInclude Include="..\..\src\core\common\locator.hpp" />
<ClInclude Include="..\..\src\core\common\locator-getters.hpp" />
@@ -176,6 +183,7 @@
<ClInclude Include="..\..\src\core\common\message.hpp" />
<ClInclude Include="..\..\src\core\common\notifier.hpp" />
<ClInclude Include="..\..\src\core\common\new.hpp" />
<ClInclude Include="..\..\src\core\common\random.hpp" />
<ClInclude Include="..\..\src\core\common\string.hpp" />
<ClInclude Include="..\..\src\core\common\tasklet.hpp" />
<ClInclude Include="..\..\src\core\common\timer.hpp" />
+10
View File
@@ -78,6 +78,8 @@
<ClCompile Include="..\..\src\core\api\link_api.cpp" />
<ClCompile Include="..\..\src\core\api\message_api.cpp" />
<ClCompile Include="..\..\src\core\api\netdata_api.cpp" />
<ClCompile Include="..\..\src\core\api\random_crypto_api.cpp" />
<ClCompile Include="..\..\src\core\api\random_noncrypto_api.cpp" />
<ClCompile Include="..\..\src\core\api\tasklet_api.cpp" />
<ClCompile Include="..\..\src\core\api\thread_api.cpp" />
<ClCompile Include="..\..\src\core\api\thread_ftd_api.cpp" />
@@ -85,11 +87,15 @@
<ClCompile Include="..\..\src\core\coap\coap.cpp" />
<ClCompile Include="..\..\src\core\coap\coap_message.cpp" />
<ClCompile Include="..\..\src\core\coap\coap_secure.cpp" />
<ClCompile Include="..\..\src\core\common\entropy.cpp" />
<ClCompile Include="..\..\src\core\common\crc16.cpp" />
<ClCompile Include="..\..\src\core\common\instance.cpp" />
<ClCompile Include="..\..\src\core\common\logging.cpp" />
<ClCompile Include="..\..\src\core\common\message.cpp" />
<ClCompile Include="..\..\src\core\common\notifier.cpp" />
<ClCompile Include="..\..\src\core\common\random_crypto.cpp" />
<ClCompile Include="..\..\src\core\common\random_manager.cpp" />
<ClCompile Include="..\..\src\core\common\random_noncrypto.cpp" />
<ClCompile Include="..\..\src\core\common\settings.cpp" />
<ClCompile Include="..\..\src\core\common\string.cpp" />
<ClCompile Include="..\..\src\core\common\tasklet.cpp" />
@@ -99,6 +105,7 @@
<ClCompile Include="..\..\src\core\crypto\aes_ccm.cpp" />
<ClCompile Include="..\..\src\core\crypto\aes_ecb.cpp" />
<ClCompile Include="..\..\src\core\crypto\hmac_sha256.cpp" />
<ClCompile Include="..\..\src\core\crypto\mbedtls.cpp" />
<ClCompile Include="..\..\src\core\crypto\pbkdf2_cmac.cpp" />
<ClCompile Include="..\..\src\core\crypto\sha256.cpp" />
<ClCompile Include="..\..\src\core\mac\channel_mask.cpp" />
@@ -195,6 +202,7 @@
<ClInclude Include="..\..\src\core\common\context.hpp" />
<ClInclude Include="..\..\src\core\common\crc16.hpp" />
<ClInclude Include="..\..\src\core\common\debug.hpp" />
<ClInclude Include="..\..\src\core\common\entropy.hpp" />
<ClInclude Include="..\..\src\core\common\encoding.hpp" />
<ClInclude Include="..\..\src\core\common\instance.hpp" />
<ClInclude Include="..\..\src\core\common\locator.hpp" />
@@ -203,6 +211,8 @@
<ClInclude Include="..\..\src\core\common\message.hpp" />
<ClInclude Include="..\..\src\core\common\notifier.hpp" />
<ClInclude Include="..\..\src\core\common\new.hpp" />
<ClInclude Include="..\..\src\core\common\random.hpp" />
<ClInclude Include="..\..\src\core\common\random_manager.hpp" />
<ClInclude Include="..\..\src\core\common\string.hpp" />
<ClInclude Include="..\..\src\core\common\tasklet.hpp" />
<ClInclude Include="..\..\src\core\common\timer.hpp" />
+1 -7
View File
@@ -424,13 +424,7 @@ uint16_t otPlatMessagePoolNumFreeBuffers(_In_ otInstance *otCtx)
#endif
uint32_t otPlatRandomGet()
{
LARGE_INTEGER Counter = KeQueryPerformanceCounter(NULL);
return (uint32_t)RtlRandomEx(&Counter.LowPart);
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
// Just use the system-preferred random number generator algorithm
NTSTATUS status =
+1 -1
View File
@@ -48,11 +48,11 @@ libopenthread_cc1352_a_CPPFLAGS
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
system.c \
uart.c \
crypto/aes_alt.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -26,12 +26,19 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements an entropy source based on TRNG.
*
*/
#include <openthread/platform/entropy.h>
#include <openthread/config.h>
#include <stddef.h>
#include <utils/code_utils.h>
#include <openthread/platform/random.h>
#include <driverlib/prcm.h>
#include <driverlib/trng.h>
@@ -66,17 +73,6 @@ void cc1352RandomInit(void)
TRNGEnable();
}
/**
* Function documented in platform/random.h
*/
uint32_t otPlatRandomGet(void)
{
while (!(TRNGStatusGet() & TRNG_NUMBER_READY))
;
return TRNGNumberGet(TRNG_LOW_WORD);
}
/**
* Fill an arbitrary area with random data.
*
@@ -122,9 +118,9 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen)
}
/**
* Function documented in platform/random.h
* Function documented in platform/entropy.h
*/
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
size_t length = aOutputLength;
+2 -2
View File
@@ -36,10 +36,10 @@
#include <assert.h>
#include <utils/code_utils.h>
#include <openthread/random_noncrypto.h> /* to seed the CSMA-CA funciton */
#include <openthread/platform/alarm-milli.h>
#include <openthread/platform/diag.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h> /* to seed the CSMA-CA funciton */
#include "cc1352_radio.h"
#include <driverlib/chipinfo.h>
@@ -659,7 +659,7 @@ static uint_fast8_t rfCoreSendTransmitCmd(uint8_t *aPsdu, uint8_t aLen)
sCsmacaBackoffCmd = cCsmacaBackoffCmd;
/* initialize the random state with a true random seed for the radio core's
* psudo rng */
sCsmacaBackoffCmd.randomState = otPlatRandomGet();
sCsmacaBackoffCmd.randomState = otRandomNonCryptoGetUint16();
sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *)&sTransmitCmd;
sTransmitCmd = cTransmitCmd;
+1 -1
View File
@@ -39,10 +39,10 @@ libopenthread_cc2538_a_CPPFLAGS = \
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
flash.c \
misc.c \
radio.c \
random.c \
startup-gcc.c \
system.c \
logging.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,12 +28,13 @@
/**
* @file
* This file implements a random number generator.
* This file implements an entropy source based on ADC.
*
*/
#include <openthread/platform/entropy.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h>
#include "platform-cc2538.h"
#include "utils/code_utils.h"
@@ -79,20 +80,7 @@ void cc2538RandomInit(void)
HWREG(SOC_ADC_RNDL) = seed & 0xff;
}
uint32_t otPlatRandomGet(void)
{
uint32_t random = 0;
HWREG(SOC_ADC_ADCCON1) |= SOC_ADC_ADCCON1_RCTRL0;
random = HWREG(SOC_ADC_RNDL) | (HWREG(SOC_ADC_RNDH) << 8);
HWREG(SOC_ADC_ADCCON1) |= SOC_ADC_ADCCON1_RCTRL0;
random |= ((HWREG(SOC_ADC_RNDL) | (HWREG(SOC_ADC_RNDH) << 8)) << 16);
return random;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
uint8_t channel = 0;
+1 -1
View File
@@ -48,11 +48,11 @@ libopenthread_cc2650_a_CPPFLAGS = \
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
flash.c \
misc.c \
logging.c \
radio.c \
random.c \
system.c \
uart.c \
crypto/sha256_alt.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -26,13 +26,19 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements an entropy source based on TRNG.
*
*/
#include <openthread/platform/entropy.h>
#include <utils/code_utils.h>
#include <driverlib/prcm.h>
#include <driverlib/trng.h>
#include <openthread/platform/random.h>
#include <mbedtls/entropy_poll.h>
enum
@@ -65,17 +71,6 @@ void cc2650RandomInit(void)
TRNGEnable();
}
/**
* Function documented in platform/random.h
*/
uint32_t otPlatRandomGet(void)
{
while (!(TRNGStatusGet() & TRNG_NUMBER_READY))
;
return TRNGNumberGet(TRNG_LOW_WORD);
}
/**
* Fill an arbitrary area with random data
*
@@ -121,9 +116,9 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen)
}
/**
* Function documented in platform/random.h
* Function documented in platform/entropy.h
*/
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
size_t length = aOutputLength;
+2 -2
View File
@@ -31,10 +31,10 @@
#include "cc2650_radio.h"
#include <assert.h>
#include <utils/code_utils.h>
#include <openthread/random_noncrypto.h> /* to seed the CSMA-CA funciton */
#include <openthread/platform/alarm-milli.h>
#include <openthread/platform/diag.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h> /* to seed the CSMA-CA funciton */
#include <driverlib/chipinfo.h>
#include <driverlib/osc.h>
@@ -603,7 +603,7 @@ static uint_fast8_t rfCoreSendTransmitCmd(uint8_t *aPsdu, uint8_t aLen)
sCsmacaBackoffCmd = cCsmacaBackoffCmd;
/* initialize the random state with a true random seed for the radio core's
* psudo rng */
sCsmacaBackoffCmd.randomState = otPlatRandomGet();
sCsmacaBackoffCmd.randomState = otRandomNonCryptoGetUint16();
sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *)&sTransmitCmd;
sTransmitCmd = cTransmitCmd;
+1 -1
View File
@@ -48,11 +48,11 @@ libopenthread_cc2652_a_CPPFLAGS
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
system.c \
uart.c \
crypto/aes_alt.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -26,12 +26,19 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements an entropy source based on TRNG.
*
*/
#include <openthread/platform/entropy.h>
#include <openthread/config.h>
#include <stddef.h>
#include <utils/code_utils.h>
#include <openthread/platform/random.h>
#include <driverlib/prcm.h>
#include <driverlib/trng.h>
@@ -66,17 +73,6 @@ void cc2652RandomInit(void)
TRNGEnable();
}
/**
* Function documented in platform/random.h
*/
uint32_t otPlatRandomGet(void)
{
while (!(TRNGStatusGet() & TRNG_NUMBER_READY))
;
return TRNGNumberGet(TRNG_LOW_WORD);
}
/**
* Fill an arbitrary area with random data.
*
@@ -122,9 +118,9 @@ static int TRNGPoll(unsigned char *aOutput, size_t aLen)
}
/**
* Function documented in platform/random.h
* Function documented in platform/entropy.h
*/
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
size_t length = aOutputLength;
+2 -2
View File
@@ -36,10 +36,10 @@
#include <assert.h>
#include <utils/code_utils.h>
#include <openthread/random_noncrypto.h> /* to seed the CSMA-CA funciton */
#include <openthread/platform/alarm-milli.h>
#include <openthread/platform/diag.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h> /* to seed the CSMA-CA funciton */
#include "cc2652_radio.h"
#include <driverlib/chipinfo.h>
@@ -658,7 +658,7 @@ static uint_fast8_t rfCoreSendTransmitCmd(uint8_t *aPsdu, uint8_t aLen)
sCsmacaBackoffCmd = cCsmacaBackoffCmd;
/* initialize the random state with a true random seed for the radio core's
* psudo rng */
sCsmacaBackoffCmd.randomState = otPlatRandomGet();
sCsmacaBackoffCmd.randomState = otRandomNonCryptoGetUint16();
sCsmacaBackoffCmd.pNextOp = (rfc_radioOp_t *)&sTransmitCmd;
sTransmitCmd = cTransmitCmd;
+1 -1
View File
@@ -92,12 +92,12 @@ libopenthread_efr32_a_CPPFLAGS =
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
fem-control.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
startup-gcc.c \
system.c \
uart.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,11 +28,11 @@
/**
* @file
* This file implements the OpenThread platform abstraction for random number generator.
* This file implements an entropy source based on ADC.
*
*/
#include <openthread/platform/random.h>
#include <openthread/platform/entropy.h>
#include "utils/code_utils.h"
@@ -68,7 +68,7 @@ void efr32RandomInit(void)
ADC0->SINGLEFIFOCLEAR = ADC_SINGLEFIFOCLEAR_SINGLEFIFOCLEAR;
}
uint32_t otPlatRandomGet(void)
static uint32_t randomUint32Get(void)
{
uint8_t tmp;
uint32_t random = 0;
@@ -93,7 +93,7 @@ uint32_t otPlatRandomGet(void)
return random;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
@@ -101,7 +101,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
for (uint16_t length = 0; length < aOutputLength; length++)
{
aOutput[length] = (uint8_t)otPlatRandomGet();
aOutput[length] = (uint8_t)randomUint32Get();
}
exit:
+1 -1
View File
@@ -67,11 +67,11 @@ COMMONCPPFLAGS
PLATFORM_SOURCES = \
alarm.c \
entropy.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
system.c \
uart.c \
platform-emsk.h \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,18 +28,19 @@
/**
* @file
* This file implements a pseudo-random number generator.
* This file implements an entropy source based on rand().
*
* @warning
* This implementation is not a true random number generator and does @em satisfy the Thread requirements.
*
*/
#include <openthread/platform/entropy.h>
#include <utils/code_utils.h>
#include "platform-emsk.h"
#include "openthread/platform/radio.h"
#include "openthread/platform/random.h"
#include <stdlib.h>
@@ -58,12 +59,12 @@ void emskRandomInit(void)
srand(seed);
}
uint32_t otPlatRandomGet(void)
static uint32_t randomUint32Get(void)
{
return (uint32_t)rand();
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
uint8_t channel = 0;
@@ -71,7 +72,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otEXPECT_ACTION(aOutput && aOutputLength, error = OT_ERROR_INVALID_ARGS);
// TODO: `otPlatRandomGet()` and `otPlatRandomGetTrue()` should include a pointer to the
// TODO: `otPlatEntropyGet()` should include a pointer to the
// owning OpenThread Instance as an input argument (similar to other platform APIs).
//
// The platform implementation requires to know the OpenThread instance to be able to
@@ -98,7 +99,7 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
for (uint16_t length = 0; length < aOutputLength; length++)
{
/* Get random number */
aOutput[length] = (uint8_t)otPlatRandomGet();
aOutput[length] = (uint8_t)randomUint32Get();
}
/* Enable radio*/
+1 -1
View File
@@ -41,11 +41,11 @@ libopenthread_gp712_a_CPPFLAGS = \
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
system.c \
uart-posix.c \
$(NULL)
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2016-2017, The OpenThread Authors.
* Copyright (c) 2016-2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,37 +28,37 @@
/**
* @file
* This file implements a pseudo-random number generator.
* This file implements an entropy source based on /dev/urandom or pseudo-random generator.
*
*/
#include <openthread/platform/entropy.h>
#include <assert.h>
#include <stdio.h>
#include <openthread/error.h>
#include <openthread/platform/random.h>
#include "utils/code_utils.h"
#if __SANITIZE_ADDRESS__ != 0
static uint32_t sState = 1;
#endif // __SANITIZE_ADDRESS__
void qorvoRandomInit(void)
{
#if __SANITIZE_ADDRESS__ == 0
otError error;
error = otPlatRandomGetTrue((uint8_t *)&sState, sizeof(sState));
assert(error == OT_ERROR_NONE);
#else // __SANITIZE_ADDRESS__
#if __SANITIZE_ADDRESS__ != 0
sState = (uint32_t)time(NULL);
#endif // __SANITIZE_ADDRESS__
}
uint32_t otPlatRandomGet(void)
#if __SANITIZE_ADDRESS__ != 0
static uint32_t randomUint32Get(void)
{
uint32_t mlcg, p, q;
uint64_t tmpstate;
@@ -80,7 +80,9 @@ uint32_t otPlatRandomGet(void)
return mlcg;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
#endif // __SANITIZE_ADDRESS__
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
@@ -118,7 +120,7 @@ exit:
for (uint16_t length = 0; length < aOutputLength; length++)
{
aOutput[length] = (uint8_t)otPlatRandomGet();
aOutput[length] = (uint8_t)randomUint32Get();
}
exit:
+1 -1
View File
@@ -51,11 +51,11 @@ libopenthread_kw41z_a_CPPFLAGS
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
system.c \
uart.c \
$(NULL)
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,11 +28,12 @@
/**
* @file
* This file implements a random number generator.
* This file implements an entropy source based on TRNG.
*
*/
#include "openthread/platform/random.h"
#include <openthread/platform/entropy.h>
#include "fsl_device_registers.h"
#include "fsl_trng.h"
#include <stdint.h>
@@ -60,12 +61,7 @@ exit:
return;
}
uint32_t otPlatRandomGet(void)
{
return (uint32_t)rand();
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError status = OT_ERROR_NONE;
+1 -1
View File
@@ -72,6 +72,7 @@ COMMONCPPFLAGS
PLATFORM_COMMON_SOURCES = \
alarm.c \
entropy.c \
fem.c \
flash.c \
logging.c \
@@ -80,7 +81,6 @@ PLATFORM_COMMON_SOURCES
platform-fem.h \
platform-nrf5.h \
radio.c \
random.c \
temp.c \
spi-slave.c \
system.c \
@@ -28,10 +28,12 @@
/**
* @file
* This file implements a random number generator.
* This file implements an entropy source based on TRNG.
*
*/
#include <openthread/platform/entropy.h>
#include <openthread-core-config.h>
#include <openthread/config.h>
@@ -40,7 +42,6 @@
#include <string.h>
#include <utils/code_utils.h>
#include <openthread/platform/random.h>
#include "platform-nrf5.h"
@@ -169,12 +170,7 @@ void nrf5RandomDeinit(void)
NVIC_SetPriority(RNG_IRQn, 0);
}
uint32_t otPlatRandomGet(void)
{
return (uint32_t)rand();
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
uint8_t copyLength;
@@ -235,7 +235,7 @@
*
*/
#ifndef RNG_BUFFER_SIZE
#define RNG_BUFFER_SIZE 64
#define RNG_BUFFER_SIZE 128
#endif
/**
+1 -1
View File
@@ -80,6 +80,7 @@ COMMONCPPFLAGS
PLATFORM_COMMON_SOURCES = \
alarm.c \
entropy.c \
fem.c \
flash.c \
logging.c \
@@ -88,7 +89,6 @@ PLATFORM_COMMON_SOURCES
platform-fem.h \
platform-nrf5.h \
radio.c \
random.c \
temp.c \
spi-slave.c \
system.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,10 +28,12 @@
/**
* @file
* This file implements a random number generator.
* This file implements an entropy source based on TRNG.
*
*/
#include <openthread/platform/entropy.h>
#include <openthread-core-config.h>
#include <openthread/config.h>
@@ -40,7 +42,6 @@
#include <string.h>
#include <utils/code_utils.h>
#include <openthread/platform/random.h>
#include "platform-nrf5.h"
@@ -186,12 +187,7 @@ void nrf5RandomDeinit(void)
#endif // SOFTDEVICE_PRESENT
}
uint32_t otPlatRandomGet(void)
{
return (uint32_t)rand();
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
uint8_t copyLength;
@@ -235,7 +235,7 @@
*
*/
#ifndef RNG_BUFFER_SIZE
#define RNG_BUFFER_SIZE 64
#define RNG_BUFFER_SIZE 128
#endif
/**
+1 -1
View File
@@ -40,10 +40,10 @@ libopenthread_posix_a_CPPFLAGS = \
PLATFORM_SOURCES = \
alarm.c \
diag.c \
entropy.c \
misc.c \
logging.c \
radio.c \
random.c \
uart-posix.c \
flash.c \
spi-stubs.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,31 +28,28 @@
/**
* @file
* This file implements a pseudo-random number generator.
* This file implements an entropy source based on /dev/urandom or pseudo-random generator.
*
*/
#include "platform-posix.h"
#include <assert.h>
#include <stdio.h>
#include "platform-posix.h"
#include <openthread/platform/random.h>
#include <openthread/platform/entropy.h>
#include "utils/code_utils.h"
#if __SANITIZE_ADDRESS__ != 0
static uint32_t sState = 1;
#endif // __SANITIZE_ADDRESS__
void platformRandomInit(void)
{
#if __SANITIZE_ADDRESS__ == 0
otError error;
error = otPlatRandomGetTrue((uint8_t *)&sState, sizeof(sState));
assert(error == OT_ERROR_NONE);
#else // __SANITIZE_ADDRESS__
#if __SANITIZE_ADDRESS__ != 0
// Multiplying gNodeId assures that no two nodes gets the same seed within an hour.
sState = (uint32_t)time(NULL) + (3600 * gNodeId);
@@ -60,7 +57,9 @@ void platformRandomInit(void)
#endif // __SANITIZE_ADDRESS__
}
uint32_t otPlatRandomGet(void)
#if __SANITIZE_ADDRESS__ != 0
static uint32_t randomUint32Get(void)
{
uint32_t mlcg, p, q;
uint64_t tmpstate;
@@ -82,7 +81,9 @@ uint32_t otPlatRandomGet(void)
return mlcg;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
#endif // __SANITIZE_ADDRESS__
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
@@ -120,7 +121,7 @@ exit:
for (uint16_t length = 0; length < aOutputLength; length++)
{
aOutput[length] = (uint8_t)otPlatRandomGet();
aOutput[length] = (uint8_t)randomUint32Get();
}
exit:
+2 -2
View File
@@ -31,11 +31,11 @@
#if OPENTHREAD_POSIX_VIRTUAL_TIME == 0
#include <openthread/dataset.h>
#include <openthread/random_noncrypto.h>
#include <openthread/platform/alarm-micro.h>
#include <openthread/platform/alarm-milli.h>
#include <openthread/platform/diag.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h>
#include <openthread/platform/time.h>
#include "utils/code_utils.h"
@@ -560,7 +560,7 @@ int8_t otPlatRadioGetRssi(otInstance *aInstance)
probabilityThreshold = (channel - POSIX_RADIO_CHANNEL_MIN) * POSIX_HIGH_RSSI_PROB_INC_PER_CHANNEL;
if ((otPlatRandomGet() & 0xffff) < (probabilityThreshold * 0xffff / 100))
if (otRandomNonCryptoGetUint16() < (probabilityThreshold * 0xffff / 100))
{
rssi = POSIX_HIGH_RSSI_SAMPLE;
}
+1 -1
View File
@@ -43,10 +43,10 @@ CLEANFILES =
libopenthread_qpg6095_a_SOURCES = \
alarm.c \
entropy.c \
logging.c \
misc.c \
platform.c \
random.c \
radio.c \
settings.cpp \
uart.c \
@@ -28,15 +28,16 @@
/**
* @file
* This file implements a random number generator.
* This file implements an entropy source.
*
*/
#include <openthread/platform/entropy.h>
#include "assert.h"
#include "random_qorvo.h"
#include <common/code_utils.hpp>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h>
#define GP_COMPONENT_ID GP_COMPONENT_ID_APP
@@ -47,14 +48,7 @@ void qorvoRandomInit(void)
// pseudoRandom += (uint8_t) (seed&0xFF);
}
uint32_t otPlatRandomGet(void)
{
uint32_t random = 0;
otPlatRandomGetTrue((uint8_t *)(&random), sizeof(uint32_t));
return random;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
assert(aOutputLength < 256);
+2 -2
View File
@@ -89,13 +89,13 @@ libopenthread_samr21_a_CPPFLAGS
PLATFORM_SOURCES = \
crypto/aes_alt.c \
alarm.c \
diag.c \
cxx_helpers.c \
diag.c \
entropy.c \
flash.c \
logging.c \
misc.c \
radio.c \
random.c \
system.c \
uart.c \
$(NULL)
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,21 +28,17 @@
/**
* @file
* This file implements the OpenThread platform abstraction for random number generator.
* This file implements an entropy source based on TRNG.
*
*/
#include <openthread/platform/entropy.h>
#include "phy.h"
#include "platform-samr21.h"
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h>
uint32_t otPlatRandomGet(void)
{
return samr21RadioRandomGet();
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
samr21RadioRandomGetTrue(aOutput, aOutputLength);
+3
View File
@@ -62,6 +62,7 @@ openthread_headers = \
dataset_ftd.h \
diag.h \
dns.h \
entropy.h \
error.h \
icmp6.h \
instance.h \
@@ -75,6 +76,8 @@ openthread_headers = \
ncp.h \
netdata.h \
network_time.h \
random_crypto.h \
random_noncrypto.h \
server.h \
sntp.h \
tasklet.h \
+74
View File
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief
* This file defines the OpenThread entropy source API.
*/
#ifndef OPENTHREAD_ENTROPY_H_
#define OPENTHREAD_ENTROPY_H_
#include "openthread-core-config.h"
#include "utils/wrap_stdint.h"
#include <mbedtls/entropy.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup api-entropy
*
* @brief
* This module includes functions that manages entropy source.
*
* @{
*
*/
/**
* This function returns initialized mbedtls_entropy_context.
*
* @returns A pointer to initialized mbedtls_entropy_context.
*/
mbedtls_entropy_context *otEntropyMbedTlsContextGet(void);
/**
* @}
*
*/
#ifdef __cplusplus
} // extern "C"
#endif
#endif // OPENTHREAD_ENTROPY_H_
+1 -1
View File
@@ -33,11 +33,11 @@ ot_platform_headers = \
alarm-milli.h \
ble.h \
diag.h \
entropy.h \
memory.h \
misc.h \
logging.h \
radio.h \
random.h \
time.h \
uart.h \
udp.h \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -29,11 +29,11 @@
/**
* @file
* @brief
* This file includes the platform abstraction for random number generation.
* This file includes the platform abstraction for entropy generation.
*/
#ifndef OPENTHREAD_PLATFORM_RANDOM_H_
#define OPENTHREAD_PLATFORM_RANDOM_H_
#ifndef OPENTHREAD_PLATFORM_ENTROPY_H_
#define OPENTHREAD_PLATFORM_ENTROPY_H_
#include <stdint.h>
@@ -44,27 +44,17 @@ extern "C" {
#endif
/**
* @addtogroup plat-random
* @addtogroup plat-entropy
*
* @brief
* This module includes the platform abstraction for random number generation.
* This module includes the platform abstraction for entropy generation.
*
* @{
*
*/
/**
* Get a 32-bit random value.
*
* This function may be implemented using a pseudo-random number generator.
*
* @returns A 32-bit random value.
*
*/
uint32_t otPlatRandomGet(void);
/**
* Get true random value sequence.
* Fill buffer with entropy.
*
* This function MUST be implemented using a true random number generator (TRNG).
*
@@ -72,11 +62,11 @@ uint32_t otPlatRandomGet(void);
* @param[in] aOutputLength Size of @p aBuffer.
*
* @retval OT_ERROR_NONE Successfully filled @p aBuffer with true random values.
* @retval OT_ERROR_FAILED Failed to fill @p aBuffer with true random values.
* @retval OT_ERROR_FAILED Failed to fill @p aBuffer with true random values.
* @retval OT_ERROR_INVALID_ARGS @p aBuffer was set to NULL.
*
*/
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength);
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength);
/**
* @}
@@ -87,4 +77,4 @@ otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength);
} // end of extern "C"
#endif
#endif // OPENTHREAD_PLATFORM_RANDOM_H_
#endif // OPENTHREAD_PLATFORM_ENTROPY_H_
+84
View File
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief
* This file defines the OpenThread cryptographic random number generator API.
*/
#ifndef OPENTHREAD_RANDOM_CRYPTO_H_
#define OPENTHREAD_RANDOM_CRYPTO_H_
#include "openthread-core-config.h"
#include "utils/wrap_stdint.h"
#include <mbedtls/ctr_drbg.h>
#include <openthread/error.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup api-random
*
* @brief
* This module includes functions that generates cryptographic random numbers.
*
* @{
*
*/
/**
* This function fills a given buffer with cryptographically secure random bytes.
*
* @param[out] aBuffer A pointer to a buffer to fill with the random bytes.
* @param[in] aSize Size of buffer (number of bytes to fill).
*
*/
otError otRandomCryptoFillBuffer(uint8_t *aBuffer, uint16_t aSize);
/**
* This function returns initialized mbedtls_ctr_drbg_context.
*
* @returns A pointer to initialized mbedtls_ctr_drbg_context.
*/
mbedtls_ctr_drbg_context *otRandomCryptoMbedTlsContextGet(void);
/**
* @}
*
*/
#ifdef __cplusplus
} // extern "C"
#endif
#endif // OPENTHREAD_RANDOM_CRYPTO_H_
+144
View File
@@ -0,0 +1,144 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief
* This file defines the OpenThread non cryptographic random number generator API.
*/
#ifndef OPENTHREAD_RANDOM_H_
#define OPENTHREAD_RANDOM_H_
#include "openthread-core-config.h"
#include "utils/wrap_stdint.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup api-random
*
* @brief
* This module includes functions that generates non cryptographic random numbers.
*
* @{
*
*/
/**
* This function generates and returns a random `uint32_t` value.
*
* @returns A random `uint32_t` value.
*
*/
uint32_t otRandomNonCryptoGetUint32(void);
/**
* This function generates and returns a random byte.
*
* @returns A random `uint8_t` value.
*
*/
uint8_t otRandomNonCryptoGetUint8(void);
/**
* This function generates and returns a random `uint16_t` value.
*
* @returns A random `uint16_t` value.
*
*/
uint16_t otRandomNonCryptoGetUint16(void);
/**
* This function generates and returns a random `uint8_t` value within a given range `[aMin, aMax)`.
*
* @param[in] aMin A minimum value (this value can be included in returned random result).
* @param[in] aMax A maximum value (this value is excluded from returned random result).
*
* @returns A random `uint8_t` value in the given range (i.e., aMin <= random value < aMax).
*/
uint8_t otRandomNonCryptoGetUint8InRange(uint8_t aMin, uint8_t aMax);
/**
* This function generates and returns a random `uint16_t` value within a given range `[aMin, aMax)`.
*
* @note The returned random value can include the @p aMin value but excludes the @p aMax.
*
* @param[in] aMin A minimum value (this value can be included in returned random result).
* @param[in] aMax A maximum value (this value is excluded from returned random result).
*
* @returns A random `uint16_t` value in the given range (i.e., aMin <= random value < aMax).
*/
uint16_t otRandomNonCryptoGetUint16InRange(uint16_t aMin, uint16_t aMax);
/**
* This function generates and returns a random `uint32_t` value within a given range `[aMin, aMax)`.
*
* @note The returned random value can include the @p aMin value but excludes the @p aMax.
*
* @param[in] aMin A minimum value (this value can be included in returned random result).
* @param[in] aMax A maximum value (this value is excluded from returned random result).
*
* @returns A random `uint32_t` value in the given range (i.e., aMin <= random value < aMax).
*
*/
uint32_t otRandomNonCryptoGetUint32InRange(uint32_t aMin, uint32_t aMax);
/**
* This function fills a given buffer with random bytes.
*
* @param[out] aBuffer A pointer to a buffer to fill with the random bytes.
* @param[in] aSize Size of buffer (number of bytes to fill).
*
*/
void otRandomNonCryptoFillBuffer(uint8_t *aBuffer, uint16_t aSize);
/**
* This function adds a random jitter within a given range to a given value.
*
* @param[in] aValue A value to which the random jitter is added.
* @param[in] aJitter Maximum jitter. Random jitter is selected from the range `[-aJitter, aJitter]`.
*
* @returns The given value with an added random jitter.
*
*/
uint32_t otRandomNonCryptoAddJitter(uint32_t aValue, uint16_t aJitter);
/**
* @}
*
*/
#ifdef __cplusplus
} // extern "C"
#endif
#endif // OPENTHREAD_RANDOM_H_
+1 -6
View File
@@ -248,12 +248,7 @@ const struct Command Interpreter::sCommands[] = {
{"version", &Interpreter::ProcessVersion},
};
#ifdef OTDLL
uint32_t otPlatRandomGet(void)
{
return (uint32_t)rand();
}
#else
#ifndef OTDLL
void otFreeMemory(const void *)
{
// No-op on systems running OpenThread in-proc
+13
View File
@@ -113,6 +113,7 @@ SOURCES_COMMON = \
api/dataset_api.cpp \
api/dataset_ftd_api.cpp \
api/dns_api.cpp \
api/entropy_api.cpp \
api/icmp6_api.cpp \
api/instance_api.cpp \
api/ip6_api.cpp \
@@ -124,6 +125,8 @@ SOURCES_COMMON = \
api/message_api.cpp \
api/netdata_api.cpp \
api/network_time_api.cpp \
api/random_crypto_api.cpp \
api/random_noncrypto_api.cpp \
api/server_api.cpp \
api/sntp_api.cpp \
api/tasklet_api.cpp \
@@ -134,10 +137,14 @@ SOURCES_COMMON = \
coap/coap_message.cpp \
coap/coap_secure.cpp \
common/crc16.cpp \
common/entropy.cpp \
common/instance.cpp \
common/logging.cpp \
common/message.cpp \
common/notifier.cpp \
common/random_crypto.cpp \
common/random_manager.cpp \
common/random_noncrypto.cpp \
common/settings.cpp \
common/string.cpp \
common/tasklet.cpp \
@@ -234,10 +241,14 @@ libopenthread_radio_a_SOURCES = \
api/link_raw_api.cpp \
api/logging_api.cpp \
api/message_api.cpp \
api/random_noncrypto_api.cpp \
api/tasklet_api.cpp \
common/entropy.cpp \
common/instance.cpp \
common/logging.cpp \
common/message.cpp \
common/random_manager.cpp \
common/random_noncrypto.cpp \
common/string.cpp \
common/tasklet.cpp \
common/timer.cpp \
@@ -294,6 +305,7 @@ HEADERS_COMMON = \
common/crc16.hpp \
common/debug.hpp \
common/encoding.hpp \
common/entropy.hpp \
common/extension.hpp \
common/instance.hpp \
common/locator.hpp \
@@ -303,6 +315,7 @@ HEADERS_COMMON = \
common/new.hpp \
common/notifier.hpp \
common/random.hpp \
common/random_manager.hpp \
common/settings.hpp \
common/string.hpp \
common/tasklet.hpp \
+45
View File
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements the OpenThread entropy source management API.
*/
#include "openthread/entropy.h"
#include <mbedtls/entropy.h>
#include "common/entropy.hpp"
using namespace ot;
mbedtls_entropy_context *otEntropyMbedTlsContextGet(void)
{
return Entropy::MbedTlsContextGet();
}
+50
View File
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements the OpenThread cryptographic random number generator API.
*/
#include "openthread/random_crypto.h"
#include <mbedtls/ctr_drbg.h>
#include "common/random.hpp"
using namespace ot;
otError otRandomCryptoFillBuffer(uint8_t *aBuffer, uint16_t aSize)
{
return Random::Crypto::FillBuffer(aBuffer, aSize);
}
mbedtls_ctr_drbg_context *otRandomCryptoMbedTlsContextGet(void)
{
return Random::Crypto::MbedTlsContextGet();
}
+78
View File
@@ -0,0 +1,78 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements the OpenThread software random number generator API.
*/
#include "openthread/random_noncrypto.h"
#include "common/random.hpp"
using namespace ot;
uint32_t otRandomNonCryptoGetUint32(void)
{
return Random::NonCrypto::GetUint32();
}
uint8_t otRandomNonCryptoGetUint8(void)
{
return Random::NonCrypto::GetUint8();
}
uint16_t otRandomNonCryptoGetUint16(void)
{
return Random::NonCrypto::GetUint16();
}
uint8_t otRandomNonCryptoGetUint8InRange(uint8_t aMin, uint8_t aMax)
{
return Random::NonCrypto::GetUint8InRange(aMin, aMax);
}
uint16_t otRandomNonCryptoGetUint16InRange(uint16_t aMin, uint16_t aMax)
{
return Random::NonCrypto::GetUint16InRange(aMin, aMax);
}
uint32_t otRandomNonCryptoGetUint32InRange(uint32_t aMin, uint32_t aMax)
{
return Random::NonCrypto::GetUint32InRange(aMin, aMax);
}
void otRandomNonCryptoFillBuffer(uint8_t *aBuffer, uint16_t aSize)
{
Random::NonCrypto::FillBuffer(aBuffer, aSize);
}
uint32_t otRandomNonCryptoAddJitter(uint32_t aValue, uint16_t aJitter)
{
return Random::NonCrypto::AddJitter(aValue, aJitter);
}
+2 -2
View File
@@ -59,7 +59,7 @@ CoapBase::CoapBase(Instance &aInstance, Sender aSender)
, mDefaultHandlerContext(NULL)
, mSender(aSender)
{
mMessageId = Random::GetUint16();
mMessageId = Random::NonCrypto::GetUint16();
}
void CoapBase::ClearRequestsAndResponses(void)
@@ -676,7 +676,7 @@ CoapMetadata::CoapMetadata(bool aConfirmable,
mResponseContext = aContext;
mRetransmissionCount = 0;
mRetransmissionTimeout = TimerMilli::SecToMsec(kAckTimeout);
mRetransmissionTimeout += Random::GetUint32InRange(
mRetransmissionTimeout += Random::NonCrypto::GetUint32InRange(
0, TimerMilli::SecToMsec(kAckTimeout) * kAckRandomFactorNumerator / kAckRandomFactorDenominator -
TimerMilli::SecToMsec(kAckTimeout) + 1);
+1 -1
View File
@@ -355,7 +355,7 @@ void Message::SetToken(uint8_t aTokenLength)
assert(aTokenLength <= sizeof(token));
Random::FillBuffer(token, aTokenLength);
Random::NonCrypto::FillBuffer(token, aTokenLength);
SetToken(token, aTokenLength);
}
+131
View File
@@ -0,0 +1,131 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file provides an implementation of entropy source.
*/
#include "entropy.hpp"
#include <openthread/platform/entropy.h>
#include <openthread/platform/toolchain.h>
#include "code_utils.hpp"
#include "debug.hpp"
#ifndef OPENTHREAD_RADIO
#include <mbedtls/entropy.h>
#include <mbedtls/entropy_poll.h>
#endif // OPENTHREAD_RADIO
namespace ot {
namespace Entropy {
static uint32_t sInitCnt = 0;
#ifndef OPENTHREAD_RADIO
static mbedtls_entropy_context sEntropy;
static int HandleMbedtlsEntropyPoll(void *aData, unsigned char *aOutput, size_t aInLen, size_t *aOutLen)
{
OT_UNUSED_VARIABLE(aData);
otError error;
int rval = 0;
error = otPlatEntropyGet(reinterpret_cast<uint8_t *>(aOutput), static_cast<uint16_t>(aInLen));
SuccessOrExit(error);
if (aOutLen != NULL)
{
*aOutLen = aInLen;
}
exit:
if (error != OT_ERROR_NONE)
{
rval = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
return rval;
}
#endif // OPENTHREAD_RADIO
void Init(void)
{
assert(sInitCnt < 0xffffffff);
#ifndef OPENTHREAD_RADIO
if (sInitCnt == 0)
{
mbedtls_entropy_init(&sEntropy);
mbedtls_entropy_add_source(&sEntropy, &HandleMbedtlsEntropyPoll, NULL, MBEDTLS_ENTROPY_MIN_HARDWARE,
MBEDTLS_ENTROPY_SOURCE_STRONG);
}
#endif // OPENTHREAD_RADIO
sInitCnt++;
}
void Deinit(void)
{
assert(sInitCnt > 0);
sInitCnt--;
#ifndef OPENTHREAD_RADIO
if (sInitCnt == 0)
{
mbedtls_entropy_free(&sEntropy);
}
#endif // OPENTHREAD_RADIO
}
#ifndef OPENTHREAD_RADIO
mbedtls_entropy_context *MbedTlsContextGet(void)
{
assert(sInitCnt > 0);
return &sEntropy;
}
#endif // OPENTHREAD_RADIO
otError GetUint32(uint32_t &aVal)
{
assert(sInitCnt > 0);
return otPlatEntropyGet(reinterpret_cast<uint8_t *>(&aVal), sizeof(aVal));
}
} // namespace Entropy
} // namespace ot
+88
View File
@@ -0,0 +1,88 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes definitions for OpenThread entropy generation.
*/
#ifndef ENTROPY_HPP_
#define ENTROPY_HPP_
#include "openthread-core-config.h"
#include "utils/wrap_stdint.h"
#include <openthread/error.h>
#ifndef OPENTHREAD_RADIO
#include <mbedtls/entropy.h>
#endif // OPENTHREAD_RADIO
namespace ot {
namespace Entropy {
/**
* This function initializes entropy source.
*
*/
void Init(void);
/**
* This function deinitializes entropy source.
*
*/
void Deinit(void);
#ifndef OPENTHREAD_RADIO
/**
* This function returns initialized mbedtls_entropy_context.
*
* @returns A pointer to initialized mbedtls_entropy_context.
*/
mbedtls_entropy_context *MbedTlsContextGet(void);
#endif // OPENTHREAD_RADIO
/**
* This function generates and returns a 32 bit entropy.
*
* @param aVal[out] A generated 32 bit entropy value.
*
* @retval OT_ERROR_NONE Successfully generated 32 bit entropy.
*
*/
otError GetUint32(uint32_t &aVal);
} // namespace Entropy
} // namespace ot
#endif // ENTROPY_HPP_
+10
View File
@@ -190,6 +190,16 @@ void Instance::Finalize(void)
IgnoreReturnValue(otLinkSetEnabled(this, false));
#endif
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
/**
* Object was created on buffer, so instead of deleting
* the object we call destructor explicitly.
*/
this->~Instance();
#endif // !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
exit:
return;
}
+10 -4
View File
@@ -42,6 +42,8 @@
#include <openthread/error.h>
#include <openthread/platform/logging.h>
#include "common/random_manager.hpp"
#if OPENTHREAD_RADIO || OPENTHREAD_ENABLE_RAW_LINK_API
#include "common/message.hpp"
#include "mac/link_raw.hpp"
@@ -49,8 +51,8 @@
#if OPENTHREAD_FTD || OPENTHREAD_MTD
#include "coap/coap.hpp"
#include "common/code_utils.hpp"
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
#include "crypto/mbedtls.hpp"
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
#include "utils/heap.hpp"
#endif
#include "common/notifier.hpp"
@@ -311,10 +313,14 @@ private:
Notifier mNotifier;
Settings mSettings;
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
#if OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
Crypto::MbedTls mMbedTls;
#endif
#endif // OPENTHREAD_MTD || OPENTHREAD_FTD
RandomManager mRandomManager;
#if OPENTHREAD_MTD || OPENTHREAD_FTD
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
Utils::Heap mHeap;
#endif
+59 -23
View File
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -38,22 +38,25 @@
#include "utils/wrap_stdint.h"
#include <openthread/platform/random.h>
#include <openthread/error.h>
#ifndef OPENTHREAD_RADIO
#include <mbedtls/ctr_drbg.h>
#endif // OPENTHREAD_RADIO
namespace ot {
namespace Random {
namespace NonCrypto {
/**
* @addtogroup core-random
* This function generates and returns a random `uint32_t` value.
*
* @brief
* This module includes definitions for OpenThread random number generation.
*
* The functions in this header file uses the platform random number generator `otPlatRandomGet()`.
*
* @{
* @returns A random `uint32_t` value.
*
*/
uint32_t GetUint32(void);
/**
* This function generates and returns a random byte.
@@ -63,7 +66,7 @@ namespace Random {
*/
inline uint8_t GetUint8(void)
{
return static_cast<uint8_t>(otPlatRandomGet() & 0xff);
return static_cast<uint8_t>(GetUint32() & 0xff);
}
/**
@@ -74,18 +77,7 @@ inline uint8_t GetUint8(void)
*/
inline uint16_t GetUint16(void)
{
return static_cast<uint16_t>(otPlatRandomGet() & 0xffff);
}
/**
* This function generates and returns a random `uint32_t` value.
*
* @returns A random `uint32_t` value.
*
*/
inline uint32_t GetUint32(void)
{
return otPlatRandomGet();
return static_cast<uint16_t>(GetUint32() & 0xffff);
}
/**
@@ -164,9 +156,53 @@ inline uint32_t AddJitter(uint32_t aValue, uint16_t aJitter)
}
/**
* @}
* This function seeds a software random generator.
*
* @param[in] aSeed Seed value.
*
*/
void Seed(uint32_t aSeed);
} // namespace NonCrypto
#ifndef OPENTHREAD_RADIO
namespace Crypto {
/**
* This function initializes cryptographic random number generator.
*
*/
void Init(void);
/**
* This function deinitializes cryptographic random number generator.
*
*/
void Deinit(void);
/**
* This function fills a given buffer with cryptographically secure random bytes.
*
* @param[out] aBuffer A pointer to a buffer to fill with the random bytes.
* @param[in] aSize Size of buffer (number of bytes to fill).
*
* @retval OT_ERROR_NONE Successfully filled buffer with random values.
*
*/
otError FillBuffer(uint8_t *aBuffer, uint16_t aSize);
/**
* This function returns initialized mbedtls_ctr_drbg_context.
*
* @returns A pointer to initialized mbedtls_ctr_drbg_context.
*
*/
mbedtls_ctr_drbg_context *MbedTlsContextGet(void);
} // namespace Crypto
#endif // OPENTHREAD_RADIO
} // namespace Random
} // namespace ot
+96
View File
@@ -0,0 +1,96 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file provides an implementation of cryptographic random number generator.
*/
#include "random.hpp"
#include "utils/wrap_stdint.h"
#include "entropy.hpp"
#include "crypto/mbedtls.hpp"
#include <mbedtls/entropy.h>
#include "debug.hpp"
namespace ot {
namespace Random {
namespace Crypto {
static uint32_t sInitCnt = 0;
static mbedtls_ctr_drbg_context sCtrDrbg;
void Init(void)
{
assert(sInitCnt < 0xffffffff);
if (sInitCnt == 0)
{
mbedtls_ctr_drbg_init(&sCtrDrbg);
mbedtls_ctr_drbg_seed(&sCtrDrbg, mbedtls_entropy_func, Entropy::MbedTlsContextGet(), NULL, 0);
}
sInitCnt++;
}
void Deinit(void)
{
assert(sInitCnt > 0);
sInitCnt--;
if (sInitCnt == 0)
{
mbedtls_ctr_drbg_free(&sCtrDrbg);
}
}
mbedtls_ctr_drbg_context *MbedTlsContextGet(void)
{
assert(sInitCnt > 0);
return &sCtrDrbg;
}
otError FillBuffer(uint8_t *aBuffer, uint16_t aSize)
{
int rval = 0;
assert(sInitCnt > 0);
rval = mbedtls_ctr_drbg_random(&sCtrDrbg, static_cast<unsigned char *>(aBuffer), static_cast<size_t>(aSize));
return ot::Crypto::MbedTls::MapError(rval);
}
} // namespace Crypto
} // namespace Random
} // namespace ot
+69
View File
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file provides an implementation of OpenThread random number generation manager class.
*/
#include "random_manager.hpp"
#include <openthread/error.h>
#include "debug.hpp"
#include "entropy.hpp"
#include "random.hpp"
namespace ot {
RandomManager::RandomManager(void)
{
uint32_t seed;
otError error;
Entropy::Init();
error = Entropy::GetUint32(seed);
assert(error == OT_ERROR_NONE);
Random::NonCrypto::Seed(seed);
#ifndef OPENTHREAD_RADIO
Random::Crypto::Init();
#endif
}
RandomManager::~RandomManager(void)
{
#ifndef OPENTHREAD_RADIO
Random::Crypto::Deinit();
#endif
Entropy::Deinit();
}
} // namespace ot
+61
View File
@@ -0,0 +1,61 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes definitions for OpenThread random number generation manager class.
*/
#ifndef RANDOM_MANAGER_HPP_
#define RANDOM_MANAGER_HPP_
namespace ot {
/**
* This class manages random number generator initialization/deinitialization.
*
*/
class RandomManager
{
public:
/**
* This constructor initializes the object.
*
*/
RandomManager(void);
/**
* This destructor deinitializes the object.
*
*/
~RandomManager(void);
};
} // namespace ot
#endif // RANDOM_MANAGER_HPP_
+78
View File
@@ -0,0 +1,78 @@
/*
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file provides an implementation of software random number generator.
*/
#include "random.hpp"
#include "debug.hpp"
#include "entropy.hpp"
namespace ot {
namespace Random {
namespace NonCrypto {
static uint32_t sState;
static bool sSeeded;
uint32_t GetUint32(void)
{
uint32_t mlcg, p, q;
uint64_t tmpstate;
assert(sSeeded);
tmpstate = (uint64_t)33614 * (uint64_t)sState;
q = tmpstate & 0xffffffff;
q = q >> 1;
p = tmpstate >> 32;
mlcg = p + q;
if (mlcg & 0x80000000)
{
mlcg &= 0x7fffffff;
mlcg++;
}
sState = mlcg;
return mlcg;
}
void Seed(uint32_t aSeed)
{
sSeeded = true;
sState = aSeed;
}
} // namespace NonCrypto
} // namespace Random
} // namespace ot
+4 -4
View File
@@ -77,7 +77,7 @@ otError TrickleTimer::Start(uint32_t aIntervalMin, uint32_t aIntervalMax, Mode a
mIsRunning = true;
// Select interval randomly from range [Imin, Imax].
mInterval = Random::GetUint32InRange(mIntervalMin, mIntervalMax + 1);
mInterval = Random::NonCrypto::GetUint32InRange(mIntervalMin, mIntervalMax + 1);
StartNewInterval();
@@ -121,7 +121,7 @@ void TrickleTimer::StartNewInterval(void)
VerifyOrExit(halfInterval < mInterval, mTimeInInterval = halfInterval);
// Select a random point in the interval taken from the range [I/2, I).
mTimeInInterval = Random::GetUint32InRange(halfInterval, mInterval);
mTimeInInterval = Random::NonCrypto::GetUint32InRange(halfInterval, mInterval);
break;
case kModePlainTimer:
@@ -130,7 +130,7 @@ void TrickleTimer::StartNewInterval(void)
case kModeMPL:
// Select a random point in interval taken from the range [0, I].
mTimeInInterval = Random::GetUint32InRange(0, mInterval + 1);
mTimeInInterval = Random::NonCrypto::GetUint32InRange(0, mInterval + 1);
break;
}
@@ -171,7 +171,7 @@ void TrickleTimer::HandleEndOfTimeInInterval(void)
{
case kModePlainTimer:
// Select a random interval in [Imin, Imax] and restart.
mInterval = Random::GetUint32InRange(mIntervalMin, mIntervalMax + 1);
mInterval = Random::NonCrypto::GetUint32InRange(mIntervalMin, mIntervalMax + 1);
StartNewInterval();
break;
+3 -9
View File
@@ -33,6 +33,7 @@
#include "ecdsa.hpp"
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/ecdsa.h>
#include <mbedtls/pk.h>
@@ -75,8 +76,8 @@ otError Ecdsa::Sign(uint8_t * aOutput,
VerifyOrExit(mbedtls_ecdsa_from_keypair(&ctx, keypair) == 0, error = OT_ERROR_FAILED);
// Sign using ECDSA.
VerifyOrExit(mbedtls_ecdsa_sign(&ctx.grp, &rMpi, &sMpi, &ctx.d, aInputHash, aInputHashLength, FillRandom, NULL) ==
0,
VerifyOrExit(mbedtls_ecdsa_sign(&ctx.grp, &rMpi, &sMpi, &ctx.d, aInputHash, aInputHashLength,
mbedtls_ctr_drbg_random, Random::Crypto::MbedTlsContextGet()) == 0,
error = OT_ERROR_FAILED);
VerifyOrExit(mbedtls_mpi_size(&rMpi) + mbedtls_mpi_size(&sMpi) <= *aOutputLength, error = OT_ERROR_NO_BUFS);
@@ -97,13 +98,6 @@ exit:
return error;
}
int Ecdsa::FillRandom(void *, unsigned char *aBuffer, size_t aSize)
{
Random::FillBuffer(aBuffer, static_cast<uint16_t>(aSize));
return 0;
}
#endif // OPENTHREAD_ENABLE_ECDSA
} // namespace Crypto
-3
View File
@@ -79,9 +79,6 @@ public:
uint16_t aInputHashLength,
const uint8_t *aPrivateKey,
uint16_t aPrivateKeyLength);
private:
static int FillRandom(void *, unsigned char *aBuffer, size_t aSize);
};
/**
+90 -4
View File
@@ -34,15 +34,20 @@
#include "mbedtls.hpp"
#include <mbedtls/debug.h>
#include <mbedtls/error.h>
#include <mbedtls/platform.h>
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#include <mbedtls/pem.h>
#endif
#include "common/instance.hpp"
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES && OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
namespace ot {
namespace Crypto {
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES && OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
static void *CAlloc(size_t aCount, size_t aSize)
{
return Instance::Get().GetHeap().CAlloc(aCount, aSize);
@@ -53,16 +58,97 @@ static void Free(void *aPointer)
Instance::Get().GetHeap().Free(aPointer);
}
#endif // !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES && OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
MbedTls::MbedTls(void)
{
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES && OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
#ifdef MBEDTLS_DEBUG_C
// mbedTLS's debug level is almost the same as OpenThread's
mbedtls_debug_set_threshold(OPENTHREAD_CONFIG_LOG_LEVEL);
#endif
mbedtls_platform_set_calloc_free(CAlloc, Free);
#endif // !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES && OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
}
otError MbedTls::MapError(int rval)
{
otError error = OT_ERROR_NONE;
switch (rval)
{
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_PK_TYPE_MISMATCH:
case MBEDTLS_ERR_PK_FILE_IO_ERROR:
case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
case MBEDTLS_ERR_PK_INVALID_PUBKEY:
case MBEDTLS_ERR_PK_INVALID_ALG:
case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
case MBEDTLS_ERR_X509_SIG_MISMATCH:
case MBEDTLS_ERR_X509_BAD_INPUT_DATA:
case MBEDTLS_ERR_X509_FILE_IO_ERROR:
case MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT:
case MBEDTLS_ERR_X509_INVALID_VERSION:
case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG:
case MBEDTLS_ERR_X509_INVALID_SERIAL:
case MBEDTLS_ERR_X509_UNKNOWN_OID:
case MBEDTLS_ERR_X509_INVALID_FORMAT:
case MBEDTLS_ERR_X509_INVALID_ALG:
case MBEDTLS_ERR_X509_INVALID_NAME:
case MBEDTLS_ERR_X509_INVALID_DATE:
case MBEDTLS_ERR_X509_INVALID_SIGNATURE:
case MBEDTLS_ERR_X509_INVALID_EXTENSIONS:
case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_SSL_BAD_INPUT_DATA:
error = OT_ERROR_INVALID_ARGS;
break;
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_PEM_ALLOC_FAILED:
case MBEDTLS_ERR_PK_ALLOC_FAILED:
case MBEDTLS_ERR_X509_BUFFER_TOO_SMALL:
case MBEDTLS_ERR_X509_ALLOC_FAILED:
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_SSL_ALLOC_FAILED:
case MBEDTLS_ERR_SSL_WANT_WRITE:
error = OT_ERROR_NO_BUFS;
break;
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
case MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE:
case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
case MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED:
error = OT_ERROR_SECURITY;
break;
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_X509_FATAL_ERROR:
error = OT_ERROR_FAILED;
break;
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_SSL_TIMEOUT:
case MBEDTLS_ERR_SSL_WANT_READ:
error = OT_ERROR_BUSY;
break;
default:
assert(rval >= 0);
break;
}
return error;
}
} // namespace Crypto
} // namespace ot
#endif // !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES && OPENTHREAD_CONFIG_ENABLE_BUILTIN_MBEDTLS
+5 -4
View File
@@ -38,8 +38,6 @@
#include <openthread/instance.h>
#if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
namespace ot {
namespace Crypto {
@@ -62,6 +60,11 @@ public:
*
*/
MbedTls(void);
/**
* This method converts from MbedTls error to OpenThread error.
*/
static otError MapError(int rval);
};
/**
@@ -72,6 +75,4 @@ public:
} // namespace Crypto
} // namespace ot
#endif // #if !OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
#endif // OT_MBEDTLS_HPP_
+1 -1
View File
@@ -82,7 +82,7 @@ uint8_t ChannelMask::ChooseRandomChannel(void) const
VerifyOrExit(!IsEmpty());
randomIndex = Random::GetUint8InRange(0, GetNumberOfChannels());
randomIndex = Random::NonCrypto::GetUint8InRange(0, GetNumberOfChannels());
SuccessOrExit(GetNextChannel(channel));
+3 -3
View File
@@ -84,8 +84,8 @@ Mac::Mac(Instance &aInstance)
, mDelayingSleep(false)
#endif
, mOperation(kOperationIdle)
, mBeaconSequence(Random::GetUint8())
, mDataSequence(Random::GetUint8())
, mBeaconSequence(Random::NonCrypto::GetUint8())
, mDataSequence(Random::NonCrypto::GetUint8())
, mBroadcastTransmitCount(0)
, mPanId(kPanIdBroadcast)
, mPanChannel(OPENTHREAD_CONFIG_DEFAULT_CHANNEL)
@@ -398,7 +398,7 @@ otError Mac::AcquireRadioChannel(uint16_t *aAcquisitionId)
VerifyOrExit(aAcquisitionId != NULL, error = OT_ERROR_INVALID_ARGS);
VerifyOrExit(!mRadioChannelAcquisitionId, error = OT_ERROR_INVALID_STATE);
mRadioChannelAcquisitionId = Random::GetUint16InRange(1, kMaxAcquisitionId);
mRadioChannelAcquisitionId = Random::NonCrypto::GetUint16InRange(1, kMaxAcquisitionId);
*aAcquisitionId = mRadioChannelAcquisitionId;
+1 -1
View File
@@ -46,7 +46,7 @@ namespace Mac {
void ExtAddress::GenerateRandom(void)
{
Random::FillBuffer(m8, sizeof(ExtAddress));
Random::NonCrypto::FillBuffer(m8, sizeof(ExtAddress));
SetGroup(false);
SetLocal(true);
}
+1 -1
View File
@@ -246,7 +246,7 @@ void SubMac::StartCsmaBackoff(void)
backoffExponent = kMaxBE;
}
backoff = Random::GetUint32InRange(0, static_cast<uint32_t>(1UL << backoffExponent));
backoff = Random::NonCrypto::GetUint32InRange(0, static_cast<uint32_t>(1UL << backoffExponent));
backoff *= (static_cast<uint32_t>(kUnitBackoffPeriod) * OT_RADIO_SYMBOL_TIME);
if (mRxOnWhenBackoff)
@@ -35,8 +35,6 @@
#include "announce_begin_client.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
-2
View File
@@ -38,8 +38,6 @@
#include <stdio.h>
#include "utils/wrap_string.h"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/encoding.hpp"
#include "common/instance.hpp"
+8 -7
View File
@@ -38,7 +38,6 @@
#include <stdio.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
@@ -46,6 +45,7 @@
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "common/random.hpp"
#include "common/timer.hpp"
#include "meshcop/dataset.hpp"
#include "meshcop/dataset_manager.hpp"
@@ -325,12 +325,12 @@ otError ActiveDataset::CreateNewNetwork(otOperationalDataset &aDataset)
aDataset.mActiveTimestamp = 1;
SuccessOrExit(error = otPlatRandomGetTrue(aDataset.mMasterKey.m8, sizeof(aDataset.mMasterKey)));
SuccessOrExit(error = otPlatRandomGetTrue(aDataset.mPSKc.m8, sizeof(aDataset.mPSKc)));
SuccessOrExit(error = otPlatRandomGetTrue(aDataset.mExtendedPanId.m8, sizeof(aDataset.mExtendedPanId)));
SuccessOrExit(error = Random::Crypto::FillBuffer(aDataset.mMasterKey.m8, sizeof(aDataset.mMasterKey)));
SuccessOrExit(error = Random::Crypto::FillBuffer(aDataset.mPSKc.m8, sizeof(aDataset.mPSKc)));
SuccessOrExit(error = Random::Crypto::FillBuffer(aDataset.mExtendedPanId.m8, sizeof(aDataset.mExtendedPanId)));
aDataset.mMeshLocalPrefix.m8[0] = 0xfd;
SuccessOrExit(error = otPlatRandomGetTrue(&aDataset.mMeshLocalPrefix.m8[1], OT_MESH_LOCAL_PREFIX_SIZE - 1));
SuccessOrExit(error = Random::Crypto::FillBuffer(&aDataset.mMeshLocalPrefix.m8[1], OT_MESH_LOCAL_PREFIX_SIZE - 1));
aDataset.mSecurityPolicy.mFlags = Get<KeyManager>().GetSecurityPolicyFlags();
aDataset.mChannelMask = Get<Mac::Mac>().GetSupportedChannelMask().GetMask();
@@ -338,7 +338,7 @@ otError ActiveDataset::CreateNewNetwork(otOperationalDataset &aDataset)
do
{
aDataset.mPanId = Random::GetUint16();
aDataset.mPanId = Random::NonCrypto::GetUint16();
} while (aDataset.mPanId == Mac::kPanIdBroadcast);
snprintf(aDataset.mNetworkName.m8, sizeof(aDataset.mNetworkName), "OpenThread-%04x", aDataset.mPanId);
@@ -456,7 +456,8 @@ otError ActiveDataset::GenerateLocal(void)
{
// PSKc has not yet been configured, generate new PSKc at random
otPSKc pskc;
SuccessOrExit(error = otPlatRandomGetTrue(pskc.m8, sizeof(pskc)));
SuccessOrExit(error = Random::Crypto::FillBuffer(pskc.m8, sizeof(pskc)));
tlv.SetPSKc(pskc);
}
+6 -126
View File
@@ -49,6 +49,7 @@
#include "common/logging.hpp"
#include "common/new.hpp"
#include "common/timer.hpp"
#include "crypto/mbedtls.hpp"
#include "crypto/sha256.hpp"
#include "thread/thread_netif.hpp"
@@ -102,8 +103,6 @@ Dtls::Dtls(Instance &aInstance, bool aLayerTwoSecurity)
memset(mCipherSuites, 0, sizeof(mCipherSuites));
memset(mPsk, 0, sizeof(mPsk));
memset(&mEntropy, 0, sizeof(mEntropy));
memset(&mCtrDrbg, 0, sizeof(mCtrDrbg));
memset(&mSsl, 0, sizeof(mSsl));
memset(&mConf, 0, sizeof(mConf));
@@ -114,31 +113,6 @@ Dtls::Dtls(Instance &aInstance, bool aLayerTwoSecurity)
mProvisioningUrl.Init();
}
int Dtls::HandleMbedtlsEntropyPoll(void *aData, unsigned char *aOutput, size_t aInLen, size_t *aOutLen)
{
OT_UNUSED_VARIABLE(aData);
otError error;
int rval = 0;
error = otPlatRandomGetTrue(static_cast<uint8_t *>(aOutput), static_cast<uint16_t>(aInLen));
SuccessOrExit(error);
if (aOutLen != NULL)
{
*aOutLen = aInLen;
}
exit:
if (error != OT_ERROR_NONE)
{
rval = MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
}
return rval;
}
void Dtls::FreeMbedtls(void)
{
#ifdef MBEDTLS_SSL_COOKIE_C
@@ -151,8 +125,6 @@ void Dtls::FreeMbedtls(void)
mbedtls_pk_free(&mPrivateKey);
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#endif // OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
mbedtls_entropy_free(&mEntropy);
mbedtls_ctr_drbg_free(&mCtrDrbg);
mbedtls_ssl_config_free(&mConf);
mbedtls_ssl_free(&mSsl);
}
@@ -295,8 +267,6 @@ otError Dtls::Setup(bool aClient)
mbedtls_ssl_init(&mSsl);
mbedtls_ssl_config_init(&mConf);
mbedtls_ctr_drbg_init(&mCtrDrbg);
mbedtls_entropy_init(&mEntropy);
#if OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
mbedtls_x509_crt_init(&mCaChain);
@@ -305,17 +275,6 @@ otError Dtls::Setup(bool aClient)
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#endif // OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
rval = mbedtls_entropy_add_source(&mEntropy, &Dtls::HandleMbedtlsEntropyPoll, NULL, MBEDTLS_ENTROPY_MIN_PLATFORM,
MBEDTLS_ENTROPY_SOURCE_STRONG);
VerifyOrExit(rval == 0);
{
otExtAddress eui64;
otPlatRadioGetIeeeEui64(&GetInstance(), eui64.m8);
rval = mbedtls_ctr_drbg_seed(&mCtrDrbg, mbedtls_entropy_func, &mEntropy, eui64.m8, sizeof(eui64));
VerifyOrExit(rval == 0);
}
rval = mbedtls_ssl_config_defaults(&mConf, aClient ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
MBEDTLS_SSL_TRANSPORT_DATAGRAM, MBEDTLS_SSL_PRESET_DEFAULT);
VerifyOrExit(rval == 0);
@@ -333,7 +292,7 @@ otError Dtls::Setup(bool aClient)
OT_UNUSED_VARIABLE(mVerifyPeerCertificate);
#endif // OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
mbedtls_ssl_conf_rng(&mConf, mbedtls_ctr_drbg_random, &mCtrDrbg);
mbedtls_ssl_conf_rng(&mConf, mbedtls_ctr_drbg_random, Random::Crypto::MbedTlsContextGet());
mbedtls_ssl_conf_min_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_max_version(&mConf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_ciphersuites(&mConf, mCipherSuites);
@@ -346,7 +305,7 @@ otError Dtls::Setup(bool aClient)
{
mbedtls_ssl_cookie_init(&mCookieCtx);
rval = mbedtls_ssl_cookie_setup(&mCookieCtx, mbedtls_ctr_drbg_random, &mCtrDrbg);
rval = mbedtls_ssl_cookie_setup(&mCookieCtx, mbedtls_ctr_drbg_random, Random::Crypto::MbedTlsContextGet());
VerifyOrExit(rval == 0);
mbedtls_ssl_conf_dtls_cookies(&mConf, mbedtls_ssl_cookie_write, mbedtls_ssl_cookie_check, &mCookieCtx);
@@ -397,7 +356,7 @@ exit:
FreeMbedtls();
}
return MapError(rval);
return Crypto::MbedTls::MapError(rval);
}
#if OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
@@ -600,7 +559,7 @@ exit:
otError Dtls::SetClientId(const uint8_t *aClientId, uint8_t aLength)
{
int rval = mbedtls_ssl_set_client_transport_id(&mSsl, aClientId, aLength);
return MapError(rval);
return Crypto::MbedTls::MapError(rval);
}
#endif // OPENTHREAD_ENABLE_BORDER_AGENT || OPENTHREAD_ENABLE_COMMISSIONER
@@ -619,7 +578,7 @@ otError Dtls::Send(Message &aMessage, uint16_t aLength)
aMessage.Read(0, aLength, buffer);
SuccessOrExit(error = MapError(mbedtls_ssl_write(&mSsl, buffer, aLength)));
SuccessOrExit(error = Crypto::MbedTls::MapError(mbedtls_ssl_write(&mSsl, buffer, aLength)));
aMessage.Free();
@@ -943,85 +902,6 @@ exit:
}
}
otError Dtls::MapError(int rval)
{
otError error = OT_ERROR_NONE;
switch (rval)
{
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_PK_TYPE_MISMATCH:
case MBEDTLS_ERR_PK_FILE_IO_ERROR:
case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
case MBEDTLS_ERR_PK_INVALID_PUBKEY:
case MBEDTLS_ERR_PK_INVALID_ALG:
case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
case MBEDTLS_ERR_X509_SIG_MISMATCH:
case MBEDTLS_ERR_X509_BAD_INPUT_DATA:
case MBEDTLS_ERR_X509_FILE_IO_ERROR:
case MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT:
case MBEDTLS_ERR_X509_INVALID_VERSION:
case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG:
case MBEDTLS_ERR_X509_INVALID_SERIAL:
case MBEDTLS_ERR_X509_UNKNOWN_OID:
case MBEDTLS_ERR_X509_INVALID_FORMAT:
case MBEDTLS_ERR_X509_INVALID_ALG:
case MBEDTLS_ERR_X509_INVALID_NAME:
case MBEDTLS_ERR_X509_INVALID_DATE:
case MBEDTLS_ERR_X509_INVALID_SIGNATURE:
case MBEDTLS_ERR_X509_INVALID_EXTENSIONS:
case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_SSL_BAD_INPUT_DATA:
error = OT_ERROR_INVALID_ARGS;
break;
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_PEM_ALLOC_FAILED:
case MBEDTLS_ERR_PK_ALLOC_FAILED:
case MBEDTLS_ERR_X509_BUFFER_TOO_SMALL:
case MBEDTLS_ERR_X509_ALLOC_FAILED:
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_SSL_ALLOC_FAILED:
case MBEDTLS_ERR_SSL_WANT_WRITE:
error = OT_ERROR_NO_BUFS;
break;
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
case MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE:
case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED:
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
case MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED:
error = OT_ERROR_SECURITY;
break;
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_X509_FATAL_ERROR:
error = OT_ERROR_FAILED;
break;
#endif // MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
case MBEDTLS_ERR_SSL_TIMEOUT:
case MBEDTLS_ERR_SSL_WANT_READ:
error = OT_ERROR_BUSY;
break;
default:
assert(rval >= 0);
break;
}
return error;
}
void Dtls::HandleMbedtlsDebug(void *ctx, int level, const char *, int, const char *str)
{
OT_UNUSED_VARIABLE(str);
+3 -10
View File
@@ -37,10 +37,6 @@
#include "openthread-core-config.h"
#include <mbedtls/certs.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/entropy.h>
#include <mbedtls/entropy_poll.h>
#include <mbedtls/error.h>
#include <mbedtls/net_sockets.h>
#include <mbedtls/ssl.h>
#include <mbedtls/ssl_cookie.h>
@@ -57,6 +53,7 @@
#include "common/locator.hpp"
#include "common/message.hpp"
#include "common/random.hpp"
#include "common/timer.hpp"
#include "crypto/sha256.hpp"
#include "meshcop/meshcop_tlvs.hpp"
@@ -402,8 +399,6 @@ private:
void FreeMbedtls(void);
otError Setup(bool aClient);
static otError MapError(int rval);
#if OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
/**
* Set keys and/or certificates for dtls session dependent of used cipher suite.
@@ -485,10 +480,8 @@ private:
bool mVerifyPeerCertificate;
mbedtls_entropy_context mEntropy;
mbedtls_ctr_drbg_context mCtrDrbg;
mbedtls_ssl_context mSsl;
mbedtls_ssl_config mConf;
mbedtls_ssl_context mSsl;
mbedtls_ssl_config mConf;
#ifdef MBEDTLS_SSL_COOKIE_C
mbedtls_ssl_cookie_ctx mCookieCtx;
-2
View File
@@ -35,8 +35,6 @@
#include "energy_scan_client.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
+2 -3
View File
@@ -39,13 +39,12 @@
#include <stdio.h>
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "common/random.hpp"
#include "meshcop/meshcop.hpp"
#include "meshcop/meshcop_tlvs.hpp"
#include "thread/thread_netif.hpp"
@@ -61,7 +60,7 @@ Leader::Leader(Instance &aInstance)
, mKeepAlive(OT_URI_PATH_LEADER_KEEP_ALIVE, Leader::HandleKeepAlive, this)
, mTimer(aInstance, HandleTimer, this)
, mDelayTimerMinimal(DelayTimerTlv::kDelayTimerMinimal)
, mSessionId(Random::GetUint16())
, mSessionId(Random::NonCrypto::GetUint16())
{
Get<Coap::Coap>().AddResource(mPetition);
Get<Coap::Coap>().AddResource(mKeepAlive);
-2
View File
@@ -35,8 +35,6 @@
#include "panid_query_client.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
+1 -1
View File
@@ -202,7 +202,7 @@ bool Dhcp6Client::ProcessNextIdentityAssociation()
}
// new transaction id
Random::FillBuffer(mTransactionId, kTransactionIdSize);
Random::NonCrypto::FillBuffer(mTransactionId, kTransactionIdSize);
mIdentityAssociationCurrent = &mIdentityAssociations[i];
+1 -1
View File
@@ -46,7 +46,7 @@ namespace Ip6 {
void MplBufferedMessageMetadata::GenerateNextTransmissionTime(uint32_t aCurrentTime, uint8_t aInterval)
{
// Emulate Trickle timer behavior and set up the next retransmission within [0,I) range.
uint8_t t = aInterval == 0 ? aInterval : Random::GetUint8InRange(0, aInterval);
uint8_t t = aInterval == 0 ? aInterval : Random::NonCrypto::GetUint8InRange(0, aInterval);
// Set transmission time at the beginning of the next interval.
SetTransmissionTime(aCurrentTime + GetIntervalOffset() + t);
-2
View File
@@ -37,8 +37,6 @@
#include "address_resolver.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
+2 -2
View File
@@ -78,7 +78,7 @@ otError AnnounceSenderBase::SendAnnounce(Mac::ChannelMask aChannelMask,
mJitter = aJitter;
mChannel = Mac::ChannelMask::kChannelIteratorFirst;
mTimer.Start(Random::AddJitter(mPeriod, mJitter));
mTimer.Start(Random::NonCrypto::AddJitter(mPeriod, mJitter));
exit:
return error;
@@ -106,7 +106,7 @@ void AnnounceSenderBase::HandleTimer(void)
Get<Mle::MleRouter>().SendAnnounce(mChannel, false);
mTimer.Start(Random::AddJitter(mPeriod, mJitter));
mTimer.Start(Random::NonCrypto::AddJitter(mPeriod, mJitter));
exit:
return;
-2
View File
@@ -35,8 +35,6 @@
#include "data_poll_manager.hpp"
#include <openthread/platform/random.h>
#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
-2
View File
@@ -35,8 +35,6 @@
#include "energy_scan_server.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
+2 -2
View File
@@ -86,7 +86,7 @@ MeshForwarder::MeshForwarder(Instance &aInstance)
#endif
, mDataPollManager(aInstance)
{
mFragTag = Random::GetUint16();
mFragTag = Random::NonCrypto::GetUint16();
mIpCounters.mTxSuccess = 0;
mIpCounters.mRxSuccess = 0;
@@ -553,7 +553,7 @@ otError MeshForwarder::HandleFrameRequest(Mac::Frame &aFrame)
do
{
panid = Random::GetUint16();
panid = Random::NonCrypto::GetUint16();
} while (panid == Mac::kPanIdBroadcast);
Get<Mac::Mac>().SetPanId(panid);
+13 -13
View File
@@ -168,8 +168,8 @@ Mle::Mle(Instance &aInstance)
meshLocalPrefix.m8[7] = 0x00;
// mesh-local 64
Random::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE,
OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE);
Random::NonCrypto::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE,
OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE);
mMeshLocal64.mPrefixLength = 64;
mMeshLocal64.mPreferred = true;
@@ -669,7 +669,7 @@ uint32_t Mle::GetAttachStartDelay(void) const
if (mAttachCounter == 0)
{
delay = 1 + Random::GetUint32InRange(0, kParentRequestRouterTimeout);
delay = 1 + Random::NonCrypto::GetUint32InRange(0, kParentRequestRouterTimeout);
ExitNow();
}
#if OPENTHREAD_CONFIG_ENABLE_ATTACH_BACKOFF
@@ -685,12 +685,12 @@ uint32_t Mle::GetAttachStartDelay(void) const
}
else
{
delay = Random::AddJitter(kAttachBackoffMaxInterval, kAttachBackoffJitter);
delay = Random::NonCrypto::AddJitter(kAttachBackoffMaxInterval, kAttachBackoffJitter);
}
}
#endif // OPENTHREAD_CONFIG_ENABLE_ATTACH_BACKOFF
jitter = Random::GetUint32InRange(0, kAttachStartJitter);
jitter = Random::NonCrypto::GetUint32InRange(0, kAttachStartJitter);
if (jitter + delay > delay) // check for overflow
{
@@ -1482,8 +1482,8 @@ void Mle::HandleStateChanged(otChangedFlags aFlags)
if (!Get<ThreadNetif>().IsUnicastAddress(mMeshLocal64.GetAddress()))
{
// Mesh Local EID was removed, choose a new one and add it back
Random::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE,
OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE);
Random::NonCrypto::FillBuffer(mMeshLocal64.GetAddress().mFields.m8 + OT_IP6_PREFIX_SIZE,
OT_IP6_ADDRESS_SIZE - OT_IP6_PREFIX_SIZE);
Get<ThreadNetif>().AddUnicastAddress(mMeshLocal64);
Get<Notifier>().Signal(OT_CHANGED_THREAD_ML_ADDR);
@@ -1777,7 +1777,7 @@ uint32_t Mle::Reattach(void)
Get<MeshCoP::PendingDataset>().ApplyConfiguration();
mReattachState = kReattachPending;
SetAttachState(kAttachStateStart);
delay = 1 + Random::GetUint32InRange(0, kAttachStartJitter);
delay = 1 + Random::NonCrypto::GetUint32InRange(0, kAttachStartJitter);
}
else
{
@@ -1932,7 +1932,7 @@ otError Mle::SendParentRequest(ParentRequestType aType)
uint8_t scanMask = 0;
Ip6::Address destination;
Random::FillBuffer(mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge));
Random::NonCrypto::FillBuffer(mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge));
switch (aType)
{
@@ -2259,7 +2259,7 @@ otError Mle::SendChildUpdateRequest(void)
switch (mRole)
{
case OT_DEVICE_ROLE_DETACHED:
Random::FillBuffer(mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge));
Random::NonCrypto::FillBuffer(mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge));
SuccessOrExit(error = AppendChallenge(*message, mParentRequest.mChallenge, sizeof(mParentRequest.mChallenge)));
break;
@@ -2880,7 +2880,7 @@ otError Mle::HandleAdvertisement(const Message &aMessage, const Ip6::MessageInfo
if (mRetrieveNewNetworkData ||
(static_cast<int8_t>(leaderData.GetDataVersion() - Get<NetworkData::Leader>().GetVersion()) > 0))
{
delay = Random::GetUint16InRange(0, kMleMaxResponseDelay);
delay = Random::NonCrypto::GetUint16InRange(0, kMleMaxResponseDelay);
SendDataRequest(aMessageInfo.GetPeerAddr(), tlvs, sizeof(tlvs), delay);
}
}
@@ -3048,7 +3048,7 @@ exit:
if (aMessageInfo.GetSockAddr().IsMulticast())
{
delay = Random::GetUint16InRange(0, kMleMaxResponseDelay);
delay = Random::NonCrypto::GetUint16InRange(0, kMleMaxResponseDelay);
}
else
{
@@ -4031,7 +4031,7 @@ void Mle::StartParentSearchTimer(void)
{
uint32_t interval;
interval = Random::GetUint32InRange(0, kParentSearchJitterInterval);
interval = Random::NonCrypto::GetUint32InRange(0, kParentSearchJitterInterval);
if (mParentSearchIsInBackoff)
{
+14 -12
View File
@@ -176,9 +176,10 @@ otError MleRouter::BecomeLeader(void)
mRouterTable.Clear();
partitionId = mFixedLeaderPartitionId ? mFixedLeaderPartitionId : Random::GetUint32();
partitionId = mFixedLeaderPartitionId ? mFixedLeaderPartitionId : Random::NonCrypto::GetUint32();
leaderId = IsRouterIdValid(mPreviousRouterId) ? mPreviousRouterId : Random::GetUint8InRange(0, kMaxRouterId + 1);
leaderId = IsRouterIdValid(mPreviousRouterId) ? mPreviousRouterId
: Random::NonCrypto::GetUint8InRange(0, kMaxRouterId + 1);
SetLeaderData(partitionId, mLeaderWeight, leaderId);
@@ -219,7 +220,7 @@ otError MleRouter::HandleChildStart(AttachMode aMode)
{
otError error = OT_ERROR_NONE;
mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter);
mRouterSelectionJitterTimeout = 1 + Random::NonCrypto::GetUint8InRange(0, mRouterSelectionJitter);
StopLeader();
mStateUpdateTimer.Start(kStateUpdatePeriod);
@@ -511,7 +512,7 @@ otError MleRouter::SendLinkRequest(Neighbor *aNeighbor)
if (aNeighbor == NULL)
{
Random::FillBuffer(mChallenge, sizeof(mChallenge));
Random::NonCrypto::FillBuffer(mChallenge, sizeof(mChallenge));
mChallengeTimeout = (((2 * kMaxResponseDelay) + kStateUpdatePeriod - 1) / kStateUpdatePeriod);
@@ -531,7 +532,7 @@ otError MleRouter::SendLinkRequest(Neighbor *aNeighbor)
{
uint8_t challenge[ChallengeTlv::kMaxSize];
Random::FillBuffer(challenge, sizeof(challenge));
Random::NonCrypto::FillBuffer(challenge, sizeof(challenge));
SuccessOrExit(error = AppendChallenge(*message, challenge, sizeof(challenge)));
}
@@ -747,7 +748,7 @@ otError MleRouter::SendLinkAccept(const Ip6::MessageInfo &aMessageInfo,
if (aMessageInfo.GetSockAddr().IsMulticast())
{
SuccessOrExit(error = AddDelayedResponse(*message, aMessageInfo.GetPeerAddr(),
1 + Random::GetUint16InRange(0, kMaxResponseDelay)));
1 + Random::NonCrypto::GetUint16InRange(0, kMaxResponseDelay)));
LogMleMessage("Delay Link Accept", aMessageInfo.GetPeerAddr());
}
@@ -1290,7 +1291,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa
if ((router->GetState() == Neighbor::kStateValid) && IsFullThreadDevice() &&
(mRouterSelectionJitterTimeout == 0) && (mRouterTable.GetActiveRouterCount() < mRouterUpgradeThreshold))
{
mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter);
mRouterSelectionJitterTimeout = 1 + Random::NonCrypto::GetUint8InRange(0, mRouterSelectionJitter);
ExitNow();
}
@@ -1374,7 +1375,7 @@ otError MleRouter::HandleAdvertisement(const Message &aMessage, const Ip6::Messa
HasMinDowngradeNeighborRouters() && HasSmallNumberOfChildren() &&
HasOneNeighborWithComparableConnectivity(route, routerId))
{
mRouterSelectionJitterTimeout = 1 + Random::GetUint8InRange(0, mRouterSelectionJitter);
mRouterSelectionJitterTimeout = 1 + Random::NonCrypto::GetUint8InRange(0, mRouterSelectionJitter);
}
// fall through
@@ -1920,11 +1921,11 @@ void MleRouter::SendParentResponse(Child *aChild, const ChallengeTlv &aChallenge
if (aRoutersOnlyRequest)
{
delay = 1 + Random::GetUint16InRange(0, kParentResponseMaxDelayRouters);
delay = 1 + Random::NonCrypto::GetUint16InRange(0, kParentResponseMaxDelayRouters);
}
else
{
delay = 1 + Random::GetUint16InRange(0, kParentResponseMaxDelayAll);
delay = 1 + Random::NonCrypto::GetUint16InRange(0, kParentResponseMaxDelayAll);
}
SuccessOrExit(error = AddDelayedResponse(*message, destination, delay));
@@ -2534,7 +2535,8 @@ void MleRouter::HandleNetworkDataUpdateRouter(void)
destination.mFields.m16[0] = HostSwap16(0xff02);
destination.mFields.m16[7] = HostSwap16(0x0001);
delay = (mRole == OT_DEVICE_ROLE_LEADER) ? 0 : Random::GetUint16InRange(0, kUnsolicitedDataResponseJitter);
delay =
(mRole == OT_DEVICE_ROLE_LEADER) ? 0 : Random::NonCrypto::GetUint16InRange(0, kUnsolicitedDataResponseJitter);
SendDataResponse(destination, tlvs, sizeof(tlvs), delay);
SynchronizeChildNetworkData();
@@ -2773,7 +2775,7 @@ otError MleRouter::SendDiscoveryResponse(const Ip6::Address &aDestination, uint1
tlv.SetLength(static_cast<uint8_t>(message->GetLength() - startOffset));
message->Write(startOffset - sizeof(tlv), sizeof(tlv), &tlv);
delay = Random::GetUint16InRange(0, kDiscoveryMaxJitter + 1);
delay = Random::NonCrypto::GetUint16InRange(0, kDiscoveryMaxJitter + 1);
SuccessOrExit(error = AddDelayedResponse(*message, aDestination, delay));
-2
View File
@@ -35,8 +35,6 @@
#include "network_data.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
+3 -4
View File
@@ -35,8 +35,6 @@
#include "network_data_leader.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
@@ -45,6 +43,7 @@
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "common/message.hpp"
#include "common/random.hpp"
#include "common/timer.hpp"
#include "mac/mac_frame.hpp"
#include "thread/lowpan.hpp"
@@ -64,8 +63,8 @@ LeaderBase::LeaderBase(Instance &aInstance)
void LeaderBase::Reset(void)
{
mVersion = static_cast<uint8_t>(otPlatRandomGet());
mStableVersion = static_cast<uint8_t>(otPlatRandomGet());
mVersion = Random::NonCrypto::GetUint8();
mStableVersion = Random::NonCrypto::GetUint8();
mLength = 0;
Get<Notifier>().Signal(OT_CHANGED_THREAD_NETDATA);
}
@@ -37,8 +37,6 @@
#include "network_data_leader.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
-2
View File
@@ -35,8 +35,6 @@
#include "network_diagnostic.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
-2
View File
@@ -35,8 +35,6 @@
#include "panid_query_server.hpp"
#include <openthread/platform/random.h>
#include "coap/coap_message.hpp"
#include "common/code_utils.hpp"
#include "common/debug.hpp"
+2 -2
View File
@@ -64,7 +64,7 @@ void RouterTable::Iterator::Advance(void)
RouterTable::RouterTable(Instance &aInstance)
: InstanceLocator(aInstance)
, mRouterIdSequenceLastUpdated(0)
, mRouterIdSequence(Random::GetUint8())
, mRouterIdSequence(Random::NonCrypto::GetUint8())
, mActiveRouterCount(0)
{
Clear();
@@ -212,7 +212,7 @@ Router *RouterTable::Allocate(void)
VerifyOrExit(mActiveRouterCount < Mle::kMaxRouters && numAvailable > 0);
// choose available router id at random
freeBit = Random::GetUint8InRange(0, numAvailable);
freeBit = Random::NonCrypto::GetUint8InRange(0, numAvailable);
// allocate router
for (uint8_t routerId = 0; routerId <= Mle::kMaxRouterId; routerId++)
+2 -2
View File
@@ -45,7 +45,7 @@ namespace ot {
void Neighbor::GenerateChallenge(void)
{
Random::FillBuffer(mValidPending.mPending.mChallenge, sizeof(mValidPending.mPending.mChallenge));
Random::NonCrypto::FillBuffer(mValidPending.mPending.mChallenge, sizeof(mValidPending.mPending.mChallenge));
}
bool Child::IsStateValidOrAttaching(void) const
@@ -239,7 +239,7 @@ exit:
void Child::GenerateChallenge(void)
{
Random::FillBuffer(mAttachChallenge, sizeof(mAttachChallenge));
Random::NonCrypto::FillBuffer(mAttachChallenge, sizeof(mAttachChallenge));
}
const Mac::Address &Child::GetMacAddress(Mac::Address &aMacAddress) const
+3 -5
View File
@@ -34,8 +34,6 @@
#include "channel_manager.hpp"
#include <openthread/platform/random.h>
#include "common/code_utils.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
@@ -77,7 +75,7 @@ void ChannelManager::RequestChannelChange(uint8_t aChannel)
mChannel = aChannel;
mActiveTimestamp = 0;
mTimer.Start(1 + Random::GetUint32InRange(0, kRequestStartJitterInterval));
mTimer.Start(1 + Random::NonCrypto::GetUint32InRange(0, kRequestStartJitterInterval));
Get<Notifier>().Signal(OT_CHANGED_CHANNEL_MANAGER_NEW_CHANNEL);
@@ -131,7 +129,7 @@ void ChannelManager::PreparePendingDataset(void)
}
}
pendingTimestamp += 1 + Random::GetUint32InRange(0, kMaxTimestampIncrease);
pendingTimestamp += 1 + Random::NonCrypto::GetUint32InRange(0, kMaxTimestampIncrease);
error = Get<MeshCoP::ActiveDataset>().Read(dataset);
@@ -194,7 +192,7 @@ void ChannelManager::PreparePendingDataset(void)
}
else
{
mActiveTimestamp = dataset.mActiveTimestamp + 1 + Random::GetUint32InRange(0, kMaxTimestampIncrease);
mActiveTimestamp = dataset.mActiveTimestamp + 1 + Random::NonCrypto::GetUint32InRange(0, kMaxTimestampIncrease);
}
dataset.mActiveTimestamp = mActiveTimestamp;
+1 -1
View File
@@ -121,7 +121,7 @@ void ChannelMonitor::HandleTimer(void)
{
Get<Mac::Mac>().EnergyScan(mScanChannelMasks[mChannelMaskIndex], 0, &ChannelMonitor::HandleEnergyScanResult);
mTimer.StartAt(mTimer.GetFireTime(), Random::AddJitter(kTimerInterval, kMaxJitterInterval));
mTimer.StartAt(mTimer.GetFireTime(), Random::NonCrypto::AddJitter(kTimerInterval, kMaxJitterInterval));
}
void ChannelMonitor::HandleEnergyScanResult(Instance &aInstance, otEnergyScanResult *aResult)
+1 -1
View File
@@ -200,7 +200,7 @@ void JamDetector::HandleTimer(void)
}
}
mTimer.Start(mSampleInterval + Random::GetUint32InRange(0, kMaxRandomDelay));
mTimer.Start(mSampleInterval + Random::NonCrypto::GetUint32InRange(0, kMaxRandomDelay));
exit:
return;
+3 -3
View File
@@ -300,7 +300,7 @@ void Slaac::GenerateIid(Ip6::NetifUnicastAddress &aAddress) const
}
otLogWarnUtil("SLAAC: Failed to generate a non-reserved IID after %d attempts", dadCounter);
Random::FillBuffer(hash, Ip6::Address::kInterfaceIdentifierSize);
Random::NonCrypto::FillBuffer(hash, Ip6::Address::kInterfaceIdentifierSize);
aAddress.GetAddress().SetIid(&hash[0]);
exit:
@@ -317,11 +317,11 @@ void Slaac::GetIidSecretKey(IidSecretKey &aKey) const
// If there is no previously saved secret key, generate
// a random one and save it.
error = otPlatRandomGetTrue(aKey.m8, sizeof(IidSecretKey));
error = Random::Crypto::FillBuffer(aKey.m8, sizeof(IidSecretKey));
if (error != OT_ERROR_NONE)
{
Random::FillBuffer(aKey.m8, sizeof(IidSecretKey));
Random::NonCrypto::FillBuffer(aKey.m8, sizeof(IidSecretKey));
}
Get<Settings>().SaveSlaacIidSecretKey(aKey);
+1 -1
View File
@@ -41,12 +41,12 @@ libopenthread_posix_a_CPPFLAGS = \
libopenthread_posix_a_SOURCES = \
alarm.c \
entropy.c \
hdlc_interface.cpp \
logging.c \
misc.c \
netif.cpp \
radio_spinel.cpp \
random.c \
settings.cpp \
sim.c \
system.c \
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, The OpenThread Authors.
* Copyright (c) 2019, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,32 +28,31 @@
/**
* @file
* This file implements a pseudo-random number generator.
* This file implements an entropy source based on /dev/urandom or pseudo-random generator.
*
*/
#include <openthread/platform/entropy.h>
#include "openthread-core-config.h"
#include "platform-posix.h"
#include <assert.h>
#include <stdio.h>
#include <openthread/platform/random.h>
#include "code_utils.h"
#include "platform-posix.h"
#include <openthread/error.h>
#if __SANITIZE_ADDRESS__ != 0
static uint32_t sState = 1;
#endif // __SANITIZE_ADDRESS__
void platformRandomInit(void)
{
#if __SANITIZE_ADDRESS__ == 0
otError error;
error = otPlatRandomGetTrue((uint8_t *)&sState, sizeof(sState));
assert(error == OT_ERROR_NONE);
#else // __SANITIZE_ADDRESS__
#if __SANITIZE_ADDRESS__ != 0
// Multiplying gNodeId assures that no two nodes gets the same seed within an hour.
sState = (uint32_t)time(NULL) + (3600 * gNodeId);
@@ -61,7 +60,9 @@ void platformRandomInit(void)
#endif // __SANITIZE_ADDRESS__
}
uint32_t otPlatRandomGet(void)
#if __SANITIZE_ADDRESS__ != 0
uint32_t randomUint32Get(void)
{
uint32_t mlcg, p, q;
uint64_t tmpstate;
@@ -83,7 +84,9 @@ uint32_t otPlatRandomGet(void)
return mlcg;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
#endif // __SANITIZE_ADDRESS__
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
otError error = OT_ERROR_NONE;
@@ -121,7 +124,7 @@ exit:
for (uint16_t length = 0; length < aOutputLength; length++)
{
aOutput[length] = (uint8_t)otPlatRandomGet();
aOutput[length] = (uint8_t)randomUint32Get();
}
exit:
+2 -25
View File
@@ -34,7 +34,6 @@
#include <openthread/platform/logging.h>
#include <openthread/platform/misc.h>
#include <openthread/platform/radio.h>
#include <openthread/platform/random.h>
#include <openthread/platform/settings.h>
#include <openthread/platform/uart.h>
@@ -339,33 +338,11 @@ int8_t otPlatRadioGetReceiveSensitivity(otInstance *aInstance)
return 0;
}
uint32_t otPlatRandomGet(void)
{
uint32_t mlcg, p, q;
uint64_t tmpstate;
tmpstate = (uint64_t)33614 * (uint64_t)sRandomState;
q = tmpstate & 0xffffffff;
q = q >> 1;
p = tmpstate >> 32;
mlcg = p + q;
if (mlcg & 0x80000000)
{
mlcg &= 0x7fffffff;
mlcg++;
}
sRandomState = mlcg;
return mlcg;
}
otError otPlatRandomGetTrue(uint8_t *aOutput, uint16_t aOutputLength)
otError otPlatEntropyGet(uint8_t *aOutput, uint16_t aOutputLength)
{
for (uint16_t length = 0; length < aOutputLength; length++)
{
aOutput[length] = (uint8_t)otPlatRandomGet();
aOutput[length] = (uint8_t)rand();
}
return OT_ERROR_NONE;

Some files were not shown because too many files have changed in this diff Show More