Skip to content

Commit e75990d

Browse files
committed
[all] Use crypto random interface to generate UUID
Signed-off-by: Mykhailo Lohvynenko <[email protected]>
1 parent 2db36c7 commit e75990d

File tree

13 files changed

+120
-33
lines changed

13 files changed

+120
-33
lines changed

include/aos/common/tools/uuid.hpp

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@
1111
#include "aos/common/config.hpp"
1212
#include "aos/common/tools/string.hpp"
1313

14+
namespace aos::crypto {
15+
class RandomItf;
16+
}
17+
1418
namespace aos::uuid {
1519

1620
/**
@@ -31,9 +35,9 @@ using UUID = StaticArray<uint8_t, cUUIDSize>;
3135
/**
3236
* Creates unique UUID.
3337
*
34-
* @return UUID.
38+
* @return RetWithError<UUID>.
3539
*/
36-
UUID CreateUUID();
40+
RetWithError<UUID> CreateUUID(class crypto::RandomItf& randomProvider);
3741

3842
/**
3943
* Converts UUID to string.

include/aos/iam/certmodules/pkcs11/pkcs11.hpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,10 +74,11 @@ class PKCS11Module : public HSMItf {
7474
* @param config module configuration.
7575
* @param pkcs11 reference to pkcs11 library context.
7676
* @param x509Provider reference to x509 crypto interface.
77+
* @param randomProvider reference to random crypto interface.
7778
* @return Error.
7879
*/
7980
Error Init(const String& certType, const PKCS11ModuleConfig& config, pkcs11::PKCS11Manager& pkcs11,
80-
crypto::x509::ProviderItf& x509Provider);
81+
crypto::x509::ProviderItf& x509Provider, crypto::RandomItf& randomProvider);
8182

8283
/**
8384
* Owns the module.
@@ -210,6 +211,7 @@ class PKCS11Module : public HSMItf {
210211

211212
SharedPtr<pkcs11::LibraryContext> mPKCS11;
212213
crypto::x509::ProviderItf* mX509Provider {};
214+
crypto::RandomItf* mRandomProvider {};
213215

214216
uint32_t mSlotID = 0;
215217
StaticString<pkcs11::cLabelLen> mTokenLabel;

include/aos/iam/permhandler.hpp

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,14 @@ class PermHandlerItf {
9494
*/
9595
class PermHandler : public PermHandlerItf {
9696
public:
97+
/**
98+
* Initializes object instance.
99+
*
100+
* @param randomProvider random provider.
101+
* @return Error.
102+
*/
103+
Error Init(crypto::RandomItf& randomProvider);
104+
97105
/**
98106
* Adds new service instance and its permissions into cache.
99107
*
@@ -129,11 +137,12 @@ class PermHandler : public PermHandlerItf {
129137
const Array<FunctionServicePermissions>& instancePermissions);
130138
InstancePermissions* FindBySecret(const String& secret);
131139
InstancePermissions* FindByInstanceIdent(const InstanceIdent& instanceIdent);
132-
StaticString<cSecretLen> GenerateSecret();
140+
RetWithError<StaticString<cSecretLen>> GenerateSecret();
133141
RetWithError<StaticString<cSecretLen>> GetSecretForInstance(const InstanceIdent& instanceIdent);
134142

135143
Mutex mMutex;
136144
StaticArray<InstancePermissions, cMaxNumInstances> mInstancesPerms;
145+
crypto::RandomItf* mRandomProvider {};
137146
};
138147

139148
/** @}*/

include/aos/sm/launcher.hpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
#include "aos/common/cloudprotocol/envvars.hpp"
1414
#include "aos/common/connectionsubsc.hpp"
15+
#include "aos/common/crypto/crypto.hpp"
1516
#include "aos/common/monitoring/monitoring.hpp"
1617
#include "aos/common/ocispec/ocispec.hpp"
1718
#include "aos/common/tools/list.hpp"
@@ -260,14 +261,16 @@ class Launcher : public LauncherItf,
260261
* @param statusReceiver status receiver instance.
261262
* @param connectionPublisher connection publisher instance.
262263
* @param storage storage instance.
264+
* @param randomProvider random provider instance.
263265
* @return Error.
264266
*/
265267
Error Init(const Config& config, iam::nodeinfoprovider::NodeInfoProviderItf& nodeInfoProvider,
266268
servicemanager::ServiceManagerItf& serviceManager, layermanager::LayerManagerItf& layerManager,
267269
resourcemanager::ResourceManagerItf& resourceManager, networkmanager::NetworkManagerItf& networkManager,
268270
iam::permhandler::PermHandlerItf& permHandler, runner::RunnerItf& runner, RuntimeItf& runtime,
269271
monitoring::ResourceMonitorItf& resourceMonitor, oci::OCISpecItf& ociManager,
270-
InstanceStatusReceiverItf& statusReceiver, ConnectionPublisherItf& connectionPublisher, StorageItf& storage);
272+
InstanceStatusReceiverItf& statusReceiver, ConnectionPublisherItf& connectionPublisher, StorageItf& storage,
273+
crypto::RandomItf& randomProvider);
271274

