diff --git a/examples/bridge-app/linux/main.cpp b/examples/bridge-app/linux/main.cpp index 9bd7ede2ac58f0..e053008b1a0ced 100644 --- a/examples/bridge-app/linux/main.cpp +++ b/examples/bridge-app/linux/main.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include #include #include diff --git a/examples/ota-provider-app/linux/main.cpp b/examples/ota-provider-app/linux/main.cpp index 2b951f81e6461d..d125e4312452e8 100644 --- a/examples/ota-provider-app/linux/main.cpp +++ b/examples/ota-provider-app/linux/main.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include diff --git a/examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp b/examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp index ea8d06a62c409c..d04235b9653f90 100644 --- a/examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp +++ b/examples/ota-provider-app/ota-provider-common/OTAProviderExample.cpp @@ -23,9 +23,9 @@ #include #include #include +#include #include #include -#include #include // For chip::kTestDeviceNodeId #include @@ -56,7 +56,7 @@ void GenerateUpdateToken(uint8_t * buf, size_t bufSize) { for (size_t i = 0; i < bufSize; ++i) { - buf[i] = chip::GetRandU8(); + buf[i] = chip::Crypto::GetRandU8(); } } diff --git a/examples/ota-requestor-app/linux/main.cpp b/examples/ota-requestor-app/linux/main.cpp index 9faa2fad741d69..2601aa6e755233 100644 --- a/examples/ota-requestor-app/linux/main.cpp +++ b/examples/ota-requestor-app/linux/main.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include diff --git a/examples/platform/linux/AppMain.cpp b/examples/platform/linux/AppMain.cpp index a5820733a0b36c..a514eaca993e37 100644 --- a/examples/platform/linux/AppMain.cpp +++ b/examples/platform/linux/AppMain.cpp @@ -33,7 +33,6 @@ #include #include -#include #include #include #include diff --git a/examples/shell/shell_common/cmd_misc.cpp b/examples/shell/shell_common/cmd_misc.cpp index a99ec89e0a395d..ff8a5ad9739656 100644 --- a/examples/shell/shell_common/cmd_misc.cpp +++ b/examples/shell/shell_common/cmd_misc.cpp @@ -17,11 +17,11 @@ #include +#include #include #include #include #include -#include #include #include @@ -56,7 +56,7 @@ CHIP_ERROR cmd_log(int argc, char ** argv) CHIP_ERROR cmd_rand(int argc, char ** argv) { - streamer_printf(streamer_get(), "%d\n\r", GetRandU8()); + streamer_printf(streamer_get(), "%d\n\r", static_cast(chip::Crypto::GetRandU8())); return CHIP_NO_ERROR; } diff --git a/examples/shell/standalone/main.cpp b/examples/shell/standalone/main.cpp index aa8e8627753708..77d880471d7600 100644 --- a/examples/shell/standalone/main.cpp +++ b/examples/shell/standalone/main.cpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include diff --git a/src/crypto/BUILD.gn b/src/crypto/BUILD.gn index b8b0086dbea049..761d3e6dd1f020 100644 --- a/src/crypto/BUILD.gn +++ b/src/crypto/BUILD.gn @@ -58,6 +58,8 @@ static_library("crypto") { sources = [ "CHIPCryptoPAL.cpp", "CHIPCryptoPAL.h", + "RandUtils.cpp", + "RandUtils.h", ] cflags = [ "-Wconversion" ] diff --git a/src/crypto/RandUtils.cpp b/src/crypto/RandUtils.cpp new file mode 100644 index 00000000000000..b77026ad58ebd7 --- /dev/null +++ b/src/crypto/RandUtils.cpp @@ -0,0 +1,69 @@ +/* + * + * Copyright (c) 2020 Project CHIP Authors + * Copyright (c) 2013-2017 Nest Labs, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file + * This file implements utility functions for deriving random integers. + * + * @note These utility functions do not generate cryptographically strong + * random number. To get cryptographically strong random data use + * chip::Crypto::DRBG_get_bytes(). + * + */ + +#include "RandUtils.h" + +#include +#include + +#include +#include + +namespace chip { +namespace Crypto { + +uint64_t GetRandU64() +{ + uint64_t tmp = 0; + VerifyOrDie(CHIP_NO_ERROR == DRBG_get_bytes(reinterpret_cast(&tmp), sizeof(tmp))); + return tmp; +} + +uint32_t GetRandU32() +{ + uint32_t tmp = 0; + VerifyOrDie(CHIP_NO_ERROR == DRBG_get_bytes(reinterpret_cast(&tmp), sizeof(tmp))); + return tmp; +} + +uint16_t GetRandU16() +{ + uint16_t tmp = 0; + VerifyOrDie(CHIP_NO_ERROR == DRBG_get_bytes(reinterpret_cast(&tmp), sizeof(tmp))); + return tmp; +} + +uint8_t GetRandU8() +{ + uint8_t tmp = 0; + VerifyOrDie(CHIP_NO_ERROR == DRBG_get_bytes(&tmp, sizeof(tmp))); + return tmp; +} + +} // namespace Crypto +} // namespace chip diff --git a/src/lib/support/RandUtils.h b/src/crypto/RandUtils.h similarity index 82% rename from src/lib/support/RandUtils.h rename to src/crypto/RandUtils.h index 46c6f7172623e7..c12d56cc58bed0 100644 --- a/src/lib/support/RandUtils.h +++ b/src/crypto/RandUtils.h @@ -16,21 +16,12 @@ * limitations under the License. */ -/** - * @file - * This file defines utility functions for deriving random integers. - * - * @note These utility functions do not generate cryptographically strong - * random number. To get cryptographically strong random data use - * chip::Crypto::DRBG_get_bytes(). - * - */ - #pragma once #include namespace chip { +namespace Crypto { /** * This function generates 64-bit unsigned random number. @@ -64,4 +55,5 @@ extern uint16_t GetRandU16(); */ extern uint8_t GetRandU8(); +} // namespace Crypto } // namespace chip diff --git a/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp b/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp index d0a917b17a96e0..b9aab7f843d718 100644 --- a/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp +++ b/src/include/platform/internal/GenericSoftwareUpdateManagerImpl.cpp @@ -27,6 +27,8 @@ #if CHIP_DEVICE_CONFIG_ENABLE_SOFTWARE_UPDATE_MANAGER +#include + #include #include #include @@ -35,7 +37,6 @@ #include #include -#include #include #include @@ -724,7 +725,7 @@ uint32_t GenericSoftwareUpdateManagerImpl::GetNextWaitTimeInterval() template uint32_t GenericSoftwareUpdateManagerImpl::ComputeNextScheduledWaitTimeInterval(void) { - uint32_t timeOutMsecs = (mMinWaitTimeMs + (GetRandU32() % (mMaxWaitTimeMs - mMinWaitTimeMs))); + uint32_t timeOutMsecs = (mMinWaitTimeMs + (chip::Crypto::GetRandU32() % (mMaxWaitTimeMs - mMinWaitTimeMs))); ChipLogProgress(DeviceLayer, "Next Scheduled Software Update Check in %ums", timeOutMsecs); @@ -1044,7 +1045,7 @@ void GenericSoftwareUpdateManagerImpl::DefaultRetryPolicyCallback(voi if (maxWaitTimeInMsec != 0) { minWaitTimeInMsec = (CHIP_DEVICE_CONFIG_SWU_MIN_WAIT_TIME_INTERVAL_PERCENT_PER_STEP * maxWaitTimeInMsec) / 100; - waitTimeInMsec = minWaitTimeInMsec + (GetRandU32() % (maxWaitTimeInMsec - minWaitTimeInMsec)); + waitTimeInMsec = minWaitTimeInMsec + (chip::Crypto::GetRandU32() % (maxWaitTimeInMsec - minWaitTimeInMsec)); ChipLogDetail(DeviceLayer, "Computing swu retry policy: attempts %" PRIu32 ", max wait time %" PRIu32 " ms, selected wait time %" PRIu32 diff --git a/src/lib/core/tests/TestCHIPTLV.cpp b/src/lib/core/tests/TestCHIPTLV.cpp index 60c15d028391cd..fa7ff80117a21f 100644 --- a/src/lib/core/tests/TestCHIPTLV.cpp +++ b/src/lib/core/tests/TestCHIPTLV.cpp @@ -35,13 +35,13 @@ #include #include -#include #include #include #include #include +#include #include using namespace chip; @@ -4081,7 +4081,7 @@ static void TLVReaderFuzzTest(nlTestSuite * inSuite, void * inContext) { uint8_t fuzzMask = sFixedFuzzMask; while (fuzzMask == 0) - fuzzMask = GetRandU8(); + fuzzMask = static_cast(rand() & 0xFF); fuzzedData[i] ^= fuzzMask; } diff --git a/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp b/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp index 5db2b3fb905683..39705f5d1ee112 100644 --- a/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp +++ b/src/lib/dnssd/Advertiser_ImplMinimalMdns.cpp @@ -23,6 +23,7 @@ #include "MinimalMdnsServer.h" #include "ServiceNaming.h" +#include #include #include #include @@ -32,8 +33,8 @@ #include #include #include +#include #include -#include #include // Enable detailed mDNS logging for received queries @@ -231,8 +232,7 @@ class AdvertiserMinMdns : public ServiceAdvertiser, QueryResponderAllocator * FindEmptyOperationalAllocator(); ResponseSender mResponseSender; - uint32_t mCommissionInstanceName1; - uint32_t mCommissionInstanceName2; + uint8_t mCommissionableInstanceName[sizeof(uint64_t)]; // current request handling const chip::Inet::IPPacketInfo * mCurrentSource = nullptr; @@ -280,8 +280,9 @@ CHIP_ERROR AdvertiserMinMdns::Init(chip::Inet::InetLayer * inetLayer) { GlobalMinimalMdnsServer::Server().Shutdown(); - mCommissionInstanceName1 = GetRandU32(); - mCommissionInstanceName2 = GetRandU32(); + uint64_t random_instance_name = chip::Crypto::GetRandU64(); + memcpy(&mCommissionableInstanceName[0], &random_instance_name, sizeof(mCommissionableInstanceName)); + // Re-set the server in the response sender in case this has been swapped in the // GlobalMinimalMdnsServer (used for testing). mResponseSender.SetServer(&GlobalMinimalMdnsServer::Server()); @@ -442,12 +443,9 @@ CHIP_ERROR AdvertiserMinMdns::GetCommissionableInstanceName(char * instanceName, { return CHIP_ERROR_NO_MEMORY; } - size_t len = snprintf(instanceName, maxLength, ChipLogFormatX64, mCommissionInstanceName1, mCommissionInstanceName2); - if (len >= maxLength) - { - return CHIP_ERROR_NO_MEMORY; - } - return CHIP_NO_ERROR; + + return chip::Encoding::BytesToUppercaseHexString(&mCommissionableInstanceName[0], sizeof(mCommissionableInstanceName), + instanceName, maxLength); } CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & params) diff --git a/src/lib/dnssd/BUILD.gn b/src/lib/dnssd/BUILD.gn index c209322fab9a9f..90fb0bdd31c08a 100644 --- a/src/lib/dnssd/BUILD.gn +++ b/src/lib/dnssd/BUILD.gn @@ -23,6 +23,7 @@ source_set("platform_header") { static_library("dnssd") { public_deps = [ ":platform_header", + "${chip_root}/src/crypto", "${chip_root}/src/lib/core", "${chip_root}/src/lib/support", ] diff --git a/src/lib/dnssd/Discovery_ImplPlatform.cpp b/src/lib/dnssd/Discovery_ImplPlatform.cpp index 83b21cf8d3dab1..9851cbb20d173f 100644 --- a/src/lib/dnssd/Discovery_ImplPlatform.cpp +++ b/src/lib/dnssd/Discovery_ImplPlatform.cpp @@ -19,6 +19,7 @@ #include +#include #include #include #include @@ -28,7 +29,6 @@ #include #include #include -#include #include #include #include @@ -47,7 +47,9 @@ CHIP_ERROR DiscoveryImplPlatform::InitImpl() { ReturnErrorCodeIf(mDnssdInitialized, CHIP_NO_ERROR); ReturnErrorOnFailure(ChipDnssdInit(HandleDnssdInit, HandleDnssdError, this)); - mCommissionInstanceName = GetRandU64(); + + uint64_t random_instance_name = chip::Crypto::GetRandU64(); + memcpy(&mCommissionableInstanceName[0], &random_instance_name, sizeof(mCommissionableInstanceName)); return CHIP_NO_ERROR; } @@ -116,13 +118,9 @@ CHIP_ERROR DiscoveryImplPlatform::GetCommissionableInstanceName(char * instanceN { return CHIP_ERROR_NO_MEMORY; } - size_t len = snprintf(instanceName, maxLength, "%08" PRIX32 "%08" PRIX32, static_cast(mCommissionInstanceName >> 32), - static_cast(mCommissionInstanceName)); - if (len >= maxLength) - { - return CHIP_ERROR_NO_MEMORY; - } - return CHIP_NO_ERROR; + + return chip::Encoding::BytesToUppercaseHexString(&mCommissionableInstanceName[0], sizeof(mCommissionableInstanceName), + instanceName, maxLength); } template diff --git a/src/lib/dnssd/Discovery_ImplPlatform.h b/src/lib/dnssd/Discovery_ImplPlatform.h index e2f9d18fdd72b5..076052ab042bc2 100644 --- a/src/lib/dnssd/Discovery_ImplPlatform.h +++ b/src/lib/dnssd/Discovery_ImplPlatform.h @@ -81,7 +81,7 @@ class DiscoveryImplPlatform : public ServiceAdvertiser, public Resolver bool mIsOperationalPublishing = false; bool mIsCommissionableNodePublishing = false; bool mIsCommissionerPublishing = false; - uint64_t mCommissionInstanceName; + uint8_t mCommissionableInstanceName[sizeof(uint64_t)]; bool mDnssdInitialized = false; ResolverDelegate * mResolverDelegate = nullptr; diff --git a/src/lib/shell/commands/Base64.cpp b/src/lib/shell/commands/Base64.cpp index 52db7335b65788..40d4432640352a 100644 --- a/src/lib/shell/commands/Base64.cpp +++ b/src/lib/shell/commands/Base64.cpp @@ -28,7 +28,6 @@ #include #include #include -#include chip::Shell::Engine sShellBase64Commands; diff --git a/src/lib/support/BUILD.gn b/src/lib/support/BUILD.gn index 82e02fbdca8646..8d060acd1feff9 100644 --- a/src/lib/support/BUILD.gn +++ b/src/lib/support/BUILD.gn @@ -88,8 +88,6 @@ static_library("support") { "Pool.h", "PrivateHeap.cpp", "PrivateHeap.h", - "RandUtils.cpp", - "RandUtils.h", "ReferenceCountedHandle.h", "SafeInt.h", "SerializableIntegerSet.cpp", diff --git a/src/lib/support/RandUtils.cpp b/src/lib/support/RandUtils.cpp deleted file mode 100644 index ffa759bb7f1021..00000000000000 --- a/src/lib/support/RandUtils.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Copyright (c) 2020 Project CHIP Authors - * Copyright (c) 2013-2017 Nest Labs, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * This file implements utility functions for deriving random integers. - * - * @note These utility functions do not generate cryptographically strong - * random number. To get cryptographically strong random data use - * chip::Crypto::DRBG_get_bytes(). - * - */ - -#include "RandUtils.h" - -#include -#include -#include - -#ifndef __STDC_LIMIT_MACROS -#define __STDC_LIMIT_MACROS -#endif - -namespace chip { - -/** - * @def NORMALIZED_RAND_RANGE(reqRange) - * - * This macro calculates normalized range for the output of rand() function - * based on the requested random range [0, reqRange]. - * - * @note - * For most of the platforms we support, RAND_MAX is usually 0x7FFF or 0x7FFFFFFF. - * In these cases normalization for ranges [0, UINT8_MAX] or [0, UINT16_MAX] - * is not needed. - * - * @param[in] reqRange The requested random number range. - * - * @return normalized random range. - * - */ -#define NORMALIZED_RAND_RANGE(reqRange) (((reqRange) + 1) * ((RAND_MAX + 1) / ((reqRange) + 1))) - -#if RAND_MAX < UINT8_MAX -#error "RAND_MAX value is too small. RandUtils functions assume that RAND_MAX is greater or equal to UINT8_MAX." -#endif - -uint64_t GetRandU64() -{ - // rand() returns int, which is always smaller than the size of uint64_t - // and rand() cannot be used directly to generate random uint64_t number. - return static_cast(GetRandU32()) ^ (static_cast(GetRandU32()) << (sizeof(uint32_t) * CHAR_BIT)); -} - -uint32_t GetRandU32() -{ - // Check if (RAND_MAX == UINT32_MAX) but it is unlikely because rand() returns signed int, - // which maximum possible value is 0x7FFFFFFF (smaller that UINT32_MAX = 0xFFFFFFFF). -#if RAND_MAX == UINT32_MAX - return static_cast(rand()); -#else - return static_cast(GetRandU16()) ^ (static_cast(GetRandU16()) << (sizeof(uint16_t) * CHAR_BIT)); -#endif -} - -uint16_t GetRandU16() -{ -#if RAND_MAX >= UINT16_MAX -#if (RAND_MAX == INT_MAX) || (RAND_MAX == NORMALIZED_RAND_RANGE(UINT16_MAX)) - // rand() random output range normalization is not needed. - return static_cast(rand()); -#else - // Otherwise, Normilize the output range of rand() and reject rand() outputs outside of that range. - while (true) - { - int r = rand(); - if (r < NORMALIZED_RAND_RANGE(UINT16_MAX)) - return static_cast(r); - } -#endif -#else - return static_cast(GetRandU8()) ^ (static_cast(GetRandU8()) << CHAR_BIT); -#endif -} - -uint8_t GetRandU8() -{ -#if (RAND_MAX == INT_MAX) || (RAND_MAX == NORMALIZED_RAND_RANGE(UINT8_MAX)) - // rand() random output range normalization is not needed. - return static_cast(rand()); -#else - // Otherwise, Normilize the output range of rand() and reject rand() outputs outside of that range. - while (true) - { - int r = rand(); - if (r < NORMALIZED_RAND_RANGE(UINT8_MAX)) - return static_cast(r); - } -#endif -} - -} // namespace chip diff --git a/src/messaging/ExchangeMgr.cpp b/src/messaging/ExchangeMgr.cpp index 6cd46ac7baef51..3d1b17e42fcfa5 100644 --- a/src/messaging/ExchangeMgr.cpp +++ b/src/messaging/ExchangeMgr.cpp @@ -33,11 +33,11 @@ #include #include +#include #include #include #include #include -#include #include #include #include @@ -72,7 +72,7 @@ CHIP_ERROR ExchangeManager::Init(SessionManager * sessionManager) mSessionManager = sessionManager; - mNextExchangeId = GetRandU16(); + mNextExchangeId = chip::Crypto::GetRandU16(); mNextKeyId = 0; for (auto & handler : UMHandlerPool) diff --git a/src/setup_payload/QRCodeSetupPayloadGenerator.cpp b/src/setup_payload/QRCodeSetupPayloadGenerator.cpp index 09407bc11d1ab5..a81fabc6fad85b 100644 --- a/src/setup_payload/QRCodeSetupPayloadGenerator.cpp +++ b/src/setup_payload/QRCodeSetupPayloadGenerator.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include #include diff --git a/src/setup_payload/QRCodeSetupPayloadParser.cpp b/src/setup_payload/QRCodeSetupPayloadParser.cpp index 734346cbb1ca2b..71075cb58ca813 100644 --- a/src/setup_payload/QRCodeSetupPayloadParser.cpp +++ b/src/setup_payload/QRCodeSetupPayloadParser.cpp @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include diff --git a/src/setup_payload/SetupPayload.cpp b/src/setup_payload/SetupPayload.cpp index 4ffa4bd5f7bb56..b95877d2743724 100644 --- a/src/setup_payload/SetupPayload.cpp +++ b/src/setup_payload/SetupPayload.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include namespace chip { diff --git a/src/transport/MessageCounter.cpp b/src/transport/MessageCounter.cpp index 4f06b7c41c1193..10406e1999f563 100644 --- a/src/transport/MessageCounter.cpp +++ b/src/transport/MessageCounter.cpp @@ -22,12 +22,12 @@ #include -#include +#include #include namespace chip { -GlobalUnencryptedMessageCounter::GlobalUnencryptedMessageCounter() : value(GetRandU32()) {} +GlobalUnencryptedMessageCounter::GlobalUnencryptedMessageCounter() : value(Crypto::GetRandU32()) {} CHIP_ERROR GlobalEncryptedMessageCounter::Init() {