Skip to content

Commit 012006b

Browse files
Control: Add support for HSM
Add dycrypt and encrypt support Co-authored-by: Tehila Aharonovich <[email protected]>
1 parent 0dc7c01 commit 012006b

File tree

11 files changed

+232
-41
lines changed

11 files changed

+232
-41
lines changed

control/CMakeLists.txt

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ include_directories(${BSON_INCLUDE_DIRS})
1818
file(GLOB SOURCES "src/*.cpp")
1919
list(REMOVE_ITEM SOURCES "${CMAKE_SOURCE_DIR}/src/main.cpp")
2020

21+
# Path to local communication directory
22+
2123
file(GLOB SOURCES_COMMUNICATION "../communication/src/*.cpp")
2224
file(GLOB HEADERS_COMMUNICATION "../communication/include/*.h")
2325
file(GLOB SOCKETS_COMMUNICATIONS "../communication/sockets/*.*" )
@@ -27,12 +29,25 @@ file(GLOB PARSER "../parser_json/src/*.*")
2729
file(GLOB LOGGER "../logger/*.*")
2830

2931
# Main executable
30-
add_executable(${PROJECT_NAME} ${SOURCES} ${PARSER} ${SOURCES_COMMUNICATION} ${HEADERS_COMMUNICATION} ${SOCKETS_COMMUNICATIONS} ${LOGGER} src/main.cpp)
32+
add_executable(${PROJECT_NAME} ${SOURCES} ${PARSER} ${SOURCES_COMMUNICATION} ${HEADERS_COMMUNICATION} ${SOCKETS_COMMUNICATIONS} ${LOGGER} src/main.cpp )
3133
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_SOURCE_DIR}/include)
32-
target_link_libraries(${PROJECT_NAME} PRIVATE ${BSON_LIBRARIES})
34+
target_link_libraries(${PROJECT_NAME} PRIVATE ${BSON_LIBRARIES} )
3335

3436
# Test executable, including additional source files
3537
file(GLOB TEST_SOURCES "test/*.cpp")
36-
add_executable(RunTests ${SOURCES} ${PARSER} ${SOURCES_COMMUNICATION} ${HEADERS_COMMUNICATION} ${SOCKETS_COMMUNICATIONS} ${LOGGER} ${TEST_SOURCES})
38+
add_executable(RunTests ${SOURCES} ${PARSER} ${SOURCES_COMMUNICATION} ${HEADERS_COMMUNICATION} ${SOCKETS_COMMUNICATIONS} ${LOGGER} ${TEST_SOURCES} )
3739
target_include_directories(RunTests PRIVATE ${CMAKE_SOURCE_DIR}/include)
38-
target_link_libraries(RunTests PRIVATE ${BSON_LIBRARIES} ${GTEST_LIBRARIES} pthread)
40+
target_link_libraries(RunTests PRIVATE ${BSON_LIBRARIES} ${GTEST_LIBRARIES} pthread)
41+
42+
43+
include(../hsm-client/use_hsm_client.cmake)
44+
find_library(HSM_CLIENT_LIB hsm_client_lib PATHS ${HSM_CLIENT_LIB_PATH})
45+
if(HSM_CLIENT_LIB)
46+
message(STATUS "Found hsm_client_lib: ${HSM_CLIENT_LIB}")
47+
target_link_libraries(${PROJECT_NAME} PRIVATE ${HSM_CLIENT_LIB} ${HSM_CLIENT_LIB_DEPS})
48+
target_link_libraries(RunTests PRIVATE ${HSM_CLIENT_LIB} ${HSM_CLIENT_LIB_DEPS})
49+
target_include_directories(${PROJECT_NAME} PRIVATE ${HSM_CLIENT_INCLUDE_DIRS})
50+
target_include_directories(RunTests PRIVATE ${HSM_CLIENT_INCLUDE_DIRS})
51+
else()
52+
message(FATAL_ERROR "Could not find hsm_client_lib at ${HSM_CLIENT_LIB_PATH}")
53+
endif()