272275
/**
273276
* Starts launcher.
@@ -412,6 +415,7 @@ class Launcher : public LauncherItf,
412415
servicemanager::ServiceManagerItf* mServiceManager {};
413416
StorageItf* mStorage {};
414417
RuntimeItf* mRuntime {};
418+
crypto::RandomItf* mRandomProvider {};
415419

416420
mutable StaticAllocator<cAllocatorSize> mAllocator;
417421

src/common/tools/uuid.cpp

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <stdlib.h>
99
#include <time.h>
1010

11+
#include "aos/common/crypto/crypto.hpp"
1112
#include "aos/common/tools/uuid.hpp"
1213

1314
namespace aos::uuid {
@@ -16,13 +17,17 @@ namespace aos::uuid {
1617
static const String cTemplate = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
1718
static const String cEmptyUUID = "00000000-0000-0000-0000-000000000000";
1819

19-
UUID CreateUUID()
20+
RetWithError<UUID> CreateUUID(crypto::RandomItf& randomProvider)
2021
{
2122
UUID result;
2223

2324
while (result.Size() < result.MaxSize()) {
24-
unsigned value = rand();
25-
auto chunk = Array<uint8_t>(reinterpret_cast<uint8_t*>(&value), sizeof(value));
25+
auto [value, err] = randomProvider.RandInt(RAND_MAX);
26+
if (!err.IsNone()) {
27+
return {{}, err};
28+
}
29+
30+
auto chunk = Array<uint8_t>(reinterpret_cast<uint8_t*>(&value), sizeof(value));
2631

2732
auto chunkSize = Min(result.MaxSize() - result.Size(), chunk.Size());
2833

src/iam/certmodules/pkcs11/pkcs11.cpp

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ namespace aos::iam::certhandler {
2121
**********************************************************************************************************************/
2222