control/camera.json

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
{
2+
"endianness": "little",
3+
"fields": [
4+
{
5+
"fields": [
6+
{
7+
"name": "MessageType",
8+
"size": 1,
9+
"type": "unsigned_int",
10+
"defaultValue": 1
11+
},
12+
{
13+
"name": "Level",
14+
"size": 3,
15+
"type": "unsigned_int",
16+
"defaultValue": 1
17+
},
18+
{
19+
"name": "ObjectType",
20+
"size": 4,
21+
"type": "unsigned_int",
22+
"defaultValue": 1
23+
}
24+
],
25+
"name": "AlertDetails",
26+
"size": 8,
27+
"type": "bit_field"
28+
},
29+
{
30+
"name": "ObjectDistance",
31+
"size": 32,
32+
"type": "float_fixed",
33+
"defaultValue": 100.0
34+
},
35+
{
36+
"name": "CarSpeed",
37+
"size": 32,
38+
"type": "unsigned_int",
39+
"defaultValue": 100
40+
},
41+
{
42+
"name": "ObjectSpeed",
43+
"size": 32,
44+
"type": "unsigned_int",
45+
"defaultValue": 100
46+
}
47+
]
48+
}

control/include/full_condition.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include "basic_condition.h"
1515
#include "root.h"
1616
#include "condition_factory.h"
17+
#include "hsm_support.h"
1718

1819
class Root;
1920

control/include/global_properties.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
#include "input.h"
1414
#include "full_condition.h"
1515
#include "sensor.h"
16+
#include "crypto_api.h"
17+
#include "hsm_support.h"
1618

1719
#include "../../communication/include/communication.h"
1820
#include "../../logger/logger.h"
@@ -23,6 +25,8 @@ class FullCondition;
2325
// Forward declaration instead of #include
2426
class Sensor;
2527

28+
#define BITS_IN_BYTE 8
29+
2630
// Singleton class managing global properties
2731
class GlobalProperties {
2832
private:
@@ -48,6 +52,8 @@ class GlobalProperties {
4852
uint32_t srcID = 1;
4953
// Creating the communication object with the callback function to process the data
5054
Communication *comm;
55+
56+
CryptoClient client;
5157

5258
static logger controlLogger;
5359
};

control/include/hsm_support.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#ifndef __HSM_SUPPORT__
2+
#define __HSM_SUPPORT__
3+
4+
#include "global_properties.h"
5+
6+
bool decryptData(void *data, int dataLen, uint32_t senderId);
7+
8+
bool encryptData(const void *data, int dataLen, uint8_t *encryptedData,
9+
size_t encryptedLength, uint32_t receiverId);
10+
11+
#endif // __HSM_SUPPORT__

control/include/sensor.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ class Sensor {
2323
std::string name;
2424
PacketParser *parser;
2525
std::map<std::string, Field> fieldsMap;
26+
int msgLength;
27+
bool isUsingHSM;
2628

2729
// Variables for the timer functions
2830
int timeForUpdate;

control/src/full_condition.cpp

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,23 @@ void defineCurrentSensor(const string &condition, int &index)
2222
index = closeBracket + 1;
2323
currentSensor = instanceGP.sensors[id];
2424

25-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "The current sensor id is: " + to_string(currentSensor->id));
25+
GlobalProperties::controlLogger.logMessage(
26+
logger::LogLevel::DEBUG,
27+
"The current sensor id is: " + to_string(currentSensor->id));
2628
}
2729

2830
// Recursively builds the condition tree from the condition string.
2931
Condition *FullCondition::buildNode(const string &condition, int &index,
3032
map<int, int> bracketIndexes)
3133
{
32-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "Entering buildNode function, condition[index] = " + condition[index]);
34+
GlobalProperties::controlLogger.logMessage(
35+
logger::LogLevel::DEBUG,
36+
"Entering buildNode function, condition[index] = " + condition[index]);
3337
GlobalProperties &instanceGP = GlobalProperties::getInstance();
3438

3539
if (condition.empty())
36-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::ERROR, "Condition string is empty");
40+
GlobalProperties::controlLogger.logMessage(logger::LogLevel::ERROR,
41+
"Condition string is empty");
3742

3843
// Handling sensor reference
3944
if (condition[index] == '[')
@@ -48,11 +53,13 @@ Condition *FullCondition::buildNode(const string &condition, int &index,
4853
(currentSensor ? to_string(currentSensor->id) : "-") +
4954
condition.substr(index, bracketIndexes[openBracketIndex] - index + 1);
5055

51-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "Generated condition key: " + key);
56+
GlobalProperties::controlLogger.logMessage(
57+
logger::LogLevel::DEBUG, "Generated condition key: " + key);
5258

5359
// Check if the key already exists in the existingConditions map
5460
if (s_existingConditions.find(key) != s_existingConditions.end()) {
55-
instanceGP.controlLogger.logMessage(logger::LogLevel::DEBUG, "Condition key already exists: " + key);
61+
instanceGP.controlLogger.logMessage(
62+
logger::LogLevel::DEBUG, "Condition key already exists: " + key);
5663

5764
index = bracketIndexes[openBracketIndex] + 1;
5865
if (condition[index] == ',')
@@ -65,7 +72,9 @@ Condition *FullCondition::buildNode(const string &condition, int &index,
6572
OperatorTypes operatorType = convertStringToOperatorTypes(
6673
condition.substr(index, openBracketIndex - index));
6774

68-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "Operator type: " + std::to_string(operatorType));
75+
GlobalProperties::controlLogger.logMessage(
76+
logger::LogLevel::DEBUG,
77+
"Operator type: " + std::to_string(operatorType));
6978

7079
Condition *conditionPtr = createCondition(operatorType);
7180

@@ -111,7 +120,8 @@ Condition *FullCondition::buildNode(const string &condition, int &index,
111120
string name = condition.substr(openBracketIndex + 1,
112121
commaIndex - openBracketIndex - 1);
113122

114-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "Field name: " + name);
123+
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG,
124+
"Field name: " + name);
115125

116126
int closeBracket = bracketIndexes[openBracketIndex];
117127

@@ -139,7 +149,8 @@ Condition *FullCondition::buildNode(const string &condition, int &index,
139149
// Maps the positions of opening bracket indexes to their corresponding closing bracket indexes
140150
map<int, int> findBrackets(string condition)
141151
{
142-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "Generate a map with the brackets indexes");
152+
GlobalProperties::controlLogger.logMessage(
153+
logger::LogLevel::DEBUG, "Generate a map with the brackets indexes");
143154
map<int, int> mapIndexes;
144155
stack<int> stackIndexes;
145156
// Scans the input string for brackets and uses a stack to keep track of their positions
@@ -172,7 +183,8 @@ FullCondition::FullCondition(string condition,
172183
this->buildNode(condition, index, bracketsIndexes);
173184
root = new Root(this->id, firstCondition);
174185

175-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::DEBUG, "The tree created successfully ");
186+
GlobalProperties::controlLogger.logMessage(
187+
logger::LogLevel::DEBUG, "The tree created successfully ");
176188

177189
firstCondition->parents.push_back(root);
178190
currentSensor = nullptr;
@@ -188,7 +200,26 @@ void FullCondition::activateActions()
188200
const char *message = action.second.c_str();
189201
size_t dataSize = strlen(message) + 1;
190202
uint32_t destID = action.first;
191-
instanceGP.comm->sendMessage((void *)message, dataSize, destID,
192-
instanceGP.srcID, false);
203+
204+
if (instanceGP.sensors[destID]->isUsingHSM){
205+
// Get the length of the encrypted data
206+
size_t encryptedLength =
207+
instanceGP.client.getEncryptedLen(instanceGP.srcID, dataSize);
208+
uint8_t encryptedData[encryptedLength];
209+
210+
if (encryptData((const void *)message, dataSize, encryptedData,
211+
encryptedLength, destID))
212+
instanceGP.controlLogger.logMessage(
213+
logger::LogLevel::INFO, "The message encrypted successfully");
214+
else
215+
instanceGP.controlLogger.logMessage(
216+
logger::LogLevel::ERROR, "The message encryption failed");
217+
218+
instanceGP.comm->sendMessage(encryptedData, encryptedLength, destID,
219+
instanceGP.srcID, false);
220+
}
221+
else
222+
instanceGP.comm->sendMessage((void*)message, dataSize, destID,
223+
instanceGP.srcID, false);
193224
}
194225
}

control/src/global_properties.cpp

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,28 @@
11
#include "global_properties.h"
22
using namespace std;
33