2323
Error PKCS11Module::Init(const String& certType, const PKCS11ModuleConfig& config, pkcs11::PKCS11Manager& pkcs11,
24-
crypto::x509::ProviderItf& x509Provider)
24+
crypto::x509::ProviderItf& x509Provider, crypto::RandomItf& randomProvider)
2525
{
26-
mCertType = certType;
27-
mConfig = config;
28-
mX509Provider = &x509Provider;
26+
mCertType = certType;
27+
mConfig = config;
28+
mX509Provider = &x509Provider;
29+
mRandomProvider = &randomProvider;
2930

3031
mPKCS11 = pkcs11.OpenLibrary(mConfig.mLibrary);
3132
if (!mPKCS11) {
@@ -198,7 +199,10 @@ RetWithError<SharedPtr<crypto::PrivateKeyItf>> PKCS11Module::CreateKey(const Str
198199
PKCS11Module::PendingKey pendingKey;
199200
Error err = ErrorEnum::eNone;
200201

201-
pendingKey.mUUID = uuid::CreateUUID();
202+
Tie(pendingKey.mUUID, err) = uuid::CreateUUID(*mRandomProvider);
203+
if (!err.IsNone()) {
204+
return {nullptr, AOS_ERROR_WRAP(err)};
205+
}
202206

203207
SharedPtr<pkcs11::SessionContext> session;
204208

@@ -787,7 +791,10 @@ Error PKCS11Module::CreateCertificateChain(const SharedPtr<pkcs11::SessionContex
787791
continue;
788792
}
789793

790-
auto uuid = uuid::CreateUUID();
794+
auto [uuid, errUUID] = uuid::CreateUUID(*mRandomProvider);
795+
if (!errUUID.IsNone()) {
796+
return AOS_ERROR_WRAP(errUUID);
797+
}
791798

792799
LOG_DBG() << "Import root certificate with id: " << aos::uuid::UUIDToString(uuid);
793800

src/iam/permhandler/permhandler.cpp

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77

88
#include "aos/iam/permhandler.hpp"
9+
#include "aos/common/crypto/utils.hpp"
910
#include "aos/common/tools/uuid.hpp"
1011
#include "log.hpp"
1112

@@ -15,6 +16,15 @@ namespace aos::iam::permhandler {
1516
* Public
1617
**********************************************************************************************************************/
1718

19+
Error PermHandler::Init(crypto::RandomItf& randomProvider)
20+
{
21+
LOG_DBG() << "Init perm handler";
22+
23+
mRandomProvider = &randomProvider;
24+
25+
return ErrorEnum::eNone;
26+
}
27+
1828
RetWithError<StaticString<cSecretLen>> PermHandler::RegisterInstance(
1929
const InstanceIdent& instanceIdent, const Array<FunctionServicePermissions>& instancePermissions)
2030
{
@@ -30,7 +40,10 @@ RetWithError<StaticString<cSecretLen>> PermHandler::RegisterInstance(
3040
return {secret};
3141
}
3242

33-
secret = GenerateSecret();
43+
Tie(secret, err) = GenerateSecret();
44+
if (!err.IsNone()) {
45+
return {{}, AOS_ERROR_WRAP(err)};
46+
}
3447

3548
err = AddSecret(secret, instanceIdent, instancePermissions);
3649
if (!err.IsNone()) {
@@ -108,16 +121,18 @@ InstancePermissions* PermHandler::FindByInstanceIdent(const InstanceIdent& insta
108121
return mInstancesPerms.FindIf([&instanceIdent](const auto& elem) { return instanceIdent == elem.mInstanceIdent; });
109122
}
110123

111-
StaticString<cSecretLen> PermHandler::GenerateSecret()
124+
RetWithError<StaticString<cSecretLen>> PermHandler::GenerateSecret()
112125
{
113-
StaticString<cSecretLen> newSecret;
114-
115-
do {
116-
newSecret = uuid::UUIDToString(uuid::CreateUUID());
126+
if (!mRandomProvider) {
127+
return {{}, AOS_ERROR_WRAP(ErrorEnum::eWrongState)};
128+
}
117129

118-
} while (FindBySecret(newSecret) != mInstancesPerms.end());
130+
auto [uuid, err] = uuid::CreateUUID(*mRandomProvider);
131+
if (!err.IsNone()) {
132+
return {{}, AOS_ERROR_WRAP(err)};
133+
}
119134

120-
return newSecret;
135+
return StaticString<cSecretLen>(uuid::UUIDToString(uuid));
121136
}
122137

123138
RetWithError<StaticString<cSecretLen>> PermHandler::GetSecretForInstance(const InstanceIdent& instanceIdent)

src/sm/launcher/launcher.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ Error Launcher::Init(const Config& config, iam::nodeinfoprovider::NodeInfoProvid
3232
resourcemanager::ResourceManagerItf& resourceManager, networkmanager::NetworkManagerItf& networkManager,
3333
iam::permhandler::PermHandlerItf& permHandler, runner::RunnerItf& runner, RuntimeItf& runtime,
3434
monitoring::ResourceMonitorItf& resourceMonitor, oci::OCISpecItf& ociManager,
35-
InstanceStatusReceiverItf& statusReceiver, ConnectionPublisherItf& connectionPublisher, StorageItf& storage)
35+
InstanceStatusReceiverItf& statusReceiver, ConnectionPublisherItf& connectionPublisher, StorageItf& storage,
36+
crypto::RandomItf& randomProvider)
3637
{
3738
LOG_DBG() << "Init launcher";
3839

@@ -49,6 +50,7 @@ Error Launcher::Init(const Config& config, iam::nodeinfoprovider::NodeInfoProvid
4950
mServiceManager = &serviceManager;
5051
mStatusReceiver = &statusReceiver;
5152
mStorage = &storage;
53+
mRandomProvider = &randomProvider;
5254

5355
Error err;
5456

@@ -589,7 +591,12 @@ Error Launcher::GetDesiredInstancesData(
589591
return instance.mInstanceInfo.mInstanceIdent == instanceInfo.mInstanceIdent;
590592
});
591593
if (currentInstance == currentInstances->end()) {
592-
const auto instanceID = uuid::UUIDToString(uuid::CreateUUID());
594+
auto [uuid, err] = uuid::CreateUUID(*mRandomProvider);
595+
if (!err.IsNone()) {
596+
return AOS_ERROR_WRAP(err);
597+
}
598+
599+
auto instanceID = uuid::UUIDToString(uuid);
593600

594601
if (auto err = desiredInstancesData.EmplaceBack(instanceInfo, instanceID); !err.IsNone()) {
595602
return AOS_ERROR_WRAP(err);

tests/common/src/tools/uuid_test.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,29 @@
1111
#include <gtest/gtest.h>
1212

1313
#include "aos/common/tools/uuid.hpp"
14+
#include "mocks/cryptomock.hpp"
1415

1516
namespace aos::uuid {
1617

1718
TEST(UUIDTest, CreateUUID)
1819
{
1920
static constexpr auto cTestUUIDsCount = 1000;
2021

22+
crypto::RandomMock randomProvider;
23+
2124
std::vector<UUID> uuids;
2225

2326
for (int i = 0; i < cTestUUIDsCount; i++) {
24-
auto tmp = CreateUUID();
27+
EXPECT_CALL(randomProvider, RandInt).WillRepeatedly(testing::Invoke([]() { return rand(); }));
28+
auto [uuid, err] = CreateUUID(randomProvider);
29+
30+
ASSERT_TRUE(err.IsNone());
2531

26-
ASSERT_EQ(tmp.Size(), tmp.MaxSize());
32+
ASSERT_EQ(uuid.Size(), uuid.MaxSize());
2733

28-
ASSERT_EQ(std::find(uuids.begin(), uuids.end(), tmp), uuids.end());
34+
ASSERT_EQ(std::find(uuids.begin(), uuids.end(), uuid), uuids.end());
2935

30-
uuids.push_back(tmp);
36+
uuids.push_back(uuid);
3137
}
3238
}
3339

tests/iam/iam_test.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class IAMTest : public Test {
3131

3232
ASSERT_TRUE(mCryptoFactory.Init().IsNone());
3333
mCryptoProvider = &mCryptoFactory.GetCryptoProvider();
34+
mRandomProvider = &mCryptoFactory.GetRandomProvider();
3435

3536
mCertHandler = MakeShared<CertHandler>(&mAllocator);
3637
ASSERT_TRUE(mSOFTHSMEnv.Init("", "certhanler-integr-tests").IsNone());
@@ -51,7 +52,9 @@ class IAMTest : public Test {
5152
auto& certModule = mCertModules.Back();
5253

5354
ASSERT_TRUE(
54-
pkcs11Module.Init(name, GetPKCS11ModuleConfig(), mSOFTHSMEnv.GetManager(), *mCryptoProvider).IsNone());
55+
pkcs11Module
56+
.Init(name, GetPKCS11ModuleConfig(), mSOFTHSMEnv.GetManager(), *mCryptoProvider, *mRandomProvider)
57+
.IsNone());
5558
ASSERT_TRUE(
5659
certModule.Init(name, GetCertModuleConfig(keyType, isSelfSigned), *mCryptoProvider, pkcs11Module, mStorage)
5760
.IsNone());
@@ -91,6 +94,7 @@ class IAMTest : public Test {
9194
// Service providers
9295
crypto::DefaultCryptoFactory mCryptoFactory;
9396
crypto::x509::ProviderItf* mCryptoProvider = nullptr;
97+
crypto::RandomItf* mRandomProvider = nullptr;
9498
test::SoftHSMEnv mSOFTHSMEnv;
9599
StorageStub mStorage;
96100

0 commit comments

Comments
 (0)