4-
void handleMesseage(uint32_t senderId,void *data)
4+
5+
void handleMesseage(uint32_t senderId, void *data)
56
{
67
GlobalProperties &instanceGP = GlobalProperties::getInstance();
78

89
GlobalProperties::controlLogger.logMessage(logger::LogLevel::INFO, "Received message from id " + senderId);
910

10-
char * msg = "I got message";
11+
const char *msg = "I got message";
1112
size_t dataSize = strlen(msg) + 1;
12-
instanceGP.comm->sendMessage((void*)msg, dataSize, senderId, instanceGP.srcID, false);
13+
// instanceGP.comm->sendMessage((void *)msg, dataSize, senderId,
14+
// instanceGP.srcID, false);
15+
16+
if (decryptData(data, instanceGP.sensors[senderId]->msgLength / BITS_IN_BYTE, senderId)){
17+
instanceGP.controlLogger.logMessage(
18+
logger::LogLevel::INFO, "The message dycrypted successfully");
19+
instanceGP.sensors[senderId]->isUsingHSM = true;
20+
}
21+
else {
22+
instanceGP.controlLogger.logMessage(logger::LogLevel::ERROR,
23+
"The message dycryption failed");
24+
}
25+
1326
instanceGP.sensors[senderId]->handleMessage(data);
1427

1528
for (int cId : instanceGP.trueConditions)
@@ -25,30 +38,35 @@ int readIdFromJson()
2538

2639
// Check if the input is correct
2740
if (!f.is_open())
28-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::ERROR, "Failed to open config.json");
41+
GlobalProperties::controlLogger.logMessage(
42+
logger::LogLevel::ERROR, "Failed to open config.json");
2943
json *data = NULL;
3044

3145
// Try parse to json type
3246
try {
3347
data = new json(json::parse(f));
3448
f.close();
35-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::INFO, "The id was successfully read from config.json");
49+
GlobalProperties::controlLogger.logMessage(
50+
logger::LogLevel::INFO,
51+
"The id was successfully read from config.json");
3652
}
3753
catch (exception e) {
38-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::ERROR, e.what());
54+
GlobalProperties::controlLogger.logMessage(logger::LogLevel::ERROR,
55+
e.what());
3956
}
4057

4158
return (*data)["ID"];
4259
}
4360

4461
// Initializes the sensors based on a JSON file
45-
GlobalProperties::GlobalProperties()
62+
GlobalProperties::GlobalProperties() : client(srcID)
4663
{
4764
controlLogger.logMessage(logger::LogLevel::INFO, "Initializing...");
48-
65+
4966
// Build the sensors according the json file
5067
Input::s_buildSensors(sensors);
51-
controlLogger.logMessage(logger::LogLevel::INFO, "Sensors built successfully");
68+
controlLogger.logMessage(logger::LogLevel::INFO,
69+
"Sensors built successfully");
5270

5371
srcID = readIdFromJson();
5472
// Creating the communication object with the callback function to process the data

control/src/hsm_support.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include "hsm_support.h"
2+
3+
bool decryptData(void *data, int dataLen, uint32_t senderId)
4+
{
5+
GlobalProperties &instanceGP = GlobalProperties::getInstance();
6+
7+
size_t encryptedLength =
8+
instanceGP.client.getEncryptedLen(senderId, dataLen);
9+
size_t decryptedLength =
10+
instanceGP.client.getEncryptedLen(senderId, encryptedLength);
11+
12+
uint8_t decryptedData[decryptedLength];
13+
14+
CK_RV decryptResult = instanceGP.client.decrypt(
15+
senderId, data, encryptedLength, decryptedData, decryptedLength);
16+
17+
if (decryptResult != CKR_OK || decryptedLength != dataLen)
18+
return false;
19+
20+
memcpy(data, decryptedData, decryptedLength);
21+
return true;
22+
}
23+
24+
bool encryptData(const void *data, int dataLen, uint8_t *encryptedData,
25+
size_t encryptedLength, uint32_t receiverId)
26+
{
27+
GlobalProperties &instanceGP = GlobalProperties::getInstance();
28+
29+
// Encrypt the data
30+
CK_RV encryptResult = instanceGP.client.encrypt(
31+
receiverId, data, dataLen, encryptedData, encryptedLength);
32+
// Check if encryption was successful
33+
if (encryptResult != CKR_OK)
34+
return false;
35+
return true;
36+
}

control/src/main.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
#include "input.h"
55
#include "full_condition.h"
66
#include "global_properties.h"
7-
// #include "../parser_json/src/packet_parser.h"
7+
88
using namespace std;
99

1010
int main()
@@ -13,7 +13,9 @@ int main()
1313
// Build the conditions from the bson file
1414
Input::s_buildConditions();
1515

16-
GlobalProperties::controlLogger.logMessage(logger::LogLevel::INFO, "Initialized successfully, Starting Communication...");
16+
GlobalProperties::controlLogger.logMessage(
17+
logger::LogLevel::INFO,
18+
"Initialized successfully, Starting Communication...");
1719
// Starting communication with the server
1820
instanceGP.comm->startConnection();
1921

0 commit comments

Comments
 (0)