diff --git a/examples/C++/Benchmark/BenchmarkPubSubTypes.cxx b/examples/C++/Benchmark/BenchmarkPubSubTypes.cxx index 277ee04b6c7..5d30198dd51 100644 --- a/examples/C++/Benchmark/BenchmarkPubSubTypes.cxx +++ b/examples/C++/Benchmark/BenchmarkPubSubTypes.cxx @@ -98,14 +98,14 @@ void BenchMarkPubSubType::deleteData(void* data) { delete((BenchMark*)data); } -bool BenchMarkPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool BenchMarkPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; BenchMark* p_type = (BenchMark*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,BenchMark::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(BenchMark::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || BenchMark::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Benchmark/BenchmarkPubSubTypes.h b/examples/C++/Benchmark/BenchmarkPubSubTypes.h index b28784e71d3..6352dcc6fcf 100644 --- a/examples/C++/Benchmark/BenchmarkPubSubTypes.h +++ b/examples/C++/Benchmark/BenchmarkPubSubTypes.h @@ -40,7 +40,7 @@ class BenchMarkPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5=false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/Benchmark/Benchmark_bigPubSubTypes.cxx b/examples/C++/Benchmark/Benchmark_bigPubSubTypes.cxx index 594caa1c4bc..b5802a64fb9 100644 --- a/examples/C++/Benchmark/Benchmark_bigPubSubTypes.cxx +++ b/examples/C++/Benchmark/Benchmark_bigPubSubTypes.cxx @@ -98,14 +98,14 @@ void BenchMarkBigPubSubType::deleteData(void* data) { delete((BenchMarkBig*)data); } -bool BenchMarkBigPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool BenchMarkBigPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; BenchMarkBig* p_type = (BenchMarkBig*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,BenchMarkBig::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(BenchMarkBig::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || BenchMarkBig::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Benchmark/Benchmark_bigPubSubTypes.h b/examples/C++/Benchmark/Benchmark_bigPubSubTypes.h index 2a4e2fe91a9..9788dc1b309 100644 --- a/examples/C++/Benchmark/Benchmark_bigPubSubTypes.h +++ b/examples/C++/Benchmark/Benchmark_bigPubSubTypes.h @@ -40,7 +40,7 @@ class BenchMarkBigPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5=false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.cxx b/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.cxx index 5bbf496a16d..74684ef8cb0 100644 --- a/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.cxx +++ b/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.cxx @@ -98,14 +98,14 @@ void BenchMarkMediumPubSubType::deleteData(void* data) { delete((BenchMarkMedium*)data); } -bool BenchMarkMediumPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool BenchMarkMediumPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; BenchMarkMedium* p_type = (BenchMarkMedium*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,BenchMarkMedium::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(BenchMarkMedium::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || BenchMarkMedium::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.h b/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.h index 7068b7412ed..1a340c3b8db 100644 --- a/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.h +++ b/examples/C++/Benchmark/Benchmark_mediumPubSubTypes.h @@ -40,7 +40,7 @@ class BenchMarkMediumPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5=false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/Benchmark/Benchmark_smallPubSubTypes.cxx b/examples/C++/Benchmark/Benchmark_smallPubSubTypes.cxx index a65706bb164..3e7625ff4b2 100644 --- a/examples/C++/Benchmark/Benchmark_smallPubSubTypes.cxx +++ b/examples/C++/Benchmark/Benchmark_smallPubSubTypes.cxx @@ -98,14 +98,14 @@ void BenchMarkSmallPubSubType::deleteData(void* data) { delete((BenchMarkSmall*)data); } -bool BenchMarkSmallPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool BenchMarkSmallPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; BenchMarkSmall* p_type = (BenchMarkSmall*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,BenchMarkSmall::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(BenchMarkSmall::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || BenchMarkSmall::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Benchmark/Benchmark_smallPubSubTypes.h b/examples/C++/Benchmark/Benchmark_smallPubSubTypes.h index 700b6091116..35e99c54bb4 100644 --- a/examples/C++/Benchmark/Benchmark_smallPubSubTypes.h +++ b/examples/C++/Benchmark/Benchmark_smallPubSubTypes.h @@ -40,7 +40,7 @@ class BenchMarkSmallPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5=false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/ClientServerTest/ClientServerTypes.h b/examples/C++/ClientServerTest/ClientServerTypes.h index 701142d4116..d6a82bc7dd5 100644 --- a/examples/C++/ClientServerTest/ClientServerTypes.h +++ b/examples/C++/ClientServerTest/ClientServerTypes.h @@ -57,6 +57,8 @@ class OperationDataType:public eprosima::fastrtps::TopicDataType bool serialize(void*data, eprosima::fastrtps::rtps::SerializedPayload_t* payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t* payload,void * data); std::function getSerializedSizeProvider(void* data); + bool getKey(void*, eprosima::fastrtps::rtps::InstanceHandle_t*, bool) { return false; } + void* createData(); void deleteData(void* data); }; @@ -93,6 +95,7 @@ class ResultDataType:public eprosima::fastrtps::TopicDataType bool serialize(void*data, eprosima::fastrtps::rtps::SerializedPayload_t* payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t* payload,void * data); std::function getSerializedSizeProvider(void* data); + bool getKey(void*, eprosima::fastrtps::rtps::InstanceHandle_t*, bool) { return false; } void* createData(); void deleteData(void* data); }; diff --git a/examples/C++/Configurability/samplePubSubTypes.cxx b/examples/C++/Configurability/samplePubSubTypes.cxx index d856f924226..e35aae24735 100644 --- a/examples/C++/Configurability/samplePubSubTypes.cxx +++ b/examples/C++/Configurability/samplePubSubTypes.cxx @@ -96,14 +96,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Configurability/samplePubSubTypes.h b/examples/C++/Configurability/samplePubSubTypes.h index 7dc0a55c5fc..ded921770c8 100644 --- a/examples/C++/Configurability/samplePubSubTypes.h +++ b/examples/C++/Configurability/samplePubSubTypes.h @@ -40,7 +40,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.cxx b/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.cxx index 03c03a1fe6c..437cf3065b0 100644 --- a/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.cxx +++ b/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.cxx @@ -97,14 +97,14 @@ void HelloMsgPubSubType::deleteData(void* data) { delete((HelloMsg*)data); } -bool HelloMsgPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool HelloMsgPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; HelloMsg* p_type = (HelloMsg*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,HelloMsg::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(HelloMsg::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || HelloMsg::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.h b/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.h index cdf1c5f6636..362891d94f2 100644 --- a/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.h +++ b/examples/C++/DeadlineQoSExample/deadlinepayloadPubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file deadlinepayloadPubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -40,7 +40,7 @@ class HelloMsgPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/Filtering/FilteringExamplePubSubTypes.cxx b/examples/C++/Filtering/FilteringExamplePubSubTypes.cxx index 36c43ae6acd..63c96c17d65 100644 --- a/examples/C++/Filtering/FilteringExamplePubSubTypes.cxx +++ b/examples/C++/Filtering/FilteringExamplePubSubTypes.cxx @@ -97,14 +97,14 @@ void FilteringExamplePubSubType::deleteData(void* data) { delete((FilteringExample*)data); } -bool FilteringExamplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool FilteringExamplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; FilteringExample* p_type = (FilteringExample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,FilteringExample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(FilteringExample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || FilteringExample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Filtering/FilteringExamplePubSubTypes.h b/examples/C++/Filtering/FilteringExamplePubSubTypes.h index 439c362c5fe..3d3cb2eb527 100644 --- a/examples/C++/Filtering/FilteringExamplePubSubTypes.h +++ b/examples/C++/Filtering/FilteringExamplePubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file FilteringExamplePubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -42,7 +42,7 @@ class FilteringExamplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.cxx b/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.cxx index 5000ca7dc45..0c5feaf32c5 100644 --- a/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.cxx +++ b/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.cxx @@ -95,14 +95,14 @@ void FlowControlExamplePubSubType::deleteData(void* data) { delete((FlowControlExample*)data); } -bool FlowControlExamplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool FlowControlExamplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; FlowControlExample* p_type = (FlowControlExample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,FlowControlExample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(FlowControlExample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || FlowControlExample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.h b/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.h index 64035f0e721..df1236221cb 100644 --- a/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.h +++ b/examples/C++/FlowControlExample/FlowControlExamplePubSubTypes.h @@ -38,7 +38,7 @@ class FlowControlExamplePubSubType : public eprosima::fastrtps::TopicDataType{ bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.cxx b/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.cxx index 0e15764d13d..2114e936577 100644 --- a/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.cxx +++ b/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.cxx @@ -97,14 +97,14 @@ void HelloWorldPubSubType::deleteData(void* data) { delete((HelloWorld*)data); } -bool HelloWorldPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool HelloWorldPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; HelloWorld* p_type = (HelloWorld*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,HelloWorld::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(HelloWorld::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || HelloWorld::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.h b/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.h index 53a90d4c562..30be0d93b19 100644 --- a/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.h +++ b/examples/C++/HelloWorldExample/HelloWorldPubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file HelloWorldPubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -42,7 +42,7 @@ class HelloWorldPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.cxx b/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.cxx index 0e15764d13d..2114e936577 100644 --- a/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.cxx +++ b/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.cxx @@ -97,14 +97,14 @@ void HelloWorldPubSubType::deleteData(void* data) { delete((HelloWorld*)data); } -bool HelloWorldPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool HelloWorldPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; HelloWorld* p_type = (HelloWorld*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,HelloWorld::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(HelloWorld::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || HelloWorld::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.h b/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.h index 53a90d4c562..4a01ad012c7 100644 --- a/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.h +++ b/examples/C++/HelloWorldExampleTCP/HelloWorldPubSubTypes.h @@ -42,7 +42,7 @@ class HelloWorldPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5=false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/HistoryKind/samplePubSubTypes.cxx b/examples/C++/HistoryKind/samplePubSubTypes.cxx index d856f924226..e35aae24735 100644 --- a/examples/C++/HistoryKind/samplePubSubTypes.cxx +++ b/examples/C++/HistoryKind/samplePubSubTypes.cxx @@ -96,14 +96,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/HistoryKind/samplePubSubTypes.h b/examples/C++/HistoryKind/samplePubSubTypes.h index 7dc0a55c5fc..be95cb1e0a7 100644 --- a/examples/C++/HistoryKind/samplePubSubTypes.h +++ b/examples/C++/HistoryKind/samplePubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file samplePubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -40,7 +40,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/Keys/samplePubSubTypes.cxx b/examples/C++/Keys/samplePubSubTypes.cxx index 0b704692ba1..4658c319468 100644 --- a/examples/C++/Keys/samplePubSubTypes.cxx +++ b/examples/C++/Keys/samplePubSubTypes.cxx @@ -97,14 +97,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/Keys/samplePubSubTypes.h b/examples/C++/Keys/samplePubSubTypes.h index 7dc0a55c5fc..be95cb1e0a7 100644 --- a/examples/C++/Keys/samplePubSubTypes.h +++ b/examples/C++/Keys/samplePubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file samplePubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -40,7 +40,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/LateJoiners/samplePubSubTypes.cxx b/examples/C++/LateJoiners/samplePubSubTypes.cxx index 7e79658add0..ade87336af9 100644 --- a/examples/C++/LateJoiners/samplePubSubTypes.cxx +++ b/examples/C++/LateJoiners/samplePubSubTypes.cxx @@ -98,14 +98,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/LateJoiners/samplePubSubTypes.h b/examples/C++/LateJoiners/samplePubSubTypes.h index 7dc0a55c5fc..be95cb1e0a7 100644 --- a/examples/C++/LateJoiners/samplePubSubTypes.h +++ b/examples/C++/LateJoiners/samplePubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file samplePubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -40,7 +40,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.cxx b/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.cxx index ffe2c3e8845..83d6b8e0b52 100644 --- a/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.cxx +++ b/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.cxx @@ -97,14 +97,14 @@ void ExampleMessagePubSubType::deleteData(void* data) { delete((ExampleMessage*)data); } -bool ExampleMessagePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ExampleMessagePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ExampleMessage* p_type = (ExampleMessage*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,ExampleMessage::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ExampleMessage::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ExampleMessage::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.h b/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.h index 135a23c7ba3..f089229babf 100644 --- a/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.h +++ b/examples/C++/OwnershipStrengthQoSExample/OwnershipStrengthPubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file OwnershipStrengthPubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -42,7 +42,7 @@ class ExampleMessagePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/SampleConfig_Controller/samplePubSubTypes.cxx b/examples/C++/SampleConfig_Controller/samplePubSubTypes.cxx index 823063f603e..72989fbba64 100644 --- a/examples/C++/SampleConfig_Controller/samplePubSubTypes.cxx +++ b/examples/C++/SampleConfig_Controller/samplePubSubTypes.cxx @@ -96,14 +96,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/SampleConfig_Controller/samplePubSubTypes.h b/examples/C++/SampleConfig_Controller/samplePubSubTypes.h index 567c2299d24..451acac540f 100644 --- a/examples/C++/SampleConfig_Controller/samplePubSubTypes.h +++ b/examples/C++/SampleConfig_Controller/samplePubSubTypes.h @@ -42,7 +42,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/SampleConfig_Events/samplePubSubTypes.cxx b/examples/C++/SampleConfig_Events/samplePubSubTypes.cxx index 0b704692ba1..4658c319468 100644 --- a/examples/C++/SampleConfig_Events/samplePubSubTypes.cxx +++ b/examples/C++/SampleConfig_Events/samplePubSubTypes.cxx @@ -97,14 +97,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/SampleConfig_Events/samplePubSubTypes.h b/examples/C++/SampleConfig_Events/samplePubSubTypes.h index 3a2682bb851..4ad7d3f13f2 100644 --- a/examples/C++/SampleConfig_Events/samplePubSubTypes.h +++ b/examples/C++/SampleConfig_Events/samplePubSubTypes.h @@ -41,7 +41,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.cxx b/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.cxx index 0b704692ba1..4658c319468 100644 --- a/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.cxx +++ b/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.cxx @@ -97,14 +97,14 @@ void samplePubSubType::deleteData(void* data) { delete((sample*)data); } -bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool samplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; sample* p_type = (sample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,sample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(sample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || sample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.h b/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.h index 567c2299d24..451acac540f 100644 --- a/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.h +++ b/examples/C++/SampleConfig_Multimedia/samplePubSubTypes.h @@ -42,7 +42,7 @@ class samplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.cxx b/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.cxx index 508d38968a6..065d618ae65 100644 --- a/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.cxx +++ b/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.cxx @@ -94,14 +94,14 @@ void HelloWorldPubSubType::deleteData(void* data) { delete((HelloWorld*)data); } -bool HelloWorldPubSubType::getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t* handle) { +bool HelloWorldPubSubType::getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; HelloWorld* p_type = (HelloWorld*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,HelloWorld::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(HelloWorld::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || HelloWorld::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.h b/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.h index ac136753209..4dac384a9bf 100644 --- a/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.h +++ b/examples/C++/SecureHelloWorldExample/HelloWorldPubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file HelloWorldPubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -42,7 +42,7 @@ class HelloWorldPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.cxx b/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.cxx index 0e15764d13d..2114e936577 100644 --- a/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.cxx +++ b/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.cxx @@ -97,14 +97,14 @@ void HelloWorldPubSubType::deleteData(void* data) { delete((HelloWorld*)data); } -bool HelloWorldPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool HelloWorldPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; HelloWorld* p_type = (HelloWorld*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,HelloWorld::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(HelloWorld::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || HelloWorld::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.h b/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.h index ac136753209..4dac384a9bf 100644 --- a/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.h +++ b/examples/C++/StaticHelloWorldExample/HelloWorldPubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file HelloWorldPubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -42,7 +42,7 @@ class HelloWorldPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.cxx b/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.cxx index a760e247e86..0637e2d1323 100644 --- a/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.cxx +++ b/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.cxx @@ -98,14 +98,14 @@ void XMLProfilesExamplePubSubType::deleteData(void* data) { delete((XMLProfilesExample*)data); } -bool XMLProfilesExamplePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool XMLProfilesExamplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; XMLProfilesExample* p_type = (XMLProfilesExample*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,XMLProfilesExample::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(XMLProfilesExample::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || XMLProfilesExample::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.h b/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.h index f999057333f..d3d378d3a1f 100644 --- a/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.h +++ b/examples/C++/XMLProfiles/XMLProfilesExamplePubSubTypes.h @@ -42,7 +42,7 @@ class XMLProfilesExamplePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/JNISource.stg b/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/JNISource.stg index 5e1db4da0cc..2dc0c14bcb6 100644 --- a/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/JNISource.stg +++ b/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/JNISource.stg @@ -193,7 +193,7 @@ class $struct.name$PubSubJNI : public TopicDataType, public SubscriberListener m_keyBuffer = (unsigned char*)malloc($struct.scopedname$::getKeyMaxCdrSerializedSize()>16 ? $struct.scopedname$::getKeyMaxCdrSerializedSize() : 16); //Register the type - Domain::registerType(participant,(TopicDataType*)this); + Domain::registerType(participant,(TopicDataType*)this); // Create Subscriber SubscriberAttributes Rparam; @@ -246,7 +246,7 @@ class $struct.name$PubSubJNI : public TopicDataType, public SubscriberListener delete(($struct.scopedname$*)data); } - bool getKey(void *data, InstanceHandle_t* handle) + bool getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; @@ -254,7 +254,7 @@ class $struct.name$PubSubJNI : public TopicDataType, public SubscriberListener eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,$struct.scopedname$::getKeyMaxCdrSerializedSize()); eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); p_type->serializeKey(ser); - if($struct.scopedname$::getKeyMaxCdrSerializedSize()>16) + if(force_md5 || $struct.scopedname$::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); @@ -343,7 +343,7 @@ class $struct.name$PubSubJNI : public TopicDataType, public SubscriberListener } Subscriber* getSubscriber() { return subscriber_;} - + private: diff --git a/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeHeader.stg b/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeHeader.stg index dc217733249..ccf8cd32ef1 100644 --- a/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeHeader.stg +++ b/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeHeader.stg @@ -21,10 +21,15 @@ $fileHeader(ctx=ctx, file=[ctx.filename, "PubSubTypes.h"], description=["This h #ifndef _$ctx.headerGuardName$_PUBSUBTYPES_H_ #define _$ctx.headerGuardName$_PUBSUBTYPES_H_ +#include #include #include "$ctx.filename$.h" +#if !defined(GEN_API_VER) || (GEN_API_VER != 1) +#error Generated $ctx.filename$ is not compatible with current installed Fast-RTPS. Please, regenerate it with fastrtpsgen. +#endif + $definitions; separator="\n"$ #endif // _$ctx.headerGuardName$_PUBSUBTYPES_H_ @@ -78,12 +83,13 @@ public: $if(parent.IsInterface)$$parent.name$_$endif$$struct.name$PubSubType(); virtual ~$if(parent.IsInterface)$$parent.name$_$endif$$struct.name$PubSubType(); - bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); - bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); - std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); - void* createData(); - void deleteData(void * data); + virtual bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload) override; + virtual bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data) override; + virtual std::function getSerializedSizeProvider(void* data) override; + virtual bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, + bool force_md5 = false) override; + virtual void* createData() override; + virtual void deleteData(void * data) override; MD5 m_md5; unsigned char* m_keyBuffer; }; diff --git a/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeSource.stg b/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeSource.stg index a4f77c92fba..5d678f5c887 100644 --- a/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeSource.stg +++ b/fastrtpsgen/src/com/eprosima/fastrtps/idl/templates/RTPSPubSubTypeSource.stg @@ -145,14 +145,15 @@ void $if(parent.IsInterface)$$parent.name$_$endif$$struct.name$PubSubType::delet delete(reinterpret_cast<$if(parent.IsInterface)$$struct.scopedname$$else$$struct.name$$endif$*>(data)); } -bool $if(parent.IsInterface)$$parent.name$_$endif$$struct.name$PubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool $if(parent.IsInterface)$$parent.name$_$endif$$struct.name$PubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) +{ if(!m_isGetKeyDefined) return false; $if(parent.IsInterface)$$struct.scopedname$$else$$struct.name$$endif$* p_type = static_cast<$if(parent.IsInterface)$$struct.scopedname$$else$$struct.name$$endif$*>(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),$if(parent.IsInterface)$$struct.scopedname$$else$$struct.name$$endif$::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if($if(parent.IsInterface)$$struct.scopedname$$else$$struct.name$$endif$::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || $if(parent.IsInterface)$$struct.scopedname$$else$$struct.name$$endif$::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); diff --git a/include/fastrtps/TopicDataType.h b/include/fastrtps/TopicDataType.h index a09fe517661..b7fbe08778e 100644 --- a/include/fastrtps/TopicDataType.h +++ b/include/fastrtps/TopicDataType.h @@ -78,7 +78,7 @@ class TopicDataType { * @param[out] ihandle Pointer to the Handle. * @return True if correct. */ - RTPS_DllAPI virtual bool getKey(void* data, rtps::InstanceHandle_t* ihandle){ (void) data; (void) ihandle; return false; } + RTPS_DllAPI virtual bool getKey(void* data, rtps::InstanceHandle_t* ihandle, bool force_md5 = false) = 0; /** * Set topic data type name diff --git a/include/fastrtps/config.h.in b/include/fastrtps/config.h.in index 334ba0a79e5..e973a83565d 100644 --- a/include/fastrtps/config.h.in +++ b/include/fastrtps/config.h.in @@ -20,6 +20,8 @@ #define FASTRTPS_VERSION_MICRO @PROJECT_VERSION_PATCH@ #define FASTRTPS_VERSION_STR "@PROJECT_VERSION@" +#define GEN_API_VER 1 + // C++11 support defines #ifndef HAVE_CXX11 #define HAVE_CXX11 @HAVE_CXX11@ diff --git a/include/fastrtps/qos/ParameterTypes.h b/include/fastrtps/qos/ParameterTypes.h index c2c1bccd0f1..b5dd0c5bfd3 100644 --- a/include/fastrtps/qos/ParameterTypes.h +++ b/include/fastrtps/qos/ParameterTypes.h @@ -22,6 +22,10 @@ #include "../rtps/common/all_common.h" #include "../rtps/common/Token.h" +#if HAVE_SECURITY +#include "../rtps/security/accesscontrol/ParticipantSecurityAttributes.h" +#include "../rtps/security/accesscontrol/EndpointSecurityAttributes.h" +#endif #include #include @@ -101,6 +105,10 @@ enum ParameterId_t : uint16_t //PID_RELATED_SAMPLE_IDENTITY = 0x0083 PID_IDENTITY_TOKEN = 0x1001, PID_PERMISSIONS_TOKEN = 0x1002, + PID_DATA_TAGS = 0x1003, + PID_ENDPOINT_SECURITY_INFO = 0x1004, + PID_PARTICIPANT_SECURITY_INFO = 0x1005, + PID_IDENTITY_STATUS_TOKEN = 0x1006, PID_PERSISTENCE_GUID = 0x8002, PID_RELATED_SAMPLE_IDENTITY = 0x800f, PID_DATA_REPRESENTATION = 0x0073, @@ -521,6 +529,8 @@ class ParameterSampleIdentity_t : public Parameter_t bool addToCDRMessage(rtps::CDRMessage_t* msg) override; }; +#if HAVE_SECURITY + /** * */ @@ -546,7 +556,65 @@ class ParameterToken_t : public Parameter_t bool addToCDRMessage(rtps::CDRMessage_t* msg) override; }; +class ParameterParticipantSecurityInfo_t : public Parameter_t +{ + public: + rtps::security::ParticipantSecurityAttributesMask security_attributes; + rtps::security::PluginParticipantSecurityAttributesMask plugin_security_attributes; + + ParameterParticipantSecurityInfo_t() : Parameter_t(PID_PARTICIPANT_SECURITY_INFO, 0) + { + } + + /** + * Constructor using a parameter PID and the parameter length + * @param pid Pid of the parameter + * @param in_length Its associated length + */ + ParameterParticipantSecurityInfo_t(ParameterId_t pid, uint16_t in_length) : Parameter_t(pid, in_length) + { + } + + /** + * Add the parameter to a CDRMessage_t message. + * @param[in,out] msg Pointer to the message where the parameter should be added. + * @return True if the parameter was correctly added. + */ + bool addToCDRMessage(rtps::CDRMessage_t* msg) override; +}; + +#define PARAMETER_PARTICIPANT_SECURITY_INFO_LENGTH 8 +class ParameterEndpointSecurityInfo_t : public Parameter_t +{ + public: + rtps::security::EndpointSecurityAttributesMask security_attributes; + rtps::security::PluginEndpointSecurityAttributesMask plugin_security_attributes; + + ParameterEndpointSecurityInfo_t() : Parameter_t(PID_ENDPOINT_SECURITY_INFO, 0) + { + } + + /** + * Constructor using a parameter PID and the parameter length + * @param pid Pid of the parameter + * @param in_length Its associated length + */ + ParameterEndpointSecurityInfo_t(ParameterId_t pid, uint16_t in_length) : Parameter_t(pid, in_length) + { + } + + /** + * Add the parameter to a CDRMessage_t message. + * @param[in,out] msg Pointer to the message where the parameter should be added. + * @return True if the parameter was correctly added. + */ + bool addToCDRMessage(rtps::CDRMessage_t* msg) override; +}; + +#define PARAMETER_ENDPOINT_SECURITY_INFO_LENGTH 8 + +#endif ///@} diff --git a/include/fastrtps/rtps/builtin/data/ParticipantProxyData.h b/include/fastrtps/rtps/builtin/data/ParticipantProxyData.h index b9ff724f38d..e9809b44198 100644 --- a/include/fastrtps/rtps/builtin/data/ParticipantProxyData.h +++ b/include/fastrtps/rtps/builtin/data/ParticipantProxyData.h @@ -27,28 +27,36 @@ #include "../../attributes/ReaderAttributes.h" #include "../../common/Token.h" +#if HAVE_SECURITY +#include "../../security/accesscontrol/ParticipantSecurityAttributes.h" +#endif + #define DISCOVERY_PARTICIPANT_DATA_MAX_SIZE 5000 #define DISCOVERY_TOPIC_DATA_MAX_SIZE 500 #define DISCOVERY_PUBLICATION_DATA_MAX_SIZE 5000 #define DISCOVERY_SUBSCRIPTION_DATA_MAX_SIZE 5000 #define BUILTIN_PARTICIPANT_DATA_MAX_SIZE 100 -#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_ANNOUNCER 0x00000001 << 0; -#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_DETECTOR 0x00000001 << 1; -#define DISC_BUILTIN_ENDPOINT_PUBLICATION_ANNOUNCER 0x00000001 << 2; -#define DISC_BUILTIN_ENDPOINT_PUBLICATION_DETECTOR 0x00000001 << 3; -#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_ANNOUNCER 0x00000001 << 4; -#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_DETECTOR 0x00000001 << 5; -#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_PROXY_ANNOUNCER 0x00000001 << 6; -#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_PROXY_DETECTOR 0x00000001 << 7; -#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_STATE_ANNOUNCER 0x00000001 << 8; -#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_STATE_DETECTOR 0x00000001 << 9; -#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_WRITER 0x00000001 << 10; -#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_READER 0x00000001 << 11; -#define DISC_BUILTIN_ENDPOINT_PUBLICATION_SECURE_ANNOUNCER 0x00000001 << 16; -#define DISC_BUILTIN_ENDPOINT_PUBLICATION_SECURE_DETECTOR 0x00000001 << 17; -#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_SECURE_ANNOUNCER 0x00000001 << 18; -#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_SECURE_DETECTOR 0x00000001 << 19; +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_ANNOUNCER (0x00000001 << 0) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_DETECTOR (0x00000001 << 1) +#define DISC_BUILTIN_ENDPOINT_PUBLICATION_ANNOUNCER (0x00000001 << 2) +#define DISC_BUILTIN_ENDPOINT_PUBLICATION_DETECTOR (0x00000001 << 3) +#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_ANNOUNCER (0x00000001 << 4) +#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_DETECTOR (0x00000001 << 5) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_PROXY_ANNOUNCER (0x00000001 << 6) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_PROXY_DETECTOR (0x00000001 << 7) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_STATE_ANNOUNCER (0x00000001 << 8) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_STATE_DETECTOR (0x00000001 << 9) +#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_WRITER (0x00000001 << 10) +#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_READER (0x00000001 << 11) +#define DISC_BUILTIN_ENDPOINT_PUBLICATION_SECURE_ANNOUNCER (0x00000001 << 16) +#define DISC_BUILTIN_ENDPOINT_PUBLICATION_SECURE_DETECTOR (0x00000001 << 17) +#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_SECURE_ANNOUNCER (0x00000001 << 18) +#define DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_SECURE_DETECTOR (0x00000001 << 19) +#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_WRITER (0x00000001 << 20) +#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_READER (0x00000001 << 21) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_SECURE_ANNOUNCER (0x00000001 << 26) +#define DISC_BUILTIN_ENDPOINT_PARTICIPANT_SECURE_DETECTOR (0x00000001 << 27) namespace eprosima { namespace fastrtps{ @@ -101,10 +109,16 @@ class ParticipantProxyData InstanceHandle_t m_key; //! Duration_t m_leaseDuration; +#if HAVE_SECURITY //! IdentityToken identity_token_; //! PermissionsToken permissions_token_; + //! + security::ParticipantSecurityAttributesMask security_attributes_; + //! + security::PluginParticipantSecurityAttributesMask plugin_security_attributes_; +#endif //! bool isAlive; //! @@ -134,7 +148,7 @@ class ParticipantProxyData * Read the parameter list from a recevied CDRMessage_t * @return True on success */ - bool readFromCDRMessage(CDRMessage_t* msg); + bool readFromCDRMessage(CDRMessage_t* msg, bool use_encapsulation=true); //!Clear the data (restore to default state.) void clear(); /** diff --git a/include/fastrtps/rtps/builtin/data/ReaderProxyData.h b/include/fastrtps/rtps/builtin/data/ReaderProxyData.h index 2f343ff6adb..9a24f8d6491 100644 --- a/include/fastrtps/rtps/builtin/data/ReaderProxyData.h +++ b/include/fastrtps/rtps/builtin/data/ReaderProxyData.h @@ -27,7 +27,9 @@ #include "../../attributes/WriterAttributes.h" - +#if HAVE_SECURITY +#include "../../security/accesscontrol/EndpointSecurityAttributes.h" +#endif namespace eprosima { namespace fastrtps{ @@ -298,6 +300,15 @@ class ReaderProxyData bool m_expectsInlineQos; //!Reader Qos ReaderQos m_qos; + +#if HAVE_SECURITY + //!EndpointSecurityInfo.endpoint_security_attributes + security::EndpointSecurityAttributesMask security_attributes_; + + //!EndpointSecurityInfo.plugin_endpoint_security_attributes + security::PluginEndpointSecurityAttributesMask plugin_security_attributes_; +#endif + /** * Clear (put to default) the information. */ diff --git a/include/fastrtps/rtps/builtin/data/WriterProxyData.h b/include/fastrtps/rtps/builtin/data/WriterProxyData.h index e3ee6a50d03..63556130361 100644 --- a/include/fastrtps/rtps/builtin/data/WriterProxyData.h +++ b/include/fastrtps/rtps/builtin/data/WriterProxyData.h @@ -27,7 +27,9 @@ #include "../../attributes/ReaderAttributes.h" - +#if HAVE_SECURITY +#include "../../security/accesscontrol/EndpointSecurityAttributes.h" +#endif namespace eprosima { namespace fastrtps{ @@ -317,6 +319,15 @@ class WriterProxyData //!WriterQOS WriterQos m_qos; + +#if HAVE_SECURITY + //!EndpointSecurityInfo.endpoint_security_attributes + security::EndpointSecurityAttributesMask security_attributes_; + + //!EndpointSecurityInfo.plugin_endpoint_security_attributes + security::PluginEndpointSecurityAttributesMask plugin_security_attributes_; +#endif + //!Clear the information and return the object to the default state. void clear(); //!Update certain parameters from another object. diff --git a/include/fastrtps/rtps/builtin/liveliness/WLP.h b/include/fastrtps/rtps/builtin/liveliness/WLP.h index 69a2b07fdfa..783dabd606e 100644 --- a/include/fastrtps/rtps/builtin/liveliness/WLP.h +++ b/include/fastrtps/rtps/builtin/liveliness/WLP.h @@ -119,6 +119,18 @@ class WLP * @return RTPS participant */ inline RTPSParticipantImpl* getRTPSParticipant(){return mp_participant;} + + /** + * Get the livelines builtin writer + * @return stateful writer + */ + StatefulWriter* getBuiltinWriter(); + + /** + * Get the livelines builtin writer's history + * @return writer history + */ + WriterHistory* getBuiltinWriterHistory(); private: //!Pointer to the local RTPSParticipant. @@ -143,6 +155,23 @@ class WLP std::vector m_livAutomaticWriters; //!List of the writers using manual by RTPSParticipant liveliness. std::vector m_livManRTPSParticipantWriters; + +#if HAVE_SECURITY + //!Pointer to the builtinRTPSParticipantMEssageWriter. + StatefulWriter* mp_builtinWriterSecure; + //!Pointer to the builtinRTPSParticipantMEssageReader. + StatefulReader* mp_builtinReaderSecure; + //!Writer History + WriterHistory* mp_builtinWriterSecureHistory; + //!Reader History + ReaderHistory* mp_builtinReaderSecureHistory; + + /** + * Create the secure endpoitns used in the WLP. + * @return true if correct. + */ + bool createSecureEndpoints(); +#endif }; } diff --git a/include/fastrtps/rtps/builtin/liveliness/WLPListener.h b/include/fastrtps/rtps/builtin/liveliness/WLPListener.h index eb28e63ce4a..74a2a470463 100644 --- a/include/fastrtps/rtps/builtin/liveliness/WLPListener.h +++ b/include/fastrtps/rtps/builtin/liveliness/WLPListener.h @@ -77,9 +77,6 @@ class WLPListener: public ReaderListener { */ bool computeKey(CacheChange_t* change); - //!Auxiliary message. - CDRMessage_t aux_msg; - private: WLP* mp_WLP; diff --git a/include/fastrtps/rtps/common/Guid.h b/include/fastrtps/rtps/common/Guid.h index 021b0a7bf6c..62fbc8d5448 100644 --- a/include/fastrtps/rtps/common/Guid.h +++ b/include/fastrtps/rtps/common/Guid.h @@ -144,15 +144,21 @@ inline std::ostream& operator<<(std::ostream& output,const GuidPrefix_t& guiP){ #define ENTITYID_SPDP_BUILTIN_RTPSParticipant_READER 0x000100c7 #define ENTITYID_P2P_BUILTIN_RTPSParticipant_MESSAGE_WRITER 0x000200C2 #define ENTITYID_P2P_BUILTIN_RTPSParticipant_MESSAGE_READER 0x000200C7 +#define ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_WRITER 0x000201C3 +#define ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_READER 0x000201C4 + +#if HAVE_SECURITY #define ENTITYID_SEDP_BUILTIN_PUBLICATIONS_SECURE_WRITER 0xff0003c2 #define ENTITYID_SEDP_BUILTIN_PUBLICATIONS_SECURE_READER 0xff0003c7 #define ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_WRITER 0xff0004c2 #define ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_READER 0xff0004c7 -#define ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_WRITER 0x000201C3 -#define ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_READER 0x000201C4 +#define ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_WRITER 0xff0200c2 +#define ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_READER 0xff0200c7 #define ENTITYID_P2P_BUILTIN_PARTICIPANT_VOLATILE_MESSAGE_SECURE_WRITER 0xff0202C3 #define ENTITYID_P2P_BUILTIN_PARTICIPANT_VOLATILE_MESSAGE_SECURE_READER 0xff0202C4 - +#define ENTITYID_SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_WRITER 0xff0101c2 +#define ENTITYID_SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_READER 0xff0101c7 +#endif //!@brief Structure EntityId_t, entity id part of GUID_t. //!@ingroup COMMON_MODULE @@ -315,18 +321,21 @@ const EntityId_t c_EntityId_RTPSParticipant = ENTITYID_RTPSParticipant; const EntityId_t c_EntityId_WriterLiveliness = ENTITYID_P2P_BUILTIN_RTPSParticipant_MESSAGE_WRITER; const EntityId_t c_EntityId_ReaderLiveliness = ENTITYID_P2P_BUILTIN_RTPSParticipant_MESSAGE_READER; +const EntityId_t participant_stateless_message_writer_entity_id = ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_WRITER; +const EntityId_t participant_stateless_message_reader_entity_id = ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_READER; + +#if HAVE_SECURITY const EntityId_t sedp_builtin_publications_secure_writer = ENTITYID_SEDP_BUILTIN_PUBLICATIONS_SECURE_WRITER; const EntityId_t sedp_builtin_publications_secure_reader = ENTITYID_SEDP_BUILTIN_PUBLICATIONS_SECURE_READER; const EntityId_t sedp_builtin_subscriptions_secure_writer = ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_WRITER; const EntityId_t sedp_builtin_subscriptions_secure_reader = ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_READER; -const EntityId_t participant_stateless_message_writer_entity_id = ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_WRITER; -const EntityId_t participant_stateless_message_reader_entity_id = ENTITYID_P2P_BUILTIN_PARTICIPANT_STATELESS_READER; - const EntityId_t participant_volatile_message_secure_writer_entity_id = ENTITYID_P2P_BUILTIN_PARTICIPANT_VOLATILE_MESSAGE_SECURE_WRITER; const EntityId_t participant_volatile_message_secure_reader_entity_id = ENTITYID_P2P_BUILTIN_PARTICIPANT_VOLATILE_MESSAGE_SECURE_READER; - +const EntityId_t c_EntityId_WriterLivelinessSecure = ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_WRITER; +const EntityId_t c_EntityId_ReaderLivelinessSecure = ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_READER; +#endif //!@brief Structure GUID_t, entity identifier, unique in DDS-RTPS Domain. //!@ingroup COMMON_MODULE diff --git a/include/fastrtps/rtps/common/Token.h b/include/fastrtps/rtps/common/Token.h index 892ddda3a2b..e27e714e558 100644 --- a/include/fastrtps/rtps/common/Token.h +++ b/include/fastrtps/rtps/common/Token.h @@ -60,6 +60,11 @@ class DataHolder return *this; } + bool is_nil() const + { + return class_id_.empty(); + } + void class_id(const std::string& class_id) { class_id_ = class_id; @@ -112,10 +117,11 @@ class DataHolder typedef std::vector DataHolderSeq; typedef DataHolder Token; typedef Token IdentityToken; +typedef Token IdentityStatusToken; typedef Token PermissionsToken; +typedef Token AuthenticatedPeerCredentialToken; typedef Token PermissionsCredentialToken; - class DataHolderHelper { public: diff --git a/include/fastrtps/rtps/common/Types.h b/include/fastrtps/rtps/common/Types.h index b73f13fe315..704a23a1c62 100644 --- a/include/fastrtps/rtps/common/Types.h +++ b/include/fastrtps/rtps/common/Types.h @@ -140,7 +140,14 @@ struct RTPS_DllAPI ProtocolVersion_t const ProtocolVersion_t c_ProtocolVersion_2_0(2,0); const ProtocolVersion_t c_ProtocolVersion_2_1(2,1); const ProtocolVersion_t c_ProtocolVersion_2_2(2,2); -const ProtocolVersion_t c_ProtocolVersion(2,1); +const ProtocolVersion_t c_ProtocolVersion_2_3(2,3); + +#if HAVE_SECURITY +// As imposed by DDSSEC11-93 +const ProtocolVersion_t c_ProtocolVersion(2,3); +#else +const ProtocolVersion_t c_ProtocolVersion(2,2); +#endif //!@brief Structure VendorId_t, specifying the vendor Id of the implementation. class VendorId_t diff --git a/include/fastrtps/rtps/messages/CDRMessage.h b/include/fastrtps/rtps/messages/CDRMessage.h index dfaca60ea07..7e611cb8576 100644 --- a/include/fastrtps/rtps/messages/CDRMessage.h +++ b/include/fastrtps/rtps/messages/CDRMessage.h @@ -124,15 +124,15 @@ namespace CDRMessage{ inline bool addParameterSentinel(CDRMessage_t*msg); inline bool addParameterId(CDRMessage_t*msg,ParameterId_t pid); inline bool addString(CDRMessage_t*msg, const std::string& in_str); - inline bool addOctetVector(CDRMessage_t*msg, const std::vector* ocvec); + inline bool addOctetVector(CDRMessage_t*msg, const std::vector* ocvec, bool add_final_padding=true); inline bool addParameterSampleIdentity(CDRMessage_t *msg, const SampleIdentity &sample_id); ///@} inline bool addProperty(CDRMessage_t* msg, const Property& property); - inline bool addBinaryProperty(CDRMessage_t* msg, const BinaryProperty& binary_property); + inline bool addBinaryProperty(CDRMessage_t* msg, const BinaryProperty& binary_property, bool add_final_padding=true); inline bool addPropertySeq(CDRMessage_t* msg, const PropertySeq& properties); - inline bool addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties); - inline bool addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties, const std::string& property_limit); + inline bool addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties, bool add_final_padding); + inline bool addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties, const std::string& name_start, bool add_final_padding); inline bool addDataHolder(CDRMessage_t* msg, const DataHolder& data_holder); inline bool addDataHolderSeq(CDRMessage_t* msg, const DataHolderSeq& data_holders); inline bool addMessageIdentity(CDRMessage_t* msg, const security::MessageIdentity& message_identity); diff --git a/include/fastrtps/rtps/messages/CDRMessage.hpp b/include/fastrtps/rtps/messages/CDRMessage.hpp index 7384d6f96e5..89c07c8aade 100644 --- a/include/fastrtps/rtps/messages/CDRMessage.hpp +++ b/include/fastrtps/rtps/messages/CDRMessage.hpp @@ -463,24 +463,30 @@ inline bool CDRMessage::addInt64(CDRMessage_t* msg, int64_t lolo) { return true; } -inline bool CDRMessage::addOctetVector(CDRMessage_t*msg, const std::vector* ocvec) +inline bool CDRMessage::addOctetVector(CDRMessage_t*msg, const std::vector* ocvec, bool add_final_padding) { // TODO Calculate without padding - if(msg->pos+4+ocvec->size()>=msg->max_size) + auto final_size = msg->pos + ocvec->size(); + if (add_final_padding) final_size += 4; + if(final_size>=msg->max_size) { return false; } bool valid = CDRMessage::addUInt32(msg,(uint32_t)ocvec->size()); valid &= CDRMessage::addData(msg,(octet*)ocvec->data(),(uint32_t)ocvec->size()); - int rest = ocvec->size()% 4; - if (rest != 0) + if (add_final_padding) { - rest = 4 - rest; //how many you have to add + int rest = ocvec->size() % 4; + if (rest != 0) + { + rest = 4 - rest; //how many you have to add - octet oc = '\0'; - for (int i = 0; i < rest; i++) { - valid &= CDRMessage::addOctet(msg, oc); + octet oc = '\0'; + for (int i = 0; i < rest; i++) + { + valid &= CDRMessage::addOctet(msg, oc); + } } } @@ -659,14 +665,14 @@ inline bool CDRMessage::addParameterSentinel(CDRMessage_t* msg) inline bool CDRMessage::addString(CDRMessage_t*msg, const std::string& in_str) { - uint32_t str_siz = (uint32_t)in_str.size(); + auto data = in_str.c_str(); + uint32_t str_siz = (uint32_t)strlen(data); int rest = (str_siz+1) % 4; if (rest != 0) rest = 4 - rest; //how many you have to add bool valid = CDRMessage::addUInt32(msg, str_siz+1); - valid &= CDRMessage::addData(msg, - (unsigned char*) in_str.c_str(), str_siz+1); + valid &= CDRMessage::addData(msg, (unsigned char*) data, str_siz+1); if (rest != 0) { octet oc = '\0'; for (int i = 0; i < rest; i++) { @@ -719,7 +725,7 @@ inline bool CDRMessage::readProperty(CDRMessage_t* msg, Property& property) return true; } -inline bool CDRMessage::addBinaryProperty(CDRMessage_t* msg, const BinaryProperty& binary_property) +inline bool CDRMessage::addBinaryProperty(CDRMessage_t* msg, const BinaryProperty& binary_property, bool add_final_padding) { assert(msg); @@ -727,7 +733,7 @@ inline bool CDRMessage::addBinaryProperty(CDRMessage_t* msg, const BinaryPropert { if(!CDRMessage::addString(msg, binary_property.name())) return false; - if(!CDRMessage::addOctetVector(msg, &binary_property.value())) + if (!CDRMessage::addOctetVector(msg, &binary_property.value(), add_final_padding)) return false; } @@ -789,7 +795,7 @@ inline bool CDRMessage::readPropertySeq(CDRMessage_t* msg, PropertySeq& properti } -inline bool CDRMessage::addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties) +inline bool CDRMessage::addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties, bool add_final_padding) { assert(msg); @@ -806,15 +812,18 @@ inline bool CDRMessage::addBinaryPropertySeq(CDRMessage_t* msg, const BinaryProp { returnedValue = true; for(auto it = binary_properties.begin(); returnedValue && it != binary_properties.end(); ++it) - if(it->propagate()) - returnedValue = CDRMessage::addBinaryProperty(msg, *it); + if (it->propagate()) + { + --number_to_serialize; + returnedValue = CDRMessage::addBinaryProperty(msg, *it, add_final_padding || (number_to_serialize != 0) ); + } } } return returnedValue; } -inline bool CDRMessage::addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties, const std::string& property_limit) +inline bool CDRMessage::addBinaryPropertySeq(CDRMessage_t* msg, const BinaryPropertySeq& binary_properties, const std::string& name_start, bool add_final_padding) { assert(msg); @@ -822,22 +831,24 @@ inline bool CDRMessage::addBinaryPropertySeq(CDRMessage_t* msg, const BinaryProp if(msg->pos + 4 <= msg->max_size) { - uint32_t position = 0; uint32_t number_to_serialize = 0; - for(auto it = binary_properties.begin(); it != binary_properties.end() && - it->name().compare(property_limit) != 0; ++it) + for(auto it = binary_properties.begin(); it != binary_properties.end(); ++it) { - if(it->propagate()) + if(it->name().find(name_start) == 0) ++number_to_serialize; - ++position; } if(CDRMessage::addUInt32(msg, number_to_serialize)) { returnedValue = true; - for(uint32_t i = 0; returnedValue && i < position; ++i) - if(binary_properties.at(i).propagate()) - returnedValue = CDRMessage::addBinaryProperty(msg, binary_properties.at(i)); + for (auto it = binary_properties.begin(); returnedValue && it != binary_properties.end(); ++it) + { + if (it->name().find(name_start) == 0) + { + --number_to_serialize; + returnedValue = CDRMessage::addBinaryProperty(msg, *it, add_final_padding || (number_to_serialize != 0) ); + } + } } } @@ -868,7 +879,7 @@ inline bool CDRMessage::addDataHolder(CDRMessage_t* msg, const DataHolder& data_ return false; if(!CDRMessage::addPropertySeq(msg, data_holder.properties())) return false; - if(!CDRMessage::addBinaryPropertySeq(msg, data_holder.binary_properties())) + if(!CDRMessage::addBinaryPropertySeq(msg, data_holder.binary_properties(),true)) return false; return true; diff --git a/include/fastrtps/rtps/security/accesscontrol/AccessControl.h b/include/fastrtps/rtps/security/accesscontrol/AccessControl.h index 736e289910e..ebd71bcd79e 100644 --- a/include/fastrtps/rtps/security/accesscontrol/AccessControl.h +++ b/include/fastrtps/rtps/security/accesscontrol/AccessControl.h @@ -110,7 +110,7 @@ class AccessControl virtual bool check_remote_datareader(const PermissionsHandle& remote_handle, const uint32_t domain_id, const ReaderProxyData& subscription_data, - SecurityException& exception) = 0; + bool& relay_only, SecurityException& exception) = 0; virtual bool get_participant_sec_attributes(const PermissionsHandle& local_handle, ParticipantSecurityAttributes& attributes, SecurityException& exception) = 0; diff --git a/include/fastrtps/rtps/security/accesscontrol/EndpointSecurityAttributes.h b/include/fastrtps/rtps/security/accesscontrol/EndpointSecurityAttributes.h index d6fa66cb413..4ddb5c26c47 100644 --- a/include/fastrtps/rtps/security/accesscontrol/EndpointSecurityAttributes.h +++ b/include/fastrtps/rtps/security/accesscontrol/EndpointSecurityAttributes.h @@ -18,23 +18,115 @@ #ifndef __RTPS_SECURITY_ACCESSCONTROL_ENDPOINTSECURITYATTRIBUTES_H__ #define __RTPS_SECURITY_ACCESSCONTROL_ENDPOINTSECURITYATTRIBUTES_H__ +#include "./SecurityMaskUtilities.h" + namespace eprosima { namespace fastrtps { namespace rtps { namespace security { +typedef uint32_t PluginEndpointSecurityAttributesMask; + +#define PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED (0x00000001UL << 0) +#define PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED (0x00000001UL << 1) +#define PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED (0x00000001UL << 2) +#define PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID (0x00000001UL << 31) + +#define PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_MASK_DEFAULT PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID + +struct PluginEndpointSecurityAttributes +{ + PluginEndpointSecurityAttributes() : + is_submessage_encrypted(false), is_submessage_origin_authenticated(false), is_payload_encrypted(false) + { } + + explicit PluginEndpointSecurityAttributes(const PluginEndpointSecurityAttributesMask mask) : + is_submessage_encrypted((mask & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED) != 0), + is_submessage_origin_authenticated((mask & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED) != 0), + is_payload_encrypted((mask & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED) != 0) + { + } + + bool is_submessage_encrypted; + bool is_submessage_origin_authenticated; + bool is_payload_encrypted; + + inline PluginEndpointSecurityAttributesMask mask() const + { + PluginEndpointSecurityAttributesMask rv = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (is_submessage_encrypted) rv |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (is_submessage_origin_authenticated) rv |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + if (is_payload_encrypted) rv |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED; + return rv; + } +}; + +typedef uint32_t EndpointSecurityAttributesMask; + +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_READ_PROTECTED (0x00000001UL << 0) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_WRITE_PROTECTED (0x00000001UL << 1) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_PROTECTED (0x00000001UL << 2) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_PROTECTED (0x00000001UL << 3) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_PROTECTED (0x00000001UL << 4) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_KEY_PROTECTED (0x00000001UL << 5) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_PROTECTED (0x00000001UL << 6) +#define ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID (0x00000001UL << 31) + struct EndpointSecurityAttributes { - EndpointSecurityAttributes() : is_access_protected(true), is_discovered_protected(false), - is_submessage_protected(false), is_payload_protected(false) {} + EndpointSecurityAttributes() : + is_read_protected(true), is_write_protected(true), + is_discovery_protected(false), is_liveliness_protected(false), + is_submessage_protected(false), is_payload_protected(false), is_key_protected(false), + plugin_endpoint_attributes(0UL) + {} + + explicit EndpointSecurityAttributes(const EndpointSecurityAttributesMask mask) : + is_read_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_READ_PROTECTED) != 0), + is_write_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_WRITE_PROTECTED) != 0), + is_discovery_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_PROTECTED) != 0), + is_liveliness_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_PROTECTED) != 0), + is_submessage_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_PROTECTED) != 0), + is_payload_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_PROTECTED) != 0), + is_key_protected((mask & ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_KEY_PROTECTED) != 0), + plugin_endpoint_attributes(0UL) + {} + + bool is_read_protected; + + bool is_write_protected; - bool is_access_protected; + bool is_discovery_protected; - bool is_discovered_protected; + bool is_liveliness_protected; bool is_submessage_protected; bool is_payload_protected; + + bool is_key_protected; + + PluginEndpointSecurityAttributesMask plugin_endpoint_attributes; + + inline EndpointSecurityAttributesMask mask() const + { + EndpointSecurityAttributesMask rv = ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (is_read_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_READ_PROTECTED; + if (is_write_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_WRITE_PROTECTED; + if (is_discovery_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_PROTECTED; + if (is_liveliness_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_PROTECTED; + if (is_submessage_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_PROTECTED; + if (is_payload_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_PROTECTED; + if (is_key_protected) rv |= ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_KEY_PROTECTED; + return rv; + } + + inline bool match(const EndpointSecurityAttributesMask remoteMask, + const PluginEndpointSecurityAttributesMask remotePluginMask) const + { + return security_mask_matches(mask(), remoteMask) && + security_mask_matches(plugin_endpoint_attributes, remotePluginMask); + } }; } diff --git a/include/fastrtps/rtps/security/accesscontrol/ParticipantSecurityAttributes.h b/include/fastrtps/rtps/security/accesscontrol/ParticipantSecurityAttributes.h index 0b43d3c9367..9bff120ddf6 100644 --- a/include/fastrtps/rtps/security/accesscontrol/ParticipantSecurityAttributes.h +++ b/include/fastrtps/rtps/security/accesscontrol/ParticipantSecurityAttributes.h @@ -18,21 +18,115 @@ #ifndef __RTPS_SECURITY_ACCESSCONTROL_PARTICIPANTSECURITYATTRIBUTES_H__ #define __RTPS_SECURITY_ACCESSCONTROL_PARTICIPANTSECURITYATTRIBUTES_H__ +#include "./SecurityMaskUtilities.h" + namespace eprosima { namespace fastrtps { namespace rtps { namespace security { +typedef uint32_t PluginParticipantSecurityAttributesMask; + +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED (0x00000001UL << 0) +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_BUILTIN_IS_DISCOVERY_ENCRYPTED (0x00000001UL << 1) +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_ENCRYPTED (0x00000001UL << 2) +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED (0x00000001UL << 3) +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_ORIGIN_AUTHENTICATED (0x00000001UL << 4) +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_ORIGIN_AUTHENTICATED (0x00000001UL << 5) +#define PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_VALID (0x00000001UL << 31) + +struct PluginParticipantSecurityAttributes +{ + PluginParticipantSecurityAttributes() : + is_rtps_encrypted(false), is_discovery_encrypted(false), is_liveliness_encrypted(false), + is_rtps_origin_authenticated(false), is_discovery_origin_authenticated(false), + is_liveliness_origin_authenticated(false) + {} + + explicit PluginParticipantSecurityAttributes(const PluginParticipantSecurityAttributesMask mask) : + is_rtps_encrypted((mask & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED) != 0), + is_discovery_encrypted((mask & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_BUILTIN_IS_DISCOVERY_ENCRYPTED) != 0), + is_liveliness_encrypted((mask & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_ENCRYPTED) != 0), + is_rtps_origin_authenticated((mask & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED) != 0), + is_discovery_origin_authenticated((mask & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_ORIGIN_AUTHENTICATED) != 0), + is_liveliness_origin_authenticated((mask & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_ORIGIN_AUTHENTICATED) != 0) + {} + + bool is_rtps_encrypted; + + bool is_discovery_encrypted; + + bool is_liveliness_encrypted; + + bool is_rtps_origin_authenticated; + + bool is_discovery_origin_authenticated; + + bool is_liveliness_origin_authenticated; + + inline PluginParticipantSecurityAttributesMask mask() const + { + PluginParticipantSecurityAttributesMask rv = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (is_rtps_encrypted) rv |= PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED; + if (is_discovery_encrypted) rv |= PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_BUILTIN_IS_DISCOVERY_ENCRYPTED; + if (is_liveliness_encrypted) rv |= PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_ENCRYPTED; + if (is_rtps_origin_authenticated) rv |= PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + if (is_discovery_origin_authenticated) rv |= PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_ORIGIN_AUTHENTICATED; + if (is_liveliness_origin_authenticated) rv |= PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_ORIGIN_AUTHENTICATED; + return rv; + } +}; + +typedef uint32_t ParticipantSecurityAttributesMask; + +#define PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_PROTECTED (0x00000001UL << 0) +#define PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_PROTECTED (0x00000001UL << 1) +#define PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_PROTECTED (0x00000001UL << 2) +#define PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_VALID (0x00000001UL << 31) + struct ParticipantSecurityAttributes { - ParticipantSecurityAttributes() : is_access_protected(true), is_discovered_protected(false), - is_rtps_protected(false) {} + ParticipantSecurityAttributes() : + allow_unauthenticated_participants(false), is_access_protected(true), + is_rtps_protected(false), is_discovery_protected(false), is_liveliness_protected(false), + plugin_participant_attributes (0UL) + {} - bool is_access_protected; + explicit ParticipantSecurityAttributes(const ParticipantSecurityAttributesMask mask) : + allow_unauthenticated_participants(false), is_access_protected(true), + is_rtps_protected((mask & PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_PROTECTED) != 0), + is_discovery_protected((mask & PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_PROTECTED) != 0), + is_liveliness_protected((mask & PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_PROTECTED) != 0), + plugin_participant_attributes(0UL) + {} + + bool allow_unauthenticated_participants; - bool is_discovered_protected; + bool is_access_protected; bool is_rtps_protected; + + bool is_discovery_protected; + + bool is_liveliness_protected; + + PluginParticipantSecurityAttributesMask plugin_participant_attributes; + + inline ParticipantSecurityAttributesMask mask() const + { + ParticipantSecurityAttributesMask rv = PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (is_rtps_protected) rv |= PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_PROTECTED; + if (is_discovery_protected) rv |= PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_DISCOVERY_PROTECTED; + if (is_liveliness_protected) rv |= PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_LIVELINESS_PROTECTED; + return rv; + } + + inline bool match(const ParticipantSecurityAttributesMask remoteMask, + const PluginParticipantSecurityAttributesMask remotePluginMask) const + { + return security_mask_matches(mask(), remoteMask) && + security_mask_matches(plugin_participant_attributes, remotePluginMask); + } }; } diff --git a/include/fastrtps/rtps/security/accesscontrol/SecurityMaskUtilities.h b/include/fastrtps/rtps/security/accesscontrol/SecurityMaskUtilities.h new file mode 100644 index 00000000000..e466ca7f3c5 --- /dev/null +++ b/include/fastrtps/rtps/security/accesscontrol/SecurityMaskUtilities.h @@ -0,0 +1,41 @@ +// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). +// +// 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 SecurityMaskUtilities.h + */ +#ifndef __RTPS_SECURITY_ACCESSCONTROL_SECURITYMASKUTILITIES_H__ +#define __RTPS_SECURITY_ACCESSCONTROL_SECURITYMASKUTILITIES_H__ + +namespace eprosima { +namespace fastrtps { +namespace rtps { +namespace security { + +inline bool security_mask_matches(const uint32_t lv, const uint32_t rv) +{ + if (((lv & (1UL << 31)) == 0) || ((rv & (1UL << 31)) == 0)) + { + return true; + } + + return lv == rv; +} + +} +} +} +} + +#endif // __RTPS_SECURITY_ACCESSCONTROL_SECURITYMASKUTILITIES_H__ diff --git a/include/fastrtps/rtps/security/cryptography/CryptoKeyFactory.h b/include/fastrtps/rtps/security/cryptography/CryptoKeyFactory.h index 0a5339b01b4..f3b68b5692c 100644 --- a/include/fastrtps/rtps/security/cryptography/CryptoKeyFactory.h +++ b/include/fastrtps/rtps/security/cryptography/CryptoKeyFactory.h @@ -19,6 +19,8 @@ #define _RTPS_SECURITY_CRYPTOGRAPHY_CRYPTOKEYFACTORY_H_ #include "CryptoTypes.h" +#include "../accesscontrol/EndpointSecurityAttributes.h" +#include "../accesscontrol/ParticipantSecurityAttributes.h" namespace eprosima { namespace fastrtps { @@ -43,6 +45,7 @@ class CryptoKeyFactory const IdentityHandle &participant_identity, const PermissionsHandle &participant_permissions, const PropertySeq &participant_properties, + const ParticipantSecurityAttributes &participant_security_attributes, SecurityException &exception) = 0; /** @@ -73,6 +76,7 @@ class CryptoKeyFactory virtual DatawriterCryptoHandle * register_local_datawriter( ParticipantCryptoHandle &participant_crypto, const PropertySeq &datawriter_prop, + const EndpointSecurityAttributes &datawriter_sec_attr, SecurityException &exception) = 0; /** @@ -103,6 +107,7 @@ class CryptoKeyFactory virtual DatareaderCryptoHandle * register_local_datareader( ParticipantCryptoHandle &participant_crypto, const PropertySeq &datareader_properties, + const EndpointSecurityAttributes &datareader_security_attributes, SecurityException &exception) = 0; /** diff --git a/include/fastrtps/rtps/security/cryptography/CryptoTypes.h b/include/fastrtps/rtps/security/cryptography/CryptoTypes.h index 0f9b0fcc445..1bdb558315f 100644 --- a/include/fastrtps/rtps/security/cryptography/CryptoTypes.h +++ b/include/fastrtps/rtps/security/cryptography/CryptoTypes.h @@ -32,7 +32,7 @@ #define _SEC_PREFIX_ 0x31 #define _SEC_POSTFIX_ 0x32 #define _SRTPS_PREFIX_ 0x33 -#define _SRTPS_POSTFIX_ 0x32 +#define _SRTPS_POSTFIX_ 0x34 #define _SecureBodySubmessage_ 0x30 const uint8_t SEC_PREFIX = _SEC_PREFIX_; @@ -49,11 +49,18 @@ namespace security { typedef std::array CryptoTransformKind; typedef std::array CryptoTransformKeyId; + const CryptoTransformKeyId c_transformKeyIdZero = { 0,0,0,0 }; + + typedef Token MessageToken; + typedef MessageToken AuthRequestMessageToken; + typedef MessageToken HandshakeMessageToken; + typedef Token CryptoToken; typedef Token ParticipantCryptoToken; typedef Token DatawriterCryptoToken; typedef Token DatareaderCryptoToken; + typedef std::vector HandshakeMessageTokenSeq; typedef std::vector CryptoTokenSeq; typedef CryptoTokenSeq ParticipantCryptoTokenSeq; typedef CryptoTokenSeq DatawriterCryptoTokenSeq; diff --git a/include/fastrtps/types/DynamicPubSubType.h b/include/fastrtps/types/DynamicPubSubType.h index 1d1bf07e104..5b3d6afaa0c 100644 --- a/include/fastrtps/types/DynamicPubSubType.h +++ b/include/fastrtps/types/DynamicPubSubType.h @@ -35,7 +35,7 @@ class DynamicPubSubType : public eprosima::fastrtps::TopicDataType RTPS_DllAPI void* createData(); RTPS_DllAPI void deleteData(void * data); RTPS_DllAPI bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); - RTPS_DllAPI bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + RTPS_DllAPI bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5=false); RTPS_DllAPI std::function getSerializedSizeProvider(void* data); RTPS_DllAPI bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); diff --git a/src/cpp/publisher/PublisherImpl.cpp b/src/cpp/publisher/PublisherImpl.cpp index 1101b019faa..49bbe9306e3 100644 --- a/src/cpp/publisher/PublisherImpl.cpp +++ b/src/cpp/publisher/PublisherImpl.cpp @@ -99,7 +99,11 @@ bool PublisherImpl::create_new_change_with_params(ChangeKind_t changeKind, void* InstanceHandle_t handle; if(m_att.topic.topicKind == WITH_KEY) { - mp_type->getKey(data,&handle); + bool is_key_protected = false; +#if HAVE_SECURITY + is_key_protected = mp_writer->getAttributes().security_attributes().is_key_protected; +#endif + mp_type->getKey(data,&handle,is_key_protected); } // Block lowlevel writer diff --git a/src/cpp/qos/ParameterList.cpp b/src/cpp/qos/ParameterList.cpp index 388dee0edee..fb8da4b5bc5 100644 --- a/src/cpp/qos/ParameterList.cpp +++ b/src/cpp/qos/ParameterList.cpp @@ -304,9 +304,11 @@ int32_t ParameterList::readParameterListfromCDRMsg(CDRMessage_t*msg, ParameterLi if(plength != length_diff) { delete(p); - return -1; } - plist->m_parameters.push_back((Parameter_t*)p); + else + { + plist->m_parameters.push_back((Parameter_t*)p); + } paramlist_byte_size += plength; break; } @@ -710,13 +712,7 @@ int32_t ParameterList::readParameterListfromCDRMsg(CDRMessage_t*msg, ParameterLi break; } } - case PID_IDENTITY_TOKEN: - { - ParameterToken_t* p = new ParameterToken_t(pid, plength); - valid &= CDRMessage::readDataHolder(msg, p->token); - msg->pos += (4 - msg->pos % 4) & 3; //align - IF_VALID_ADD - } + case PID_DATA_REPRESENTATION: { DataRepresentationQosPolicy * p = new DataRepresentationQosPolicy(); @@ -733,21 +729,46 @@ int32_t ParameterList::readParameterListfromCDRMsg(CDRMessage_t*msg, ParameterLi } case PID_TYPE_CONSISTENCY_ENFORCEMENT: { - uint32_t uKind(0); + uint16_t uKind(0); octet temp(0); TypeConsistencyEnforcementQosPolicy * p = new TypeConsistencyEnforcementQosPolicy(); - valid &= CDRMessage::readUInt32(msg, &uKind); - p->m_kind = static_cast(uKind); - valid &= CDRMessage::readOctet(msg, &temp); - p->m_ignore_sequence_bounds = temp == 0 ? false : true; - valid &= CDRMessage::readOctet(msg, &temp); - p->m_ignore_string_bounds = temp == 0 ? false : true; - valid &= CDRMessage::readOctet(msg, &temp); - p->m_ignore_member_names = temp == 0 ? false : true; - valid &= CDRMessage::readOctet(msg, &temp); - p->m_prevent_type_widening = temp == 0 ? false : true; - valid &= CDRMessage::readOctet(msg, &temp); - p->m_force_type_validation = temp == 0 ? false : true; + p->m_ignore_sequence_bounds = false; + p->m_ignore_string_bounds = false; + p->m_ignore_member_names = false; + p->m_prevent_type_widening = false; + p->m_force_type_validation = false; + + valid &= plength >= 2; + if (valid) + { + valid &= CDRMessage::readUInt16(msg, &uKind); + p->m_kind = static_cast(uKind); + } + if (valid && plength >= 3) + { + valid &= CDRMessage::readOctet(msg, &temp); + p->m_ignore_sequence_bounds = temp == 0 ? false : true; + } + if (valid && plength >= 4) + { + valid &= CDRMessage::readOctet(msg, &temp); + p->m_ignore_string_bounds = temp == 0 ? false : true; + } + if (valid && plength >= 5) + { + valid &= CDRMessage::readOctet(msg, &temp); + p->m_ignore_member_names = temp == 0 ? false : true; + } + if (valid && plength >= 6) + { + valid &= CDRMessage::readOctet(msg, &temp); + p->m_prevent_type_widening = temp == 0 ? false : true; + } + if (valid && plength >= 7) + { + valid &= CDRMessage::readOctet(msg, &temp); + p->m_force_type_validation = temp == 0 ? false : true; + } IF_VALID_ADD } case PID_TYPE_IDV1: @@ -762,6 +783,42 @@ int32_t ParameterList::readParameterListfromCDRMsg(CDRMessage_t*msg, ParameterLi valid &= p->readFromCDRMessage(msg, plength); IF_VALID_ADD } + +#if HAVE_SECURITY + case PID_IDENTITY_TOKEN: + case PID_PERMISSIONS_TOKEN: + { + ParameterToken_t* p = new ParameterToken_t(pid, plength); + valid &= CDRMessage::readDataHolder(msg, p->token); + msg->pos += (4 - msg->pos % 4) & 3; //align + IF_VALID_ADD + } + + case PID_PARTICIPANT_SECURITY_INFO: + { + if (plength != PARAMETER_PARTICIPANT_SECURITY_INFO_LENGTH) + { + return -1; + } + ParameterParticipantSecurityInfo_t* p = new ParameterParticipantSecurityInfo_t(pid, plength); + valid &= CDRMessage::readUInt32(msg, &p->security_attributes); + valid &= CDRMessage::readUInt32(msg, &p->plugin_security_attributes); + IF_VALID_ADD + } + + case PID_ENDPOINT_SECURITY_INFO: + { + if (plength != PARAMETER_ENDPOINT_SECURITY_INFO_LENGTH) + { + return -1; + } + ParameterEndpointSecurityInfo_t* p = new ParameterEndpointSecurityInfo_t(pid, plength); + valid &= CDRMessage::readUInt32(msg, &p->security_attributes); + valid &= CDRMessage::readUInt32(msg, &p->plugin_security_attributes); + IF_VALID_ADD + } +#endif + case PID_PAD: default: { diff --git a/src/cpp/qos/ParameterTypes.cpp b/src/cpp/qos/ParameterTypes.cpp index c608d64b4c2..b67ad958d7c 100644 --- a/src/cpp/qos/ParameterTypes.cpp +++ b/src/cpp/qos/ParameterTypes.cpp @@ -209,6 +209,8 @@ bool ParameterSampleIdentity_t::addToCDRMessage(CDRMessage_t*msg) return valid; } +#if HAVE_SECURITY + bool ParameterToken_t::addToCDRMessage(CDRMessage_t*msg) { bool valid = CDRMessage::addUInt16(msg, this->Pid); @@ -228,3 +230,23 @@ bool ParameterToken_t::addToCDRMessage(CDRMessage_t*msg) msg->length -= 2; return valid; } + +bool ParameterParticipantSecurityInfo_t::addToCDRMessage(CDRMessage_t*msg) +{ + bool valid = CDRMessage::addUInt16(msg, this->Pid); + valid &= CDRMessage::addUInt16(msg, PARAMETER_PARTICIPANT_SECURITY_INFO_LENGTH);//this->length); + valid &= CDRMessage::addUInt32(msg, this->security_attributes); + valid &= CDRMessage::addUInt32(msg, this->plugin_security_attributes); + return valid; +} + +bool ParameterEndpointSecurityInfo_t::addToCDRMessage(CDRMessage_t*msg) +{ + bool valid = CDRMessage::addUInt16(msg, this->Pid); + valid &= CDRMessage::addUInt16(msg, PARAMETER_ENDPOINT_SECURITY_INFO_LENGTH);//this->length); + valid &= CDRMessage::addUInt32(msg, this->security_attributes); + valid &= CDRMessage::addUInt32(msg, this->plugin_security_attributes); + return valid; +} + +#endif diff --git a/src/cpp/rtps/builtin/data/ParticipantProxyData.cpp b/src/cpp/rtps/builtin/data/ParticipantProxyData.cpp index 45a1c6221fd..883727c7b91 100644 --- a/src/cpp/rtps/builtin/data/ParticipantProxyData.cpp +++ b/src/cpp/rtps/builtin/data/ParticipantProxyData.cpp @@ -42,10 +42,15 @@ namespace fastrtps{ namespace rtps { ParticipantProxyData::ParticipantProxyData(): + m_protocolVersion(c_ProtocolVersion), m_VendorId(c_VendorId_Unknown), m_expectsInlineQos(false), m_availableBuiltinEndpoints(0), m_manualLivelinessCount(0), +#if HAVE_SECURITY + security_attributes_(0UL), + plugin_security_attributes_(0UL), +#endif isAlive(false), mp_leaseDurationTimer(nullptr) { @@ -65,8 +70,12 @@ ParticipantProxyData::ParticipantProxyData(const ParticipantProxyData& pdata) : m_participantName(pdata.m_participantName), m_key(pdata.m_key), m_leaseDuration(pdata.m_leaseDuration), +#if HAVE_SECURITY identity_token_(pdata.identity_token_), permissions_token_(pdata.permissions_token_), + security_attributes_(pdata.security_attributes_), + plugin_security_attributes_(pdata.plugin_security_attributes_), +#endif isAlive(pdata.isAlive), m_properties(pdata.m_properties), m_userData(pdata.m_userData), @@ -169,6 +178,7 @@ ParameterList_t ParticipantProxyData::AllQostoParameterList() parameter_list.m_parameters.push_back((Parameter_t*)p); } +#if HAVE_SECURITY if(!this->identity_token_.class_id().empty()) { ParameterToken_t* p = new ParameterToken_t(PID_IDENTITY_TOKEN, 0); @@ -176,7 +186,6 @@ ParameterList_t ParticipantProxyData::AllQostoParameterList() parameter_list.m_parameters.push_back((Parameter_t*)p); } - if(!this->permissions_token_.class_id().empty()) { ParameterToken_t* p = new ParameterToken_t(PID_PERMISSIONS_TOKEN, 0); @@ -184,14 +193,23 @@ ParameterList_t ParticipantProxyData::AllQostoParameterList() parameter_list.m_parameters.push_back((Parameter_t*)p); } + if ((this->security_attributes_ != 0UL) || (this->plugin_security_attributes_ != 0UL)) + { + ParameterParticipantSecurityInfo_t* p = new ParameterParticipantSecurityInfo_t(); + p->security_attributes = this->security_attributes_; + p->plugin_security_attributes = this->plugin_security_attributes_; + parameter_list.m_parameters.push_back((Parameter_t*)p); + } +#endif + return parameter_list; } -bool ParticipantProxyData::readFromCDRMessage(CDRMessage_t* msg) +bool ParticipantProxyData::readFromCDRMessage(CDRMessage_t* msg, bool use_encapsulation) { ParameterList_t parameter_list; - if(ParameterList::readParameterListfromCDRMsg(msg, ¶meter_list, NULL, true) > 0) + if(ParameterList::readParameterListfromCDRMsg(msg, ¶meter_list, NULL, use_encapsulation) > 0) { for(std::vector::iterator it = parameter_list.m_parameters.begin(); it!=parameter_list.m_parameters.end();++it) @@ -314,22 +332,41 @@ bool ParticipantProxyData::readFromCDRMessage(CDRMessage_t* msg) // } // } } - case PID_USER_DATA: + case PID_USER_DATA: { UserDataQosPolicy*p = (UserDataQosPolicy*)(*it); this->m_userData = p->getDataVec(); break; } - case PID_IDENTITY_TOKEN: + case PID_IDENTITY_TOKEN: { +#if HAVE_SECURITY ParameterToken_t* p = (ParameterToken_t*)(*it); this->identity_token_ = std::move(p->token); +#else + logWarning(RTPS_PARTICIPANT, "Received PID_IDENTITY_TOKEN but security is disabled"); +#endif break; } - case PID_PERMISSIONS_TOKEN: + case PID_PERMISSIONS_TOKEN: { +#if HAVE_SECURITY ParameterToken_t* p = (ParameterToken_t*)(*it); this->permissions_token_ = std::move(p->token); +#else + logWarning(RTPS_PARTICIPANT, "Received PID_PERMISSIONS_TOKEN but security is disabled"); +#endif + break; + } + case PID_PARTICIPANT_SECURITY_INFO: + { +#if HAVE_SECURITY + ParameterParticipantSecurityInfo_t* p = (ParameterParticipantSecurityInfo_t*)(*it); + this->security_attributes_ = p->security_attributes; + this->plugin_security_attributes_ = p->plugin_security_attributes; +#else + logWarning(RTPS_PARTICIPANT, "Received PID_PARTICIPANT_SECURITY_INFO but security is disabled"); +#endif break; } @@ -360,8 +397,12 @@ bool ParticipantProxyData::readFromCDRMessage(CDRMessage_t* msg) m_key = InstanceHandle_t(); m_leaseDuration = Duration_t(); isAlive = true; +#if HAVE_SECURITY identity_token_ = IdentityToken(); permissions_token_ = PermissionsToken(); + security_attributes_ = 0UL; + plugin_security_attributes_ = 0UL; +#endif m_properties.properties.clear(); m_properties.length = 0; m_userData.clear(); @@ -385,8 +426,12 @@ bool ParticipantProxyData::readFromCDRMessage(CDRMessage_t* msg) isAlive = pdata.isAlive; m_properties = pdata.m_properties; m_userData = pdata.m_userData; +#if HAVE_SECURITY identity_token_ = pdata.identity_token_; permissions_token_ = pdata.permissions_token_; + security_attributes_ = pdata.security_attributes_; + plugin_security_attributes_ = pdata.plugin_security_attributes_; +#endif } bool ParticipantProxyData::updateData(ParticipantProxyData& pdata) @@ -400,8 +445,12 @@ bool ParticipantProxyData::readFromCDRMessage(CDRMessage_t* msg) m_leaseDuration = pdata.m_leaseDuration; m_userData = pdata.m_userData; isAlive = true; +#if HAVE_SECURITY identity_token_ = pdata.identity_token_; permissions_token_ = pdata.permissions_token_; + security_attributes_ = pdata.security_attributes_; + plugin_security_attributes_ = pdata.plugin_security_attributes_; +#endif if(this->mp_leaseDurationTimer != nullptr) { mp_leaseDurationTimer->cancel_timer(); diff --git a/src/cpp/rtps/builtin/data/ReaderProxyData.cpp b/src/cpp/rtps/builtin/data/ReaderProxyData.cpp index d3a3b8ac351..2e15746db1f 100644 --- a/src/cpp/rtps/builtin/data/ReaderProxyData.cpp +++ b/src/cpp/rtps/builtin/data/ReaderProxyData.cpp @@ -30,6 +30,10 @@ namespace rtps { ReaderProxyData::ReaderProxyData() : m_expectsInlineQos(false) +#if HAVE_SECURITY + , security_attributes_(0UL) + , plugin_security_attributes_(0UL) +#endif , m_userDefinedId(0) , m_isAlive(true) , m_topicKind(NO_KEY) @@ -45,6 +49,10 @@ ReaderProxyData::~ReaderProxyData() ReaderProxyData::ReaderProxyData(const ReaderProxyData& readerInfo) : m_expectsInlineQos(readerInfo.m_expectsInlineQos) +#if HAVE_SECURITY + , security_attributes_(readerInfo.security_attributes_) + , plugin_security_attributes_(readerInfo.plugin_security_attributes_) +#endif , m_guid(readerInfo.m_guid) , m_unicastLocatorList(readerInfo.m_unicastLocatorList) , m_multicastLocatorList(readerInfo.m_multicastLocatorList) @@ -65,6 +73,10 @@ ReaderProxyData::ReaderProxyData(const ReaderProxyData& readerInfo) ReaderProxyData& ReaderProxyData::operator=(const ReaderProxyData& readerInfo) { m_expectsInlineQos = readerInfo.m_expectsInlineQos; +#if HAVE_SECURITY + security_attributes_ = readerInfo.security_attributes_; + plugin_security_attributes_ = readerInfo.plugin_security_attributes_; +#endif m_guid = readerInfo.m_guid; m_unicastLocatorList = readerInfo.m_unicastLocatorList; m_multicastLocatorList = readerInfo.m_multicastLocatorList; @@ -245,6 +257,14 @@ ParameterList_t ReaderProxyData::toParameterList() parameter_list.m_parameters.push_back((Parameter_t*)p); } } +#if HAVE_SECURITY + { + ParameterEndpointSecurityInfo_t*p = new ParameterEndpointSecurityInfo_t(); + p->security_attributes = security_attributes_; + p->plugin_security_attributes = plugin_security_attributes_; + parameter_list.m_parameters.push_back((Parameter_t*)p); + } +#endif logInfo(RTPS_PROXY_DATA,"DiscoveredReaderData converted to ParameterList with " << parameter_list.m_parameters.size()<< " parameters"); return parameter_list; @@ -449,6 +469,14 @@ bool ReaderProxyData::readFromCDRMessage(CDRMessage_t* msg) } break; } +#if HAVE_SECURITY + case PID_ENDPOINT_SECURITY_INFO: + { + ParameterEndpointSecurityInfo_t*p=(ParameterEndpointSecurityInfo_t*)(*it); + security_attributes_ = p->security_attributes; + plugin_security_attributes_ = p->plugin_security_attributes; + } +#endif default: { //logInfo(RTPS_PROXY_DATA,"Parameter with ID: " <<(uint16_t)(*it)->Pid << " NOT CONSIDERED"); diff --git a/src/cpp/rtps/builtin/data/WriterProxyData.cpp b/src/cpp/rtps/builtin/data/WriterProxyData.cpp index 2f88c9eda07..232f3223da3 100644 --- a/src/cpp/rtps/builtin/data/WriterProxyData.cpp +++ b/src/cpp/rtps/builtin/data/WriterProxyData.cpp @@ -29,7 +29,13 @@ namespace rtps { WriterProxyData::WriterProxyData() +#if HAVE_SECURITY + : security_attributes_(0) + , plugin_security_attributes_(0) + , m_userDefinedId(0) +#else : m_userDefinedId(0) +#endif , m_typeMaxSerialized(0) , m_isAlive(true) , m_topicKind(NO_KEY) @@ -39,7 +45,13 @@ WriterProxyData::WriterProxyData() } WriterProxyData::WriterProxyData(const WriterProxyData& writerInfo) +#if HAVE_SECURITY + : security_attributes_(writerInfo.security_attributes_) + , plugin_security_attributes_(writerInfo.plugin_security_attributes_) + , m_guid(writerInfo.m_guid) +#else : m_guid(writerInfo.m_guid) +#endif , m_unicastLocatorList(writerInfo.m_unicastLocatorList) , m_multicastLocatorList(writerInfo.m_multicastLocatorList) , m_key(writerInfo.m_key) @@ -65,6 +77,10 @@ WriterProxyData::~WriterProxyData() { WriterProxyData& WriterProxyData::operator=(const WriterProxyData& writerInfo) { +#if HAVE_SECURITY + security_attributes_ = writerInfo.security_attributes_; + plugin_security_attributes_ = writerInfo.plugin_security_attributes_; +#endif m_guid = writerInfo.m_guid; m_unicastLocatorList = writerInfo.m_unicastLocatorList; m_multicastLocatorList = writerInfo.m_multicastLocatorList; @@ -251,6 +267,14 @@ ParameterList_t WriterProxyData::toParameterList() parameter_list.m_parameters.push_back((Parameter_t*)p); } } +#if HAVE_SECURITY + { + ParameterEndpointSecurityInfo_t*p = new ParameterEndpointSecurityInfo_t(); + p->security_attributes = security_attributes_; + p->plugin_security_attributes = plugin_security_attributes_; + parameter_list.m_parameters.push_back((Parameter_t*)p); + } +#endif logInfo(RTPS_PROXY_DATA," with " << parameter_list.m_parameters.size()<< " parameters"); return parameter_list; @@ -449,6 +473,14 @@ bool WriterProxyData::readFromCDRMessage(CDRMessage_t* msg) } break; } +#if HAVE_SECURITY + case PID_ENDPOINT_SECURITY_INFO: + { + ParameterEndpointSecurityInfo_t*p=(ParameterEndpointSecurityInfo_t*)(*it); + security_attributes_ = p->security_attributes; + plugin_security_attributes_ = p->plugin_security_attributes; + } +#endif default: { //logInfo(RTPS_PROXY_DATA,"Parameter with ID: " << (uint16_t)(*it)->Pid <<" NOT CONSIDERED"); diff --git a/src/cpp/rtps/builtin/discovery/endpoint/EDP.cpp b/src/cpp/rtps/builtin/discovery/endpoint/EDP.cpp index dba6dbc80c1..45f776b184e 100644 --- a/src/cpp/rtps/builtin/discovery/endpoint/EDP.cpp +++ b/src/cpp/rtps/builtin/discovery/endpoint/EDP.cpp @@ -75,6 +75,10 @@ bool EDP::newLocalReaderProxyData(RTPSReader* reader, TopicAttributes& att, Read rpd.topicDiscoveryKind(att.getTopicDiscoveryKind()); rpd.m_qos = rqos; rpd.userDefinedId(reader->getAttributes().getUserDefinedID()); +#if HAVE_SECURITY + rpd.security_attributes_ = reader->getAttributes().security_attributes().mask(); + rpd.plugin_security_attributes_ = reader->getAttributes().security_attributes().plugin_endpoint_attributes; +#endif reader->m_acceptMessagesFromUnkownWriters = false; if (att.getTopicDiscoveryKind() != NO_CHECK) @@ -153,6 +157,10 @@ bool EDP::newLocalWriterProxyData(RTPSWriter* writer,TopicAttributes& att, Write wpd.m_qos = wqos; wpd.userDefinedId(writer->getAttributes().getUserDefinedID()); wpd.persistence_guid(writer->getAttributes().persistence_guid); +#if HAVE_SECURITY + wpd.security_attributes_ = writer->getAttributes().security_attributes().mask(); + wpd.plugin_security_attributes_ = writer->getAttributes().security_attributes().plugin_endpoint_attributes; +#endif if (att.getTopicDiscoveryKind() != NO_CHECK) { @@ -354,6 +362,11 @@ bool EDP::validMatching(const WriterProxyData* wdata, const ReaderProxyData* rda << rdata->guid() << " has different Ownership Kind"); return false; } + +#if HAVE_SECURITY + // TODO: Check EndpointSecurityInfo +#endif + //Partition check: bool matched = false; if(wdata->m_qos.m_partition.names.empty() && rdata->m_qos.m_partition.names.empty()) @@ -450,6 +463,10 @@ bool EDP::validMatching(const ReaderProxyData* rdata, const WriterProxyData* wda logWarning(RTPS_EDP, "INCOMPATIBLE QOS (topic: " << wdata->topicName() << "):Remote Writer " << wdata->guid() << " has different Ownership Kind" << endl;); return false; } +#if HAVE_SECURITY + // TODO: Check EndpointSecurityInfo +#endif + //Partition check: bool matched = false; if(rdata->m_qos.m_partition.names.empty() && wdata->m_qos.m_partition.names.empty()) @@ -1045,7 +1062,7 @@ bool EDP::checkTypeIdentifier(const TypeIdentifier * wti, const TypeIdentifier * */ bool EDP::checkTypeIdentifier(const WriterProxyData* wdata, const ReaderProxyData* rdata) const { - if (wdata->topicDiscoveryKind() == NO_CHECK && rdata->topicDiscoveryKind() == NO_CHECK) + if (wdata->topicDiscoveryKind() == NO_CHECK || rdata->topicDiscoveryKind() == NO_CHECK) { return true; } diff --git a/src/cpp/rtps/builtin/discovery/endpoint/EDPSimple.cpp b/src/cpp/rtps/builtin/discovery/endpoint/EDPSimple.cpp index 99704cb65bf..1d5d3bfc02f 100644 --- a/src/cpp/rtps/builtin/discovery/endpoint/EDPSimple.cpp +++ b/src/cpp/rtps/builtin/discovery/endpoint/EDPSimple.cpp @@ -295,6 +295,10 @@ bool EDPSimple::create_sedp_secure_endpoints() bool created = true; RTPSReader* raux = nullptr; RTPSWriter* waux = nullptr; + + auto& part_attr = mp_RTPSParticipant->security_attributes(); + security::PluginParticipantSecurityAttributes plugin_part_attr(part_attr.plugin_participant_attributes); + if(m_discovery.m_simpleEDP.enable_builtin_secure_publications_writer_and_subscriptions_reader) { hatt.initialReservedCaches = 100; @@ -313,8 +317,16 @@ bool EDPSimple::create_sedp_secure_endpoints() watt.times.nackResponseDelay.fraction = 0; watt.times.initialHeartbeatDelay.seconds = 0; watt.times.initialHeartbeatDelay.fraction = 0; - watt.endpoint.security_attributes().is_submessage_protected = - mp_RTPSParticipant->security_attributes().is_discovered_protected; + watt.endpoint.security_attributes().is_submessage_protected = part_attr.is_discovery_protected; + watt.endpoint.security_attributes().plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (part_attr.is_discovery_protected) + { + if (plugin_part_attr.is_discovery_encrypted) + watt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (plugin_part_attr.is_discovery_origin_authenticated) + watt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + } + if(mp_RTPSParticipant->getRTPSParticipantAttributes().throughputController.bytesPerPeriod != UINT32_MAX && mp_RTPSParticipant->getRTPSParticipantAttributes().throughputController.periodMillisecs != 0) watt.mode = ASYNCHRONOUS_WRITER; @@ -348,8 +360,15 @@ bool EDPSimple::create_sedp_secure_endpoints() ratt.times.heartbeatResponseDelay.fraction = 0; ratt.times.initialAcknackDelay.seconds = 0; ratt.times.initialAcknackDelay.fraction = 0; - ratt.endpoint.security_attributes().is_submessage_protected = - mp_RTPSParticipant->security_attributes().is_discovered_protected; + ratt.endpoint.security_attributes().is_submessage_protected = part_attr.is_discovery_protected; + ratt.endpoint.security_attributes().plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (part_attr.is_discovery_protected) + { + if (plugin_part_attr.is_discovery_encrypted) + ratt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (plugin_part_attr.is_discovery_origin_authenticated) + ratt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + } created &=this->mp_RTPSParticipant->createReader(&raux, ratt, sedp_builtin_subscriptions_secure_reader_.second, mp_subListen, sedp_builtin_subscriptions_secure_reader, true); if(created) @@ -384,8 +403,15 @@ bool EDPSimple::create_sedp_secure_endpoints() ratt.times.heartbeatResponseDelay.fraction = 0; ratt.times.initialAcknackDelay.seconds = 0; ratt.times.initialAcknackDelay.fraction = 0; - ratt.endpoint.security_attributes().is_submessage_protected = - mp_RTPSParticipant->security_attributes().is_discovered_protected; + ratt.endpoint.security_attributes().is_submessage_protected = part_attr.is_discovery_protected; + ratt.endpoint.security_attributes().plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (part_attr.is_discovery_protected) + { + if (plugin_part_attr.is_discovery_encrypted) + ratt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (plugin_part_attr.is_discovery_origin_authenticated) + ratt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + } created &=this->mp_RTPSParticipant->createReader(&raux, ratt, sedp_builtin_publications_secure_reader_.second, mp_pubListen, sedp_builtin_publications_secure_reader, true); if(created) @@ -416,8 +442,15 @@ bool EDPSimple::create_sedp_secure_endpoints() watt.times.nackResponseDelay.fraction = 0; watt.times.initialHeartbeatDelay.seconds = 0; watt.times.initialHeartbeatDelay.fraction = 0; - watt.endpoint.security_attributes().is_submessage_protected = - mp_RTPSParticipant->security_attributes().is_discovered_protected; + watt.endpoint.security_attributes().is_submessage_protected = part_attr.is_discovery_protected; + watt.endpoint.security_attributes().plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (part_attr.is_discovery_protected) + { + if (plugin_part_attr.is_discovery_encrypted) + watt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (plugin_part_attr.is_discovery_origin_authenticated) + watt.endpoint.security_attributes().plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + } if(mp_RTPSParticipant->getRTPSParticipantAttributes().throughputController.bytesPerPeriod != UINT32_MAX && mp_RTPSParticipant->getRTPSParticipantAttributes().throughputController.periodMillisecs != 0) watt.mode = ASYNCHRONOUS_WRITER; @@ -450,7 +483,7 @@ bool EDPSimple::processLocalReaderProxyData(RTPSReader* local_reader, ReaderProx auto* reader = &mp_SubReader; #if HAVE_SECURITY - if(local_reader->getAttributes().security_attributes().is_discovered_protected) + if(local_reader->getAttributes().security_attributes().is_discovery_protected) { writer = &sedp_builtin_subscriptions_secure_writer_; reader = &sedp_builtin_subscriptions_secure_reader_; @@ -515,7 +548,7 @@ bool EDPSimple::processLocalWriterProxyData(RTPSWriter* local_writer, WriterProx auto* reader = &mp_PubReader; #if HAVE_SECURITY - if(local_writer->getAttributes().security_attributes().is_discovered_protected) + if(local_writer->getAttributes().security_attributes().is_discovery_protected) { writer = &sedp_builtin_publications_secure_writer_; reader = &sedp_builtin_publications_secure_reader_; @@ -576,7 +609,7 @@ bool EDPSimple::removeLocalWriter(RTPSWriter* W) auto* reader = &mp_PubReader; #if HAVE_SECURITY - if(W->getAttributes().security_attributes().is_discovered_protected) + if(W->getAttributes().security_attributes().is_discovery_protected) { writer = &sedp_builtin_publications_secure_writer_; reader = &sedp_builtin_publications_secure_reader_; @@ -621,7 +654,7 @@ bool EDPSimple::removeLocalReader(RTPSReader* R) auto* reader = &mp_SubReader; #if HAVE_SECURITY - if(R->getAttributes().security_attributes().is_discovered_protected) + if(R->getAttributes().security_attributes().is_discovery_protected) { writer = &sedp_builtin_subscriptions_secure_writer_; reader = &sedp_builtin_subscriptions_secure_reader_; @@ -761,7 +794,7 @@ void EDPSimple::assignRemoteEndpoints(const ParticipantProxyData& pdata) } auxendp = endp; - auxendp &= DISC_BUILTIN_ENDPOINT_PUBLICATION_SECURE_DETECTOR + auxendp &= DISC_BUILTIN_ENDPOINT_PUBLICATION_SECURE_DETECTOR; //FIXME: FIX TO NOT FAIL WITH BAD BUILTIN ENDPOINT SET //auxendp = 1; if(auxendp != 0 && sedp_builtin_publications_secure_writer_.first!=nullptr) @@ -807,7 +840,7 @@ void EDPSimple::assignRemoteEndpoints(const ParticipantProxyData& pdata) } auxendp = endp; - auxendp &= DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_SECURE_DETECTOR + auxendp &= DISC_BUILTIN_ENDPOINT_SUBSCRIPTION_SECURE_DETECTOR; //FIXME: FIX TO NOT FAIL WITH BAD BUILTIN ENDPOINT SET //auxendp = 1; if(auxendp != 0 && sedp_builtin_subscriptions_secure_writer_.first!=nullptr) diff --git a/src/cpp/rtps/builtin/discovery/participant/PDPSimple.cpp b/src/cpp/rtps/builtin/discovery/participant/PDPSimple.cpp index a8a9d00ee52..fbb88bdd2fe 100644 --- a/src/cpp/rtps/builtin/discovery/participant/PDPSimple.cpp +++ b/src/cpp/rtps/builtin/discovery/participant/PDPSimple.cpp @@ -113,10 +113,20 @@ void PDPSimple::initializeParticipantProxyData(ParticipantProxyData* participant participant_data->m_availableBuiltinEndpoints |= DISC_BUILTIN_ENDPOINT_PARTICIPANT_ANNOUNCER; participant_data->m_availableBuiltinEndpoints |= DISC_BUILTIN_ENDPOINT_PARTICIPANT_DETECTOR; +#if HAVE_SECURITY + participant_data->m_availableBuiltinEndpoints |= DISC_BUILTIN_ENDPOINT_PARTICIPANT_SECURE_ANNOUNCER; + participant_data->m_availableBuiltinEndpoints |= DISC_BUILTIN_ENDPOINT_PARTICIPANT_SECURE_DETECTOR; +#endif + if(mp_RTPSParticipant->getAttributes().builtin.use_WriterLivelinessProtocol) { participant_data->m_availableBuiltinEndpoints |= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_WRITER; participant_data->m_availableBuiltinEndpoints |= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_READER; + +#if HAVE_SECURITY + participant_data->m_availableBuiltinEndpoints |= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_WRITER; + participant_data->m_availableBuiltinEndpoints |= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_READER; +#endif } if(mp_RTPSParticipant->getAttributes().builtin.use_SIMPLE_EndpointDiscoveryProtocol) @@ -186,6 +196,10 @@ void PDPSimple::initializeParticipantProxyData(ParticipantProxyData* participant participant_data->permissions_token_ = std::move(*permissions_token); mp_RTPSParticipant->security_manager().return_permissions_token(permissions_token); } + + auto sec_attrs = mp_RTPSParticipant->security_attributes(); + participant_data->security_attributes_ = sec_attrs.mask(); + participant_data->plugin_security_attributes_ = sec_attrs.plugin_participant_attributes; #endif } @@ -878,7 +892,7 @@ CDRMessage_t PDPSimple::get_participant_proxy_data_serialized(Endianness_t endia cdr_msg.msg_endian = endian; ParameterList_t parameter_list = getLocalParticipantProxyData()->AllQostoParameterList(); - if(!ParameterList::writeParameterListToCDRMsg(&cdr_msg, ¶meter_list, true)) + if(!ParameterList::writeParameterListToCDRMsg(&cdr_msg, ¶meter_list, false)) { cdr_msg.pos = 0; cdr_msg.length = 0; diff --git a/src/cpp/rtps/builtin/liveliness/WLP.cpp b/src/cpp/rtps/builtin/liveliness/WLP.cpp index 5be897f3518..e293859f5b8 100644 --- a/src/cpp/rtps/builtin/liveliness/WLP.cpp +++ b/src/cpp/rtps/builtin/liveliness/WLP.cpp @@ -55,14 +55,23 @@ WLP::WLP(BuiltinProtocols* p): m_minAutomatic_MilliSec(std::numeric_limitsdeleteUserEndpoint(mp_builtinReaderSecure); + mp_participant->deleteUserEndpoint(mp_builtinWriterSecure); + delete(this->mp_builtinReaderSecureHistory); + delete(this->mp_builtinWriterSecureHistory); +#endif mp_participant->deleteUserEndpoint(mp_builtinReader); mp_participant->deleteUserEndpoint(mp_builtinWriter); delete(this->mp_builtinReaderHistory); @@ -78,7 +87,12 @@ bool WLP::initWL(RTPSParticipantImpl* p) { logInfo(RTPS_LIVELINESS,"Beginning Liveliness Protocol"); mp_participant = p; - return createEndpoints(); + + bool retVal = createEndpoints(); +#if HAVE_SECURITY + if(retVal) createSecureEndpoints(); +#endif + return retVal; } bool WLP::createEndpoints() @@ -150,16 +164,103 @@ bool WLP::createEndpoints() return true; } +#if HAVE_SECURITY + +bool WLP::createSecureEndpoints() +{ + //CREATE WRITER + HistoryAttributes hatt; + hatt.initialReservedCaches = 20; + hatt.maximumReservedCaches = 1000; + hatt.payloadMaxSize = BUILTIN_PARTICIPANT_DATA_MAX_SIZE; + mp_builtinWriterSecureHistory = new WriterHistory(hatt); + WriterAttributes watt; + watt.endpoint.unicastLocatorList = mp_builtinProtocols->m_metatrafficUnicastLocatorList; + watt.endpoint.multicastLocatorList = mp_builtinProtocols->m_metatrafficMulticastLocatorList; + // Wparam.topic.topicName = "DCPSParticipantMessageSecure"; + // Wparam.topic.topicDataType = "RTPSParticipantMessageData"; + watt.endpoint.topicKind = WITH_KEY; + watt.endpoint.durabilityKind = TRANSIENT_LOCAL; + watt.endpoint.reliabilityKind = RELIABLE; + if (mp_participant->getRTPSParticipantAttributes().throughputController.bytesPerPeriod != UINT32_MAX && + mp_participant->getRTPSParticipantAttributes().throughputController.periodMillisecs != 0) + watt.mode = ASYNCHRONOUS_WRITER; + + const security::ParticipantSecurityAttributes& part_attrs = mp_participant->security_attributes(); + security::PluginParticipantSecurityAttributes plugin_attrs(part_attrs.plugin_participant_attributes); + security::EndpointSecurityAttributes& sec_attrs = watt.endpoint.security_attributes(); + sec_attrs.is_submessage_protected = part_attrs.is_liveliness_protected; + if (part_attrs.is_liveliness_protected) + { + sec_attrs.plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (plugin_attrs.is_liveliness_encrypted) + sec_attrs.plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (plugin_attrs.is_liveliness_origin_authenticated) + sec_attrs.plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + } + + RTPSWriter* wout; + if (mp_participant->createWriter(&wout, watt, mp_builtinWriterSecureHistory, nullptr, c_EntityId_WriterLivelinessSecure, true)) + { + mp_builtinWriterSecure = dynamic_cast(wout); + logInfo(RTPS_LIVELINESS, "Builtin Secure Liveliness Writer created"); + } + else + { + logError(RTPS_LIVELINESS, "Secure Liveliness Writer Creation failed "); + delete(mp_builtinWriterSecureHistory); + mp_builtinWriterSecureHistory = nullptr; + return false; + } + hatt.initialReservedCaches = 100; + hatt.maximumReservedCaches = 2000; + hatt.payloadMaxSize = BUILTIN_PARTICIPANT_DATA_MAX_SIZE; + mp_builtinReaderSecureHistory = new ReaderHistory(hatt); + ReaderAttributes ratt; + ratt.endpoint.topicKind = WITH_KEY; + ratt.endpoint.durabilityKind = TRANSIENT_LOCAL; + ratt.endpoint.reliabilityKind = RELIABLE; + ratt.expectsInlineQos = true; + ratt.endpoint.unicastLocatorList = mp_builtinProtocols->m_metatrafficUnicastLocatorList; + ratt.endpoint.multicastLocatorList = mp_builtinProtocols->m_metatrafficMulticastLocatorList; + //Rparam.topic.topicName = "DCPSParticipantMessageSecure"; + //Rparam.topic.topicDataType = "RTPSParticipantMessageData"; + ratt.endpoint.topicKind = WITH_KEY; + sec_attrs = ratt.endpoint.security_attributes(); + sec_attrs.is_submessage_protected = part_attrs.is_liveliness_protected; + if (part_attrs.is_liveliness_protected) + { + sec_attrs.plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID; + if (plugin_attrs.is_liveliness_encrypted) + sec_attrs.plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + if (plugin_attrs.is_liveliness_origin_authenticated) + sec_attrs.plugin_endpoint_attributes |= PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + } + RTPSReader* rout; + if (mp_participant->createReader(&rout, ratt, mp_builtinReaderSecureHistory, (ReaderListener*)mp_listener, c_EntityId_ReaderLivelinessSecure, true)) + { + mp_builtinReaderSecure = dynamic_cast(rout); + logInfo(RTPS_LIVELINESS, "Builtin Liveliness Reader created"); + } + else + { + logError(RTPS_LIVELINESS, "Liveliness Reader Creation failed."); + delete(mp_builtinReaderSecureHistory); + mp_builtinReaderSecureHistory = nullptr; + return false; + } + + return true; +} +#endif + bool WLP::assignRemoteEndpoints(const ParticipantProxyData& pdata) { uint32_t endp = pdata.m_availableBuiltinEndpoints; uint32_t partdet = endp; uint32_t auxendp = endp; - //TODO Hacer el check con RTI y solo añadirlo cuando el vendor ID sea RTI. partdet &= DISC_BUILTIN_ENDPOINT_PARTICIPANT_DETECTOR; //Habria que quitar esta linea que comprueba si tiene PDP. auxendp &= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_WRITER; - //auxendp = 1; - //FIXME: WRITERLIVELINESS PUT THIS BACK TO THE ORIGINAL LINE if((auxendp!=0 || partdet!=0) && this->mp_builtinReader!=nullptr) { @@ -177,8 +278,6 @@ bool WLP::assignRemoteEndpoints(const ParticipantProxyData& pdata) } auxendp = endp; auxendp &=BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_READER; - //auxendp = 1; - //FIXME: WRITERLIVELINESS PUT THIS BACK TO THE ORIGINAL LINE if((auxendp!=0 || partdet!=0) && this->mp_builtinWriter!=nullptr) { logInfo(RTPS_LIVELINESS,"Adding remote reader to my local Builtin Writer"); @@ -193,6 +292,44 @@ bool WLP::assignRemoteEndpoints(const ParticipantProxyData& pdata) ratt.endpoint.reliabilityKind = RELIABLE; mp_builtinWriter->matched_reader_add(ratt); } + +#if HAVE_SECURITY + auxendp = endp; + auxendp &= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_WRITER; + if ((auxendp != 0 || partdet != 0) && this->mp_builtinReaderSecure != nullptr) + { + logInfo(RTPS_LIVELINESS, "Adding remote writer to my local Builtin Secure Reader"); + RemoteWriterAttributes watt(pdata.m_VendorId); + watt.guid.guidPrefix = pdata.m_guid.guidPrefix; + watt.guid.entityId = c_EntityId_WriterLivelinessSecure; + watt.endpoint.persistence_guid = watt.guid; + watt.endpoint.unicastLocatorList = pdata.m_metatrafficUnicastLocatorList; + watt.endpoint.multicastLocatorList = pdata.m_metatrafficMulticastLocatorList; + watt.endpoint.topicKind = WITH_KEY; + watt.endpoint.durabilityKind = TRANSIENT_LOCAL; + watt.endpoint.reliabilityKind = RELIABLE; + watt.endpoint.security_attributes() = mp_builtinReaderSecure->getAttributes().security_attributes(); + mp_builtinReaderSecure->matched_writer_add(watt); + } + auxendp = endp; + auxendp &= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_READER; + if ((auxendp != 0 || partdet != 0) && this->mp_builtinWriterSecure != nullptr) + { + logInfo(RTPS_LIVELINESS, "Adding remote reader to my local Builtin Secure Writer"); + RemoteReaderAttributes ratt(pdata.m_VendorId); + ratt.expectsInlineQos = false; + ratt.guid.guidPrefix = pdata.m_guid.guidPrefix; + ratt.guid.entityId = c_EntityId_ReaderLivelinessSecure; + ratt.endpoint.unicastLocatorList = pdata.m_metatrafficUnicastLocatorList; + ratt.endpoint.multicastLocatorList = pdata.m_metatrafficMulticastLocatorList; + ratt.endpoint.topicKind = WITH_KEY; + ratt.endpoint.durabilityKind = TRANSIENT_LOCAL; + ratt.endpoint.reliabilityKind = RELIABLE; + ratt.endpoint.security_attributes() = mp_builtinWriterSecure->getAttributes().security_attributes(); + mp_builtinWriterSecure->matched_reader_add(ratt); + } +#endif + return true; } @@ -202,15 +339,12 @@ void WLP::removeRemoteEndpoints(ParticipantProxyData* pdata) uint32_t endp = pdata->m_availableBuiltinEndpoints; uint32_t partdet = endp; uint32_t auxendp = endp; - //TODO Hacer el check con RTI y solo añadirlo cuando el vendor ID sea RTI. partdet &= DISC_BUILTIN_ENDPOINT_PARTICIPANT_DETECTOR; //Habria que quitar esta linea que comprueba si tiene PDP. auxendp &= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_WRITER; - //auxendp = 1; - //FIXME: WRITERLIVELINESS PUT THIS BACK TO THE ORIGINAL LINE if((auxendp!=0 || partdet!=0) && this->mp_builtinReader!=nullptr) { - logInfo(RTPS_LIVELINESS,"Adding remote writer to my local Builtin Reader"); + logInfo(RTPS_LIVELINESS,"Removing remote writer from my local Builtin Reader"); RemoteWriterAttributes watt; watt.guid.guidPrefix = pdata->m_guid.guidPrefix; watt.guid.entityId = c_EntityId_WriterLiveliness; @@ -224,11 +358,9 @@ void WLP::removeRemoteEndpoints(ParticipantProxyData* pdata) } auxendp = endp; auxendp &=BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_READER; - //auxendp = 1; - //FIXME: WRITERLIVELINESS PUT THIS BACK TO THE ORIGINAL LINE if((auxendp!=0 || partdet!=0) && this->mp_builtinWriter!=nullptr) { - logInfo(RTPS_LIVELINESS,"Adding remote reader to my local Builtin Writer"); + logInfo(RTPS_LIVELINESS,"Removing remote reader from my local Builtin Writer"); RemoteReaderAttributes ratt; ratt.expectsInlineQos = false; ratt.guid.guidPrefix = pdata->m_guid.guidPrefix; @@ -240,6 +372,43 @@ void WLP::removeRemoteEndpoints(ParticipantProxyData* pdata) ratt.endpoint.reliabilityKind = RELIABLE; mp_builtinWriter->matched_reader_remove(ratt); } + +#if HAVE_SECURITY + auxendp = endp; + auxendp &= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_WRITER; + if ((auxendp != 0 || partdet != 0) && this->mp_builtinReaderSecure != nullptr) + { + logInfo(RTPS_LIVELINESS, "Removing remote writer from my local Builtin Secure Reader"); + RemoteWriterAttributes watt; + watt.guid.guidPrefix = pdata->m_guid.guidPrefix; + watt.guid.entityId = c_EntityId_WriterLivelinessSecure; + watt.endpoint.persistence_guid = watt.guid; + watt.endpoint.unicastLocatorList = pdata->m_metatrafficUnicastLocatorList; + watt.endpoint.multicastLocatorList = pdata->m_metatrafficMulticastLocatorList; + watt.endpoint.topicKind = WITH_KEY; + watt.endpoint.durabilityKind = TRANSIENT_LOCAL; + watt.endpoint.reliabilityKind = RELIABLE; + watt.endpoint.security_attributes() = mp_builtinReaderSecure->getAttributes().security_attributes(); + mp_builtinReaderSecure->matched_writer_remove(watt); + } + auxendp = endp; + auxendp &= BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_DATA_READER; + if ((auxendp != 0 || partdet != 0) && this->mp_builtinWriterSecure != nullptr) + { + logInfo(RTPS_LIVELINESS, "Removing remote reader from my local Builtin Secure Writer"); + RemoteReaderAttributes ratt; + ratt.expectsInlineQos = false; + ratt.guid.guidPrefix = pdata->m_guid.guidPrefix; + ratt.guid.entityId = c_EntityId_ReaderLivelinessSecure; + ratt.endpoint.unicastLocatorList = pdata->m_metatrafficUnicastLocatorList; + ratt.endpoint.multicastLocatorList = pdata->m_metatrafficMulticastLocatorList; + ratt.endpoint.topicKind = WITH_KEY; + ratt.endpoint.durabilityKind = TRANSIENT_LOCAL; + ratt.endpoint.reliabilityKind = RELIABLE; + ratt.endpoint.security_attributes() = mp_builtinWriterSecure->getAttributes().security_attributes(); + mp_builtinWriterSecure->matched_reader_remove(ratt); + } +#endif } @@ -449,6 +618,34 @@ bool WLP::updateLocalWriter(RTPSWriter* W, WriterQos& wqos) return true; } +StatefulWriter* WLP::getBuiltinWriter() +{ + StatefulWriter* ret_val = mp_builtinWriter; + +#if HAVE_SECURITY + if (mp_participant->security_attributes().is_liveliness_protected) + { + ret_val = mp_builtinWriterSecure; + } +#endif + + return ret_val; +} + +WriterHistory* WLP::getBuiltinWriterHistory() +{ + WriterHistory* ret_val = mp_builtinWriterHistory; + +#if HAVE_SECURITY + if (mp_participant->security_attributes().is_liveliness_protected) + { + ret_val = mp_builtinWriterSecureHistory; + } +#endif + + return ret_val; +} + } /* namespace rtps */ } /* namespace fastrtps */ } /* namespace eprosima */ diff --git a/src/cpp/rtps/builtin/liveliness/WLPListener.cpp b/src/cpp/rtps/builtin/liveliness/WLPListener.cpp index ed6776c1c22..341a42cc9d3 100644 --- a/src/cpp/rtps/builtin/liveliness/WLPListener.cpp +++ b/src/cpp/rtps/builtin/liveliness/WLPListener.cpp @@ -38,15 +38,12 @@ namespace fastrtps{ namespace rtps { -WLPListener::WLPListener(WLP* plwp): - mp_WLP(plwp) +WLPListener::WLPListener(WLP* plwp) : mp_WLP(plwp) { - free(aux_msg.buffer); } WLPListener::~WLPListener() { - aux_msg.buffer = nullptr; } @@ -65,13 +62,13 @@ void WLPListener::onNewCacheChangeAdded(RTPSReader* reader,const CacheChange_t* return; } //Check the serializedPayload: - for(auto ch = this->mp_WLP->mp_builtinReaderHistory->changesBegin(); - ch!=mp_WLP->mp_builtinReaderHistory->changesEnd();++ch) + auto history = reader->getHistory(); + for(auto ch = history->changesBegin(); ch!=history->changesEnd();++ch) { if((*ch)->instanceHandle == change->instanceHandle && (*ch)->sequenceNumber < change->sequenceNumber) { - mp_WLP->mp_builtinReaderHistory->remove_change(*ch); + history->remove_change(*ch); break; } } @@ -95,7 +92,7 @@ void WLPListener::onNewCacheChangeAdded(RTPSReader* reader,const CacheChange_t* if(guidP == reader->getGuid().guidPrefix) { logInfo(RTPS_LIVELINESS,"Message from own RTPSParticipant, ignoring"); - this->mp_WLP->mp_builtinReaderHistory->remove_change(change); + history->remove_change(change); return; } this->mp_WLP->getBuiltinProtocols()->mp_PDP->assertRemoteWritersLiveliness(guidP,livelinessKind); @@ -141,18 +138,9 @@ bool WLPListener::computeKey(CacheChange_t* change) if(change->instanceHandle == c_InstanceHandle_Unknown) { SerializedPayload_t* pl = &change->serializedPayload; - if(pl->length > 16) + if(pl->length >= 16) { - CDRMessage::initCDRMsg(&aux_msg); - aux_msg.buffer = pl->data; - aux_msg.length = pl->length; - aux_msg.max_size = pl->max_size; - aux_msg.msg_endian = pl->encapsulation == PL_CDR_BE ? BIGEND : LITTLEEND; - for(uint8_t i =0;i<16;++i) - { - change->instanceHandle.value[i] = aux_msg.buffer[i]; - } - aux_msg.buffer = nullptr; + memcpy(change->instanceHandle.value, pl->data, 16); return true; } return false; diff --git a/src/cpp/rtps/builtin/liveliness/timedevent/WLivelinessPeriodicAssertion.cpp b/src/cpp/rtps/builtin/liveliness/timedevent/WLivelinessPeriodicAssertion.cpp index b589fde2f98..3cb90b144d6 100644 --- a/src/cpp/rtps/builtin/liveliness/timedevent/WLivelinessPeriodicAssertion.cpp +++ b/src/cpp/rtps/builtin/liveliness/timedevent/WLivelinessPeriodicAssertion.cpp @@ -67,7 +67,7 @@ void WLivelinessPeriodicAssertion::event(EventCode code, const char* msg) if(code == EVENT_SUCCESS) { logInfo(RTPS_LIVELINESS,"Period: "<< this->getIntervalMilliSec()); - if(this->mp_WLP->mp_builtinWriter->getMatchedReadersSize()>0) + if(this->mp_WLP->getBuiltinWriter()->getMatchedReadersSize()>0) { if(m_livelinessKind == AUTOMATIC_LIVELINESS_QOS) AutomaticLivelinessAssertion(); @@ -92,8 +92,10 @@ bool WLivelinessPeriodicAssertion::AutomaticLivelinessAssertion() std::lock_guard guard(*this->mp_WLP->getBuiltinProtocols()->mp_PDP->getMutex()); if(this->mp_WLP->m_livAutomaticWriters.size()>0) { - std::lock_guard wguard(*this->mp_WLP->mp_builtinWriter->getMutex()); - CacheChange_t* change=this->mp_WLP->mp_builtinWriter->new_change([]() -> uint32_t {return BUILTIN_PARTICIPANT_DATA_MAX_SIZE;}, ALIVE,m_iHandle); + auto writer = this->mp_WLP->getBuiltinWriter(); + auto history = this->mp_WLP->getBuiltinWriterHistory(); + std::lock_guard wguard(*writer->getMutex()); + CacheChange_t* change=writer->new_change([]() -> uint32_t {return BUILTIN_PARTICIPANT_DATA_MAX_SIZE;}, ALIVE,m_iHandle); if(change!=nullptr) { //change->instanceHandle = m_iHandle; @@ -107,19 +109,19 @@ bool WLivelinessPeriodicAssertion::AutomaticLivelinessAssertion() change->serializedPayload.data[i] = 0; change->serializedPayload.data[15] = m_livelinessKind+1; change->serializedPayload.length = 12+4+4+4; - if(mp_WLP->mp_builtinWriterHistory->getHistorySize() > 0) + if(history->getHistorySize() > 0) { - for(std::vector::iterator chit = mp_WLP->mp_builtinWriterHistory->changesBegin(); - chit!=mp_WLP->mp_builtinWriterHistory->changesEnd();++chit) + for(std::vector::iterator chit = history->changesBegin(); + chit!=history->changesEnd();++chit) { if((*chit)->instanceHandle == change->instanceHandle) { - mp_WLP->mp_builtinWriterHistory->remove_change(*chit); + history->remove_change(*chit); break; } } } - mp_WLP->mp_builtinWriterHistory->add_change(change); + history->add_change(change); } } return true; @@ -140,8 +142,10 @@ bool WLivelinessPeriodicAssertion::ManualByRTPSParticipantLivelinessAssertion() } if(livelinessAsserted) { - std::lock_guard wguard(*this->mp_WLP->mp_builtinWriter->getMutex()); - CacheChange_t* change=this->mp_WLP->mp_builtinWriter->new_change([]() -> uint32_t {return BUILTIN_PARTICIPANT_DATA_MAX_SIZE;}, ALIVE); + auto writer = this->mp_WLP->getBuiltinWriter(); + auto history = this->mp_WLP->getBuiltinWriterHistory(); + std::lock_guard wguard(*writer->getMutex()); + CacheChange_t* change=writer->new_change([]() -> uint32_t {return BUILTIN_PARTICIPANT_DATA_MAX_SIZE;}, ALIVE); if(change!=nullptr) { change->instanceHandle = m_iHandle; @@ -156,15 +160,15 @@ bool WLivelinessPeriodicAssertion::ManualByRTPSParticipantLivelinessAssertion() change->serializedPayload.data[i] = 0; change->serializedPayload.data[15] = m_livelinessKind+1; change->serializedPayload.length = 12+4+4+4; - for(auto ch = mp_WLP->mp_builtinWriterHistory->changesBegin(); - ch!=mp_WLP->mp_builtinWriterHistory->changesEnd();++ch) + for(auto ch = history->changesBegin(); + ch!=history->changesEnd();++ch) { if((*ch)->instanceHandle == change->instanceHandle) { - mp_WLP->mp_builtinWriterHistory->remove_change(*ch); + history->remove_change(*ch); } } - mp_WLP->mp_builtinWriterHistory->add_change(change); + history->add_change(change); } } return false; diff --git a/src/cpp/rtps/messages/RTPSMessageGroup.cpp b/src/cpp/rtps/messages/RTPSMessageGroup.cpp index c1385da0c52..9f99bd419e9 100644 --- a/src/cpp/rtps/messages/RTPSMessageGroup.cpp +++ b/src/cpp/rtps/messages/RTPSMessageGroup.cpp @@ -306,7 +306,7 @@ bool RTPSMessageGroup::add_info_dst_in_buffer(CDRMessage_t* buffer, const std::v (void)remote_endpoints; bool added = false; -#if HAVE_SECURITY +#if FALSE // HAVE_SECURITY uint32_t from_buffer_position = buffer->pos; #endif @@ -325,7 +325,7 @@ bool RTPSMessageGroup::add_info_dst_in_buffer(CDRMessage_t* buffer, const std::v if(added) { -#if HAVE_SECURITY +#if FALSE // HAVE_SECURITY if(endpoint_->getAttributes().security_attributes().is_submessage_protected) { buffer->pos = from_buffer_position; diff --git a/src/cpp/rtps/participant/RTPSParticipantImpl.h b/src/cpp/rtps/participant/RTPSParticipantImpl.h index 281b6a194b1..cec1d7a770b 100644 --- a/src/cpp/rtps/participant/RTPSParticipantImpl.h +++ b/src/cpp/rtps/participant/RTPSParticipantImpl.h @@ -43,9 +43,9 @@ #include #include #include -#include #if HAVE_SECURITY +#include #include "../security/SecurityManager.h" #endif diff --git a/src/cpp/rtps/security/SecurityManager.cpp b/src/cpp/rtps/security/SecurityManager.cpp index e9e046ab915..a60f60c245a 100644 --- a/src/cpp/rtps/security/SecurityManager.cpp +++ b/src/cpp/rtps/security/SecurityManager.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -31,6 +32,8 @@ #include #include #include +#include +#include #include #include #include @@ -41,10 +44,12 @@ #include #include -#define BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_READER (1 << 22) -#define BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_WRITER (1 << 23) -#define BUILTIN_ENDPOINT_PARTICIPANT_VOLATILE_MESSAGE_SECURE_READER (1 << 24) -#define BUILTIN_ENDPOINT_PARTICIPANT_VOLATILE_MESSAGE_SECURE_WRITER (1 << 25) +#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_WRITER (1 << 20) +#define BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_SECURE_READER (1 << 21) +#define BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_WRITER (1 << 22) +#define BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_READER (1 << 23) +#define BUILTIN_ENDPOINT_PARTICIPANT_VOLATILE_MESSAGE_SECURE_WRITER (1 << 24) +#define BUILTIN_ENDPOINT_PARTICIPANT_VOLATILE_MESSAGE_SECURE_READER (1 << 25) #define AUTHENTICATION_PARTICIPANT_STATELESS_MESSAGE "dds.sec.auth" #define GMCLASSID_SECURITY_PARTICIPANT_CRYPTO_TOKENS "dds.sec.participant_crypto_tokens" @@ -98,7 +103,7 @@ bool SecurityManager::init(ParticipantSecurityAttributes& attributes, const Prop SecurityException exception; domain_id_ = participant_->getRTPSParticipantAttributes().builtin.domainId; - authentication_plugin_ = factory_.create_authentication_plugin(participant_->getRTPSParticipantAttributes().properties); + authentication_plugin_ = factory_.create_authentication_plugin(participant_properties); if(authentication_plugin_ != nullptr) { @@ -124,7 +129,7 @@ bool SecurityManager::init(ParticipantSecurityAttributes& attributes, const Prop // Set participant guid participant_->setGuid(adjusted_participant_key); - access_plugin_ = factory_.create_access_control_plugin(participant_->getRTPSParticipantAttributes().properties); + access_plugin_ = factory_.create_access_control_plugin(participant_properties); if(access_plugin_ != nullptr) { @@ -195,32 +200,35 @@ bool SecurityManager::init(ParticipantSecurityAttributes& attributes, const Prop } } + if (access_plugin_ == nullptr) + { + // Read participant properties. + const std::string* property_value = PropertyPolicyHelper::find_property(participant_properties, + "rtps.participant.rtps_protection_kind"); + if (property_value != nullptr && property_value->compare("ENCRYPT") == 0) + { + attributes.is_rtps_protected = true; + attributes.plugin_participant_attributes |= + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_VALID | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED; + } + } + if(access_plugin_ == nullptr || local_permissions_handle_ != nullptr) { - crypto_plugin_ = factory_.create_cryptography_plugin(participant_->getRTPSParticipantAttributes().properties); + crypto_plugin_ = factory_.create_cryptography_plugin(participant_properties); if(crypto_plugin_ != nullptr) { local_participant_crypto_handle_ = crypto_plugin_->cryptokeyfactory()->register_local_participant(*local_identity_handle_, *local_permissions_handle_, - participant_->getRTPSParticipantAttributes().properties.properties(), + participant_properties.properties(), + attributes, exception); if(local_participant_crypto_handle_ != nullptr) { assert(!local_participant_crypto_handle_->nil()); - - if(access_plugin_ == nullptr) - { - // Read participant properties. - const std::string* property_value = PropertyPolicyHelper::find_property(participant_properties, - "rtps.participant.rtps_protection_kind"); - if(property_value != nullptr && property_value->compare("ENCRYPT") == 0) - { - attributes.is_rtps_protected = true; - } - } - } else { @@ -432,6 +440,13 @@ bool SecurityManager::restore_discovered_participant_info(const GUID_t& remote_p bool SecurityManager::discovered_participant(const ParticipantProxyData& participant_data) { + // Early return when ParticipantSecurityInfo does not match + auto& sec_attrs = participant_->security_attributes(); + if(!sec_attrs.match(participant_data.security_attributes_, participant_data.plugin_security_attributes_)) + { + return false; + } + if(authentication_plugin_ == nullptr) { participant_->pdpsimple()->notifyAboveRemoteEndpoints(participant_data); @@ -699,11 +714,11 @@ bool SecurityManager::on_process_handshake(const ParticipantProxyData& participa #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -960,6 +975,8 @@ bool SecurityManager::create_participant_volatile_message_secure_writer() watt.endpoint.durabilityKind = VOLATILE; watt.endpoint.unicastLocatorList = participant_->getRTPSParticipantAttributes().builtin.metatrafficUnicastLocatorList; watt.endpoint.remoteLocatorList = participant_->getRTPSParticipantAttributes().builtin.initialPeersList; + watt.endpoint.security_attributes().is_submessage_protected = true; + watt.endpoint.security_attributes().plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; // TODO(Ricardo) Study keep_all if(participant_->getRTPSParticipantAttributes().throughputController.bytesPerPeriod != UINT32_MAX && @@ -1010,6 +1027,8 @@ bool SecurityManager::create_participant_volatile_message_secure_reader() ratt.endpoint.durabilityKind = VOLATILE; ratt.endpoint.unicastLocatorList = participant_->getRTPSParticipantAttributes().builtin.metatrafficUnicastLocatorList; ratt.endpoint.remoteLocatorList = participant_->getRTPSParticipantAttributes().builtin.initialPeersList; + ratt.endpoint.security_attributes().is_submessage_protected = true; + ratt.endpoint.security_attributes().plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; RTPSReader* rout = nullptr; if(participant_->createReader(&rout, ratt, participant_volatile_message_secure_reader_history_, &participant_volatile_message_secure_listener_, @@ -1122,9 +1141,9 @@ void SecurityManager::process_participant_stateless_message(const CacheChange_t* aux_msg.pos += 1; octet encapsulation = 0; CDRMessage::readOctet(&aux_msg, &encapsulation); - if(encapsulation == PL_CDR_BE) + if(encapsulation == CDR_BE) aux_msg.msg_endian = BIGEND; - else if(encapsulation == PL_CDR_LE) + else if(encapsulation == CDR_LE) aux_msg.msg_endian = LITTLEEND; else return; @@ -1320,9 +1339,9 @@ void SecurityManager::process_participant_volatile_message_secure(const CacheCha aux_msg.pos += 1; octet encapsulation = 0; CDRMessage::readOctet(&aux_msg, &encapsulation); - if(encapsulation == PL_CDR_BE) + if(encapsulation == CDR_BE) aux_msg.msg_endian = BIGEND; - else if(encapsulation == PL_CDR_LE) + else if(encapsulation == CDR_LE) aux_msg.msg_endian = LITTLEEND; else return; @@ -1628,8 +1647,8 @@ void SecurityManager::match_builtin_endpoints(const ParticipantProxyData& partic { uint32_t builtin_endpoints = participant_data.m_availableBuiltinEndpoints; - if(participant_stateless_message_reader_ != nullptr && - builtin_endpoints & BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_WRITER) + if (participant_stateless_message_reader_ != nullptr && + builtin_endpoints & BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_WRITER) { RemoteWriterAttributes watt(participant_data.m_VendorId); watt.guid.guidPrefix = participant_data.m_guid.guidPrefix; @@ -1640,8 +1659,8 @@ void SecurityManager::match_builtin_endpoints(const ParticipantProxyData& partic participant_stateless_message_reader_->matched_writer_add(watt); } - if(participant_stateless_message_writer_ != nullptr && - builtin_endpoints & BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_READER) + if (participant_stateless_message_writer_ != nullptr && + builtin_endpoints & BUILTIN_ENDPOINT_PARTICIPANT_STATELESS_MESSAGE_READER) { RemoteReaderAttributes ratt(participant_data.m_VendorId); ratt.expectsInlineQos = false; @@ -1651,6 +1670,11 @@ void SecurityManager::match_builtin_endpoints(const ParticipantProxyData& partic ratt.endpoint.reliabilityKind = BEST_EFFORT; participant_stateless_message_writer_->matched_reader_add(ratt); } +} + +void SecurityManager::match_builtin_key_exchange_endpoints(const ParticipantProxyData& participant_data) +{ + uint32_t builtin_endpoints = participant_data.m_availableBuiltinEndpoints; if(participant_volatile_message_secure_reader_ != nullptr && builtin_endpoints & BUILTIN_ENDPOINT_PARTICIPANT_VOLATILE_MESSAGE_SECURE_WRITER) @@ -1734,88 +1758,93 @@ void SecurityManager::unmatch_builtin_endpoints(const ParticipantProxyData& part } } -// TODO (Ricardo) Change participant_data -ParticipantCryptoHandle* SecurityManager::register_and_match_crypto_endpoint(const GUID_t& remote_participant_guid, - IdentityHandle& remote_participant_identity, - SharedSecretHandle& shared_secret) +void SecurityManager::exchange_participant_crypto(ParticipantCryptoHandle* remote_participant_crypto, const GUID_t& remote_participant_guid) { - if(crypto_plugin_ == nullptr) - return nullptr; - - NilHandle nil_handle; SecurityException exception; - // Register remote participant into crypto plugin. - ParticipantCryptoHandle* remote_participant_crypto = - crypto_plugin_->cryptokeyfactory()->register_matched_remote_participant(*local_participant_crypto_handle_, - remote_participant_identity, nil_handle, shared_secret, exception); - - if(remote_participant_crypto != nullptr) + // Get participant crypto tokens. + ParticipantCryptoTokenSeq local_participant_crypto_tokens; + if (crypto_plugin_->cryptkeyexchange()->create_local_participant_crypto_tokens(local_participant_crypto_tokens, + *local_participant_crypto_handle_, *remote_participant_crypto, exception)) { - // Get participant crypto tokens. - ParticipantCryptoTokenSeq local_participant_crypto_tokens; - if(crypto_plugin_->cryptkeyexchange()->create_local_participant_crypto_tokens(local_participant_crypto_tokens, - *local_participant_crypto_handle_, *remote_participant_crypto, exception)) + + ParticipantGenericMessage message = generate_participant_crypto_token_message(remote_participant_guid, + local_participant_crypto_tokens); + + CacheChange_t* change = participant_volatile_message_secure_writer_->new_change([&message]() -> uint32_t { - ParticipantGenericMessage message = generate_participant_crypto_token_message(remote_participant_guid, - local_participant_crypto_tokens); + return static_cast(ParticipantGenericMessageHelper::serialized_size(message) + + 4 /*encapsulation*/); + } + , ALIVE, c_InstanceHandle_Unknown); - CacheChange_t* change = participant_volatile_message_secure_writer_->new_change([&message]() -> uint32_t - { - return static_cast(ParticipantGenericMessageHelper::serialized_size(message) - + 4 /*encapsulation*/); - } - , ALIVE, c_InstanceHandle_Unknown); + if (change != nullptr) + { + // Serialize message + CDRMessage_t aux_msg(0); + aux_msg.wraps = true; + aux_msg.buffer = change->serializedPayload.data; + aux_msg.length = change->serializedPayload.length; + aux_msg.max_size = change->serializedPayload.max_size; - if(change != nullptr) - { - // Serialize message - CDRMessage_t aux_msg(0); - aux_msg.wraps = true; - aux_msg.buffer = change->serializedPayload.data; - aux_msg.length = change->serializedPayload.length; - aux_msg.max_size = change->serializedPayload.max_size; - - // Serialize encapsulation - CDRMessage::addOctet(&aux_msg, 0); + // Serialize encapsulation + CDRMessage::addOctet(&aux_msg, 0); #if __BIG_ENDIAN__ - aux_msg.msg_endian = BIGEND; - change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + aux_msg.msg_endian = BIGEND; + change->serializedPayload.encapsulation = PL_CDR_BE; + CDRMessage::addOctet(&aux_msg, CDR_BE); #else - aux_msg.msg_endian = LITTLEEND; - change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + aux_msg.msg_endian = LITTLEEND; + change->serializedPayload.encapsulation = PL_CDR_LE; + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif - CDRMessage::addUInt16(&aux_msg, 0); + CDRMessage::addUInt16(&aux_msg, 0); - if(CDRMessage::addParticipantGenericMessage(&aux_msg, message)) - { - change->serializedPayload.length = aux_msg.length; + if (CDRMessage::addParticipantGenericMessage(&aux_msg, message)) + { + change->serializedPayload.length = aux_msg.length; - // Send - if(!participant_volatile_message_secure_writer_history_->add_change(change)) - { - participant_volatile_message_secure_writer_history_->release_Cache(change); - logError(SECURITY, "WriterHistory cannot add the CacheChange_t"); - } - } - else + // Send + if (!participant_volatile_message_secure_writer_history_->add_change(change)) { participant_volatile_message_secure_writer_history_->release_Cache(change); - logError(SECURITY, "Cannot serialize ParticipantGenericMessage"); + logError(SECURITY, "WriterHistory cannot add the CacheChange_t"); } } else { - logError(SECURITY, "WriterHistory cannot retrieve a CacheChange_t"); + participant_volatile_message_secure_writer_history_->release_Cache(change); + logError(SECURITY, "Cannot serialize ParticipantGenericMessage"); } } else { - logError(SECURITY, "Error generating crypto token. (" << exception.what() << ")"); + logError(SECURITY, "WriterHistory cannot retrieve a CacheChange_t"); } + } + else + { + logError(SECURITY, "Error generating crypto token. (" << exception.what() << ")"); + } +} + +// TODO (Ricardo) Change participant_data +ParticipantCryptoHandle* SecurityManager::register_and_match_crypto_endpoint(IdentityHandle& remote_participant_identity, + SharedSecretHandle& shared_secret) +{ + if(crypto_plugin_ == nullptr) + return nullptr; + NilHandle nil_handle; + SecurityException exception; + + // Register remote participant into crypto plugin. + ParticipantCryptoHandle* remote_participant_crypto = + crypto_plugin_->cryptokeyfactory()->register_matched_remote_participant(*local_participant_crypto_handle_, + remote_participant_identity, nil_handle, shared_secret, exception); + + if(remote_participant_crypto != nullptr) + { return remote_participant_crypto; } else @@ -2000,6 +2029,9 @@ bool SecurityManager::register_local_writer(const GUID_t& writer_guid, const Pro if(property_value != nullptr && property_value->compare("ENCRYPT") == 0) { security_attributes.is_submessage_protected = true; + security_attributes.plugin_endpoint_attributes |= + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; } property_value = PropertyPolicyHelper::find_property(writer_properties, @@ -2008,6 +2040,10 @@ bool SecurityManager::register_local_writer(const GUID_t& writer_guid, const Pro if(property_value != nullptr && property_value->compare("ENCRYPT") == 0) { security_attributes.is_payload_protected = true; + security_attributes.is_key_protected = true; + security_attributes.plugin_endpoint_attributes |= + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED; } } @@ -2015,7 +2051,7 @@ bool SecurityManager::register_local_writer(const GUID_t& writer_guid, const Pro security_attributes.is_payload_protected)) { DatawriterCryptoHandle* writer_handle = crypto_plugin_->cryptokeyfactory()->register_local_datawriter( - *local_participant_crypto_handle_, writer_properties.properties(), exception); + *local_participant_crypto_handle_, writer_properties.properties(), security_attributes, exception); if(writer_handle != nullptr && !writer_handle->nil()) { @@ -2037,10 +2073,12 @@ bool SecurityManager::register_local_builtin_writer(const GUID_t& writer_guid, E bool returned_value = true; SecurityException exception; - if(crypto_plugin_ != nullptr && security_attributes.is_submessage_protected) + if(crypto_plugin_ != nullptr && security_attributes.is_submessage_protected && + writer_guid.entityId != participant_volatile_message_secure_writer_entity_id) { + PropertySeq auxProps; DatawriterCryptoHandle* writer_handle = crypto_plugin_->cryptokeyfactory()->register_local_datawriter( - *local_participant_crypto_handle_, PropertySeq(), exception); + *local_participant_crypto_handle_, auxProps, security_attributes, exception); if(writer_handle != nullptr && !writer_handle->nil()) { @@ -2157,6 +2195,9 @@ bool SecurityManager::register_local_reader(const GUID_t& reader_guid, const Pro if(property_value != nullptr && property_value->compare("ENCRYPT") == 0) { security_attributes.is_submessage_protected = true; + security_attributes.plugin_endpoint_attributes |= + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; } property_value = PropertyPolicyHelper::find_property(reader_properties, @@ -2165,6 +2206,10 @@ bool SecurityManager::register_local_reader(const GUID_t& reader_guid, const Pro if(property_value != nullptr && property_value->compare("ENCRYPT") == 0) { security_attributes.is_payload_protected = true; + security_attributes.is_key_protected = true; + security_attributes.plugin_endpoint_attributes |= + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_VALID | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED; } } @@ -2173,7 +2218,7 @@ bool SecurityManager::register_local_reader(const GUID_t& reader_guid, const Pro { DatareaderCryptoHandle* reader_handle = crypto_plugin_->cryptokeyfactory()->register_local_datareader( - *local_participant_crypto_handle_, reader_properties.properties(), exception); + *local_participant_crypto_handle_, reader_properties.properties(), security_attributes, exception); if(reader_handle != nullptr && !reader_handle->nil()) { @@ -2195,10 +2240,12 @@ bool SecurityManager::register_local_builtin_reader(const GUID_t& reader_guid, E bool returned_value = true; SecurityException exception; - if(crypto_plugin_ != nullptr && security_attributes.is_submessage_protected) + if(crypto_plugin_ != nullptr && security_attributes.is_submessage_protected && + reader_guid.entityId != participant_volatile_message_secure_reader_entity_id) { + PropertySeq auxProps; DatareaderCryptoHandle* reader_handle = crypto_plugin_->cryptokeyfactory()->register_local_datareader( - *local_participant_crypto_handle_, PropertySeq(), exception); + *local_participant_crypto_handle_, auxProps, security_attributes, exception); if(reader_handle != nullptr && !reader_handle->nil()) { @@ -2291,6 +2338,11 @@ bool SecurityManager::discovered_reader(const GUID_t& writer_guid, const GUID_t& ParticipantCryptoHandle* remote_participant_crypto_handle = nullptr; SharedSecretHandle* shared_secret_handle = &SharedSecretHandle::nil_handle; + if (!security_attributes.match(remote_reader_data.security_attributes_, remote_reader_data.plugin_security_attributes_)) + { + return false; + } + if(remote_participant_key == participant_->getGuid()) { remote_participant_crypto_handle = local_participant_crypto_handle_; @@ -2310,13 +2362,14 @@ bool SecurityManager::discovered_reader(const GUID_t& writer_guid, const GUID_t& // assert(access_plugin_ == nullptr || remote_permissions != nullptr); // assert(crypto_plugin_ == nullptr || remote_participant_crypto_handle != nullptr); + bool relay_only = false; bool returned_value = true; SecurityException exception; if(!is_builtin && access_plugin_ != nullptr && remote_permissions != nullptr) { if((returned_value = access_plugin_->check_remote_datareader( - *remote_permissions, domain_id_, remote_reader_data, exception)) == false) + *remote_permissions, domain_id_, remote_reader_data, relay_only, exception)) == false) { logError(SECURITY, "Error checking create remote reader " << remote_reader_data.guid() << " (" << exception.what() << ")"); } @@ -2325,6 +2378,7 @@ bool SecurityManager::discovered_reader(const GUID_t& writer_guid, const GUID_t& if(returned_value && crypto_plugin_ != nullptr && (security_attributes.is_submessage_protected || security_attributes.is_payload_protected)) { + bool is_key_exchange = (remote_reader_data.guid().entityId == participant_volatile_message_secure_reader_entity_id); auto local_writer = writer_handles_.find(writer_guid); returned_value = false; @@ -2334,166 +2388,178 @@ bool SecurityManager::discovered_reader(const GUID_t& writer_guid, const GUID_t& { DatareaderCryptoHandle* remote_reader_handle = crypto_plugin_->cryptokeyfactory()->register_matched_remote_datareader( *local_writer->second.writer_handle, *remote_participant_crypto_handle, - *shared_secret_handle, false, exception); + *shared_secret_handle, relay_only, exception); if(remote_reader_handle != nullptr && !remote_reader_handle->nil()) { - GUID_t local_reader_guid; - WriterProxyData writer_data; - - // Get local writer crypto tokens. - DatawriterCryptoTokenSeq local_writer_crypto_tokens; - if(crypto_plugin_->cryptkeyexchange()->create_local_datawriter_crypto_tokens(local_writer_crypto_tokens, - *local_writer->second.writer_handle, *remote_reader_handle, exception)) + if (is_key_exchange) { - if(remote_participant_key == participant_->getGuid()) + lock.unlock(); + logInfo(SECURITY, "Process successful discovering local reader " << remote_reader_data.guid()); + local_writer->second.associated_readers.emplace(remote_reader_data.guid(), + std::make_tuple(remote_reader_data, remote_reader_handle)); + participant_->pdpsimple()->getEDP()->pairing_remote_reader_with_local_writer_after_security( + writer_guid, remote_reader_data); + } + else + { + GUID_t local_reader_guid; + WriterProxyData writer_data; + + // Get local writer crypto tokens. + DatawriterCryptoTokenSeq local_writer_crypto_tokens; + if (crypto_plugin_->cryptkeyexchange()->create_local_datawriter_crypto_tokens(local_writer_crypto_tokens, + *local_writer->second.writer_handle, *remote_reader_handle, exception)) { - logInfo(SECURITY, "Process successful discovering local reader " << remote_reader_data.guid()); - local_writer->second.associated_readers.emplace(remote_reader_data.guid(), + if (remote_participant_key == participant_->getGuid()) + { + logInfo(SECURITY, "Process successful discovering local reader " << remote_reader_data.guid()); + local_writer->second.associated_readers.emplace(remote_reader_data.guid(), std::make_tuple(remote_reader_data, remote_reader_handle)); // Search local reader. - auto local_reader = reader_handles_.find(remote_reader_data.guid()); - - if(local_reader != reader_handles_.end()) - { - returned_value = true; - auto remote_writer = local_reader->second.associated_writers.find(writer_guid); + auto local_reader = reader_handles_.find(remote_reader_data.guid()); - if(remote_writer!= local_reader->second.associated_writers.end()) + if (local_reader != reader_handles_.end()) { - if(crypto_plugin_->cryptkeyexchange()->set_remote_datawriter_crypto_tokens( - *local_reader->second.reader_handle, - *std::get<1>(remote_writer->second), - local_writer_crypto_tokens, - exception)) + returned_value = true; + auto remote_writer = local_reader->second.associated_writers.find(writer_guid); + + if (remote_writer != local_reader->second.associated_writers.end()) { - local_reader_guid = local_reader->first; - writer_data = std::get<0>(remote_writer->second); + if (crypto_plugin_->cryptkeyexchange()->set_remote_datawriter_crypto_tokens( + *local_reader->second.reader_handle, + *std::get<1>(remote_writer->second), + local_writer_crypto_tokens, + exception)) + { + local_reader_guid = local_reader->first; + writer_data = std::get<0>(remote_writer->second); + } + else + { + logError(SECURITY, "Cannot set local reader crypto tokens (" + << remote_reader_data.guid() << ") - (" << exception.what() << ")"); + } } else { - logError(SECURITY, "Cannot set local reader crypto tokens (" - << remote_reader_data.guid() << ") - (" << exception.what() << ")"); + // Store in pendings. + remote_writer_pending_messages_.emplace(writer_guid, std::move(local_writer_crypto_tokens)); } } else { - // Store in pendings. - remote_writer_pending_messages_.emplace(writer_guid, std::move(local_writer_crypto_tokens)); + logError(SECURITY, "Cannot find local reader (" + << remote_reader_data.guid() << ") - (" << exception.what() << ")"); } } else { - logError(SECURITY, "Cannot find local reader (" - << remote_reader_data.guid() << ") - (" << exception.what() << ")"); - } - } - else - { - ParticipantGenericMessage message = generate_writer_crypto_token_message(remote_participant_key, + ParticipantGenericMessage message = generate_writer_crypto_token_message(remote_participant_key, remote_reader_data.guid(), writer_guid, local_writer_crypto_tokens); - CacheChange_t* change = participant_volatile_message_secure_writer_->new_change([&message]() -> uint32_t - { + CacheChange_t* change = participant_volatile_message_secure_writer_->new_change([&message]() -> uint32_t + { return static_cast(ParticipantGenericMessageHelper::serialized_size(message) - + 4 /*encapsulation*/); - } - , ALIVE, c_InstanceHandle_Unknown); + + 4 /*encapsulation*/); + } + , ALIVE, c_InstanceHandle_Unknown); - if(change != nullptr) - { - // Serialize message - CDRMessage_t aux_msg(0); - aux_msg.wraps = true; - aux_msg.buffer = change->serializedPayload.data; - aux_msg.length = change->serializedPayload.length; - aux_msg.max_size = change->serializedPayload.max_size; - - // Serialize encapsulation - CDRMessage::addOctet(&aux_msg, 0); + if (change != nullptr) + { + // Serialize message + CDRMessage_t aux_msg(0); + aux_msg.wraps = true; + aux_msg.buffer = change->serializedPayload.data; + aux_msg.length = change->serializedPayload.length; + aux_msg.max_size = change->serializedPayload.max_size; + + // Serialize encapsulation + CDRMessage::addOctet(&aux_msg, 0); #if __BIG_ENDIAN__ - aux_msg.msg_endian = BIGEND; - change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + aux_msg.msg_endian = BIGEND; + change->serializedPayload.encapsulation = PL_CDR_BE; + CDRMessage::addOctet(&aux_msg, CDR_BE); #else - aux_msg.msg_endian = LITTLEEND; - change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + aux_msg.msg_endian = LITTLEEND; + change->serializedPayload.encapsulation = PL_CDR_LE; + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif - CDRMessage::addUInt16(&aux_msg, 0); + CDRMessage::addUInt16(&aux_msg, 0); - if(CDRMessage::addParticipantGenericMessage(&aux_msg, message)) - { - change->serializedPayload.length = aux_msg.length; - - // Send - if(participant_volatile_message_secure_writer_history_->add_change(change)) + if (CDRMessage::addParticipantGenericMessage(&aux_msg, message)) { - logInfo(SECURITY, "Process successful discovering remote reader " << remote_reader_data.guid()); - local_writer->second.associated_readers.emplace(remote_reader_data.guid(), + change->serializedPayload.length = aux_msg.length; + + // Send + if (participant_volatile_message_secure_writer_history_->add_change(change)) + { + logInfo(SECURITY, "Process successful discovering remote reader " << remote_reader_data.guid()); + local_writer->second.associated_readers.emplace(remote_reader_data.guid(), std::make_tuple(remote_reader_data, remote_reader_handle)); - returned_value = true; + returned_value = true; + } + else + { + participant_volatile_message_secure_writer_history_->release_Cache(change); + logError(SECURITY, "WriterHistory cannot add the CacheChange_t"); + } } else { participant_volatile_message_secure_writer_history_->release_Cache(change); - logError(SECURITY, "WriterHistory cannot add the CacheChange_t"); + logError(SECURITY, "Cannot serialize ParticipantGenericMessage"); } } else { - participant_volatile_message_secure_writer_history_->release_Cache(change); - logError(SECURITY, "Cannot serialize ParticipantGenericMessage"); + logError(SECURITY, "WriterHistory cannot retrieve a CacheChange_t"); } } - else - { - logError(SECURITY, "WriterHistory cannot retrieve a CacheChange_t"); - } } - } - else - { - logError(SECURITY, "Error generating crypto token. (" << exception.what() << ")"); - } - - // Check pending reader crypto messages. - auto pending = remote_reader_pending_messages_.find(remote_reader_data.guid()); - bool pairing_cause_pending_message = false; - - if(pending != remote_reader_pending_messages_.end()) - { - if(crypto_plugin_->cryptkeyexchange()->set_remote_datareader_crypto_tokens( - *local_writer->second.writer_handle, - *remote_reader_handle, - pending->second, - exception)) + else { - pairing_cause_pending_message = true; + logError(SECURITY, "Error generating crypto token. (" << exception.what() << ")"); } - else + + // Check pending reader crypto messages. + auto pending = remote_reader_pending_messages_.find(remote_reader_data.guid()); + bool pairing_cause_pending_message = false; + + if (pending != remote_reader_pending_messages_.end()) { - logError(SECURITY, "Cannot set remote reader crypto tokens (" + if (crypto_plugin_->cryptkeyexchange()->set_remote_datareader_crypto_tokens( + *local_writer->second.writer_handle, + *remote_reader_handle, + pending->second, + exception)) + { + pairing_cause_pending_message = true; + } + else + { + logError(SECURITY, "Cannot set remote reader crypto tokens (" << remote_reader_data.guid() << ") - (" << exception.what() << ")"); - } + } - remote_reader_pending_messages_.erase(pending); - } - lock.unlock(); + remote_reader_pending_messages_.erase(pending); + } + lock.unlock(); - // If reader was found and setting of crypto tokens works, then tell core to match reader and writer. - if(local_reader_guid != GUID_t::unknown()) - { - participant_->pdpsimple()->getEDP()->pairing_remote_writer_with_local_reader_after_security( + // If reader was found and setting of crypto tokens works, then tell core to match reader and writer. + if (local_reader_guid != GUID_t::unknown()) + { + participant_->pdpsimple()->getEDP()->pairing_remote_writer_with_local_reader_after_security( local_reader_guid, writer_data); - } + } - // If writer was found and setting of crypto tokens works, then tell core to match writer and reader. - if(pairing_cause_pending_message) - { - participant_->pdpsimple()->getEDP()->pairing_remote_reader_with_local_writer_after_security( + // If writer was found and setting of crypto tokens works, then tell core to match writer and reader. + if (pairing_cause_pending_message) + { + participant_->pdpsimple()->getEDP()->pairing_remote_reader_with_local_writer_after_security( writer_guid, remote_reader_data); + } } } else @@ -2574,6 +2640,11 @@ bool SecurityManager::discovered_writer(const GUID_t& reader_guid, const GUID_t& ParticipantCryptoHandle* remote_participant_crypto_handle = nullptr; SharedSecretHandle* shared_secret_handle = &SharedSecretHandle::nil_handle; + if (!security_attributes.match(remote_writer_data.security_attributes_, remote_writer_data.plugin_security_attributes_)) + { + return false; + } + if(remote_participant_key == participant_->getGuid()) { remote_participant_crypto_handle = local_participant_crypto_handle_; @@ -2608,6 +2679,7 @@ bool SecurityManager::discovered_writer(const GUID_t& reader_guid, const GUID_t& if(returned_value && crypto_plugin_ != nullptr && (security_attributes.is_submessage_protected || security_attributes.is_payload_protected)) { + bool is_key_exchange = (remote_writer_data.guid().entityId == participant_volatile_message_secure_writer_entity_id); auto local_reader = reader_handles_.find(reader_guid); returned_value = false; @@ -2621,163 +2693,175 @@ bool SecurityManager::discovered_writer(const GUID_t& reader_guid, const GUID_t& if(remote_writer_handle != nullptr && !remote_writer_handle->nil()) { - GUID_t local_writer_guid; - ReaderProxyData reader_data; - - // Get local reader crypto tokens. - DatareaderCryptoTokenSeq local_reader_crypto_tokens; - if(crypto_plugin_->cryptkeyexchange()->create_local_datareader_crypto_tokens(local_reader_crypto_tokens, - *local_reader->second.reader_handle, *remote_writer_handle, exception)) + if (is_key_exchange) + { + lock.unlock(); + logInfo(SECURITY, "Process successful discovering local writer " << remote_writer_data.guid()); + local_reader->second.associated_writers.emplace(remote_writer_data.guid(), + std::make_tuple(remote_writer_data, remote_writer_handle)); + participant_->pdpsimple()->getEDP()->pairing_remote_writer_with_local_reader_after_security( + reader_guid, remote_writer_data); + } + else { - if(remote_participant_key == participant_->getGuid()) + GUID_t local_writer_guid; + ReaderProxyData reader_data; + + // Get local reader crypto tokens. + DatareaderCryptoTokenSeq local_reader_crypto_tokens; + if (crypto_plugin_->cryptkeyexchange()->create_local_datareader_crypto_tokens(local_reader_crypto_tokens, + *local_reader->second.reader_handle, *remote_writer_handle, exception)) { - logInfo(SECURITY, "Process successful discovering local writer " << remote_writer_data.guid()); - local_reader->second.associated_writers.emplace(remote_writer_data.guid(), + if (remote_participant_key == participant_->getGuid()) + { + logInfo(SECURITY, "Process successful discovering local writer " << remote_writer_data.guid()); + local_reader->second.associated_writers.emplace(remote_writer_data.guid(), std::make_tuple(remote_writer_data, remote_writer_handle)); // Search local writer. - auto local_writer = writer_handles_.find(remote_writer_data.guid()); - - if(local_writer != writer_handles_.end()) - { - returned_value = true; - auto remote_reader = local_writer->second.associated_readers.find(reader_guid); + auto local_writer = writer_handles_.find(remote_writer_data.guid()); - if(remote_reader != local_writer->second.associated_readers.end()) + if (local_writer != writer_handles_.end()) { - if(crypto_plugin_->cryptkeyexchange()->set_remote_datareader_crypto_tokens( - *local_writer->second.writer_handle, - *std::get<1>(remote_reader->second), - local_reader_crypto_tokens, - exception)) + returned_value = true; + auto remote_reader = local_writer->second.associated_readers.find(reader_guid); + + if (remote_reader != local_writer->second.associated_readers.end()) { - local_writer_guid = local_writer->first; - reader_data = std::get<0>(remote_reader->second); + if (crypto_plugin_->cryptkeyexchange()->set_remote_datareader_crypto_tokens( + *local_writer->second.writer_handle, + *std::get<1>(remote_reader->second), + local_reader_crypto_tokens, + exception)) + { + local_writer_guid = local_writer->first; + reader_data = std::get<0>(remote_reader->second); + } + else + { + logError(SECURITY, "Cannot set local writer crypto tokens (" + << remote_writer_data.guid() << ") - (" << exception.what() << ")"); + } } else { - logError(SECURITY, "Cannot set local writer crypto tokens (" - << remote_writer_data.guid() << ") - (" << exception.what() << ")"); + // Store in pendings. + remote_reader_pending_messages_.emplace(reader_guid, std::move(local_reader_crypto_tokens)); } } else { - // Store in pendings. - remote_reader_pending_messages_.emplace(reader_guid, std::move(local_reader_crypto_tokens)); + logError(SECURITY, "Cannot find local writer (" + << remote_writer_data.guid() << ") - (" << exception.what() << ")"); } } else { - logError(SECURITY, "Cannot find local writer (" - << remote_writer_data.guid() << ") - (" << exception.what() << ")"); - } - } - else - { - ParticipantGenericMessage message = generate_reader_crypto_token_message(remote_participant_key, + ParticipantGenericMessage message = generate_reader_crypto_token_message(remote_participant_key, remote_writer_data.guid(), reader_guid, local_reader_crypto_tokens); - CacheChange_t* change = participant_volatile_message_secure_writer_->new_change([&message]() -> uint32_t - { + CacheChange_t* change = participant_volatile_message_secure_writer_->new_change([&message]() -> uint32_t + { return static_cast(ParticipantGenericMessageHelper::serialized_size(message) - + 4 /*encapsulation*/); - } - , ALIVE, c_InstanceHandle_Unknown); + + 4 /*encapsulation*/); + } + , ALIVE, c_InstanceHandle_Unknown); - if(change != nullptr) - { - // Serialize message - CDRMessage_t aux_msg(0); - aux_msg.wraps = true; - aux_msg.buffer = change->serializedPayload.data; - aux_msg.length = change->serializedPayload.length; - aux_msg.max_size = change->serializedPayload.max_size; - - // Serialize encapsulation - CDRMessage::addOctet(&aux_msg, 0); + if (change != nullptr) + { + // Serialize message + CDRMessage_t aux_msg(0); + aux_msg.wraps = true; + aux_msg.buffer = change->serializedPayload.data; + aux_msg.length = change->serializedPayload.length; + aux_msg.max_size = change->serializedPayload.max_size; + + // Serialize encapsulation + CDRMessage::addOctet(&aux_msg, 0); #if __BIG_ENDIAN__ - aux_msg.msg_endian = BIGEND; - change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + aux_msg.msg_endian = BIGEND; + change->serializedPayload.encapsulation = PL_CDR_BE; + CDRMessage::addOctet(&aux_msg, CDR_BE); #else - aux_msg.msg_endian = LITTLEEND; - change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + aux_msg.msg_endian = LITTLEEND; + change->serializedPayload.encapsulation = PL_CDR_LE; + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif - CDRMessage::addUInt16(&aux_msg, 0); + CDRMessage::addUInt16(&aux_msg, 0); - if(CDRMessage::addParticipantGenericMessage(&aux_msg, message)) - { - change->serializedPayload.length = aux_msg.length; - - // Send - if(participant_volatile_message_secure_writer_history_->add_change(change)) + if (CDRMessage::addParticipantGenericMessage(&aux_msg, message)) { - logInfo(SECURITY, "Process successful discovering remote writer " << remote_writer_data.guid()); - local_reader->second.associated_writers.emplace(remote_writer_data.guid(), + change->serializedPayload.length = aux_msg.length; + + // Send + if (participant_volatile_message_secure_writer_history_->add_change(change)) + { + logInfo(SECURITY, "Process successful discovering remote writer " << remote_writer_data.guid()); + local_reader->second.associated_writers.emplace(remote_writer_data.guid(), std::make_tuple(remote_writer_data, remote_writer_handle)); - returned_value = true; + returned_value = true; + } + else + { + participant_volatile_message_secure_writer_history_->release_Cache(change); + logError(SECURITY, "WriterHistory cannot add the CacheChange_t"); + } } else { participant_volatile_message_secure_writer_history_->release_Cache(change); - logError(SECURITY, "WriterHistory cannot add the CacheChange_t"); + logError(SECURITY, "Cannot serialize ParticipantGenericMessage"); } } else { - participant_volatile_message_secure_writer_history_->release_Cache(change); - logError(SECURITY, "Cannot serialize ParticipantGenericMessage"); + logError(SECURITY, "WriterHistory cannot retrieve a CacheChange_t"); } - } - else - { - logError(SECURITY, "WriterHistory cannot retrieve a CacheChange_t"); - } + } } - } - else - { - logError(SECURITY, "Error generating crypto token. (" << exception.what() << ")"); - } - - // Check pending writer crypto messages. - auto pending = remote_writer_pending_messages_.find(remote_writer_data.guid()); - bool pairing_cause_pending_message = false; - - if(pending != remote_writer_pending_messages_.end()) - { - if(crypto_plugin_->cryptkeyexchange()->set_remote_datawriter_crypto_tokens( - *local_reader->second.reader_handle, - *remote_writer_handle, - pending->second, - exception)) + else { - pairing_cause_pending_message = true; + logError(SECURITY, "Error generating crypto token. (" << exception.what() << ")"); } - else + + // Check pending writer crypto messages. + auto pending = remote_writer_pending_messages_.find(remote_writer_data.guid()); + bool pairing_cause_pending_message = false; + + if (pending != remote_writer_pending_messages_.end()) { - logError(SECURITY, "Cannot set remote writer crypto tokens (" + if (crypto_plugin_->cryptkeyexchange()->set_remote_datawriter_crypto_tokens( + *local_reader->second.reader_handle, + *remote_writer_handle, + pending->second, + exception)) + { + pairing_cause_pending_message = true; + } + else + { + logError(SECURITY, "Cannot set remote writer crypto tokens (" << remote_writer_data.guid() << ") - (" << exception.what() << ")"); - } + } - remote_writer_pending_messages_.erase(pending); - } - lock.unlock(); + remote_writer_pending_messages_.erase(pending); + } + lock.unlock(); - // If writer was found and setting of crypto tokens works, then tell core to match writer and reader. - if(local_writer_guid != GUID_t::unknown()) - { - participant_->pdpsimple()->getEDP()->pairing_remote_reader_with_local_writer_after_security( + // If writer was found and setting of crypto tokens works, then tell core to match writer and reader. + if (local_writer_guid != GUID_t::unknown()) + { + participant_->pdpsimple()->getEDP()->pairing_remote_reader_with_local_writer_after_security( local_writer_guid, reader_data); - } + } - // If reader was found and setting of crypto tokens works, then tell core to match reader and writer. - if(pairing_cause_pending_message) - { - participant_->pdpsimple()->getEDP()->pairing_remote_writer_with_local_reader_after_security( + // If reader was found and setting of crypto tokens works, then tell core to match reader and writer. + if (pairing_cause_pending_message) + { + participant_->pdpsimple()->getEDP()->pairing_remote_writer_with_local_reader_after_security( reader_guid, remote_writer_data); + } } } else @@ -2816,6 +2900,36 @@ bool SecurityManager::encode_writer_submessage(const CDRMessage_t& input_message if(crypto_plugin_ == nullptr) return false; + if (writer_guid.entityId == participant_volatile_message_secure_writer_entity_id) + { + bool ret_val = false; + if (receiving_list.size() == 1) + { + bool acquired = mutex_.try_lock(); + GUID_t participant_guid(receiving_list.at(0).guidPrefix, c_EntityId_RTPSParticipant); + auto part = discovered_participants_.find(participant_guid); + if (part != discovered_participants_.end()) + { + auto pCrypto = part->second.get_participant_crypto(); + EndpointSecurityAttributes attr; + SecurityException exception; + PropertySeq auxProps; + auxProps.emplace_back(Property("dds.sec.builtin_endpoint_name", "BuiltinParticipantVolatileMessageSecureWriter")); + auto wHandle = crypto_plugin_->cryptokeyfactory()->register_local_datawriter(*pCrypto, auxProps, attr, exception); + std::vector receiving_crypto_list; + if (crypto_plugin_->cryptotransform()->encode_datawriter_submessage(output_message, + input_message, *wHandle, receiving_crypto_list, exception)) + { + ret_val = true; + } + } + + if (acquired) mutex_.unlock(); + } + + return ret_val; + } + std::unique_lock lock(mutex_); const auto& wr_it = writer_handles_.find(writer_guid); @@ -2864,6 +2978,36 @@ bool SecurityManager::encode_reader_submessage(const CDRMessage_t& input_message if(crypto_plugin_ == nullptr) return false; + if (reader_guid.entityId == participant_volatile_message_secure_reader_entity_id) + { + bool ret_val = false; + + if (receiving_list.size() == 1) + { + bool acquired = mutex_.try_lock(); + GUID_t participant_guid(receiving_list.at(0).guidPrefix, c_EntityId_RTPSParticipant); + auto part = discovered_participants_.find(participant_guid); + if (part != discovered_participants_.end()) + { + auto pCrypto = part->second.get_participant_crypto(); + EndpointSecurityAttributes attr; + SecurityException exception; + PropertySeq auxProps; + auxProps.emplace_back(Property("dds.sec.builtin_endpoint_name", "BuiltinParticipantVolatileMessageSecureReader")); + auto rHandle = crypto_plugin_->cryptokeyfactory()->register_local_datareader(*pCrypto, auxProps, attr, exception); + std::vector receiving_crypto_list; + if (crypto_plugin_->cryptotransform()->encode_datareader_submessage(output_message, + input_message, *rHandle, receiving_crypto_list, exception)) + { + ret_val = true; + } + } + if (acquired) mutex_.unlock(); + } + + return ret_val; + } + std::unique_lock lock(mutex_); const auto& rd_it = reader_handles_.find(reader_guid); @@ -3133,8 +3277,8 @@ bool SecurityManager::participant_authorized(const ParticipantProxyData& partici } // Starts cryptography mechanism - ParticipantCryptoHandle* participant_crypto_handle = register_and_match_crypto_endpoint(participant_data.m_guid, - *remote_participant_info->identity_handle_, + ParticipantCryptoHandle* participant_crypto_handle = + register_and_match_crypto_endpoint(*remote_participant_info->identity_handle_, *shared_secret_handle); // Store cryptography info @@ -3207,6 +3351,9 @@ bool SecurityManager::participant_authorized(const ParticipantProxyData& partici << participant_data.m_guid << ")"); return false; } + + match_builtin_key_exchange_endpoints(participant_data); + exchange_participant_crypto(participant_crypto_handle, participant_data.m_guid); } else { @@ -3220,6 +3367,8 @@ bool SecurityManager::participant_authorized(const ParticipantProxyData& partici dp_it->second.set_shared_secret(shared_secret_handle); dp_it->second.set_permissions_handle(remote_permissions); } + + match_builtin_key_exchange_endpoints(participant_data); } participant_->pdpsimple()->notifyAboveRemoteEndpoints(participant_data); diff --git a/src/cpp/rtps/security/SecurityManager.h b/src/cpp/rtps/security/SecurityManager.h index 99f99cba68d..b76ce0b088c 100644 --- a/src/cpp/rtps/security/SecurityManager.h +++ b/src/cpp/rtps/security/SecurityManager.h @@ -354,11 +354,15 @@ class SecurityManager void match_builtin_endpoints(const ParticipantProxyData& participant_data); + void match_builtin_key_exchange_endpoints(const ParticipantProxyData& participant_data); + void unmatch_builtin_endpoints(const ParticipantProxyData& participant_data); - ParticipantCryptoHandle* register_and_match_crypto_endpoint(const GUID_t& remote_participant_guid, IdentityHandle& remote_participant_identity, + ParticipantCryptoHandle* register_and_match_crypto_endpoint(IdentityHandle& remote_participant_identity, SharedSecretHandle& shared_secret); + void exchange_participant_crypto(ParticipantCryptoHandle* remote_participant_crypto, const GUID_t& remote_participant_guid); + void process_participant_stateless_message(const CacheChange_t* const change); void process_participant_volatile_message_secure(const CacheChange_t* const change); diff --git a/src/cpp/security/accesscontrol/CommonParser.cpp b/src/cpp/security/accesscontrol/CommonParser.cpp index 0fa4d1909b6..0baa4e07d5b 100644 --- a/src/cpp/security/accesscontrol/CommonParser.cpp +++ b/src/cpp/security/accesscontrol/CommonParser.cpp @@ -74,43 +74,53 @@ bool eprosima::fastrtps::rtps::security::parse_domain_id_set(tinyxml2::XMLElemen { if(tinyxml2::XMLError::XML_SUCCESS != subnode->QueryUnsignedText(&min_domain_id)) { - logError(XMLPARSER, "Invalid value of " << DomainId_str << + logError(XMLPARSER, "Invalid min value of " << DomainId_str << " tag. Line " << PRINTLINE(subnode)); returned_value = false; } - } - else - { - logError(XMLPARSER, "Expected " << Min_str << " tag. Line " << - PRINTLINE(subnode)); - returned_value = false; - } - - if(returned_value && (subnode = subnode->NextSiblingElement()) != nullptr) - { - // "Max" parameter is optional - if(strcmp(subnode->Name(), Max_str) == 0) + else { uint32_t max_domain_id = 0; - if(tinyxml2::XMLError::XML_SUCCESS == subnode->QueryUnsignedText(&max_domain_id)) + + // "Max" parameter is optional + if ((subnode = subnode->NextSiblingElement()) != nullptr) { - domains.ranges.push_back(std::make_pair(min_domain_id, max_domain_id)); + if (strcmp(subnode->Name(), Max_str) == 0) + { + if (tinyxml2::XMLError::XML_SUCCESS != subnode->QueryUnsignedText(&max_domain_id)) + { + logError(XMLPARSER, "Invalid max value of " << DomainId_str << + " tag. Line " << PRINTLINE(subnode)); + returned_value = false; + } + } } - else + + if(returned_value) { - logError(XMLPARSER, "Invalid max value of " << DomainId_str << - " tag. Line " << PRINTLINE(subnode)); - returned_value = false; + domains.ranges.push_back(std::make_pair(min_domain_id, max_domain_id)); } } + } + else if (strcmp(subnode->Name(), Max_str) == 0) + { + uint32_t max_domain_id = 0; + if (tinyxml2::XMLError::XML_SUCCESS == subnode->QueryUnsignedText(&max_domain_id)) + { + domains.ranges.push_back(std::make_pair(min_domain_id, max_domain_id)); + } else { - domains.ranges.push_back(std::make_pair(min_domain_id, 0)); + logError(XMLPARSER, "Invalid max value of " << DomainId_str << + " tag. Line " << PRINTLINE(subnode)); + returned_value = false; } } else { - domains.ranges.push_back(std::make_pair(min_domain_id, 0)); + logError(XMLPARSER, "Expected " << Min_str << " or " << Max_str << " tag. Line " << + PRINTLINE(subnode)); + returned_value = false; } } else diff --git a/src/cpp/security/accesscontrol/GovernanceParser.cpp b/src/cpp/security/accesscontrol/GovernanceParser.cpp index bea2c14a742..d0000614dc0 100644 --- a/src/cpp/security/accesscontrol/GovernanceParser.cpp +++ b/src/cpp/security/accesscontrol/GovernanceParser.cpp @@ -48,6 +48,8 @@ static const char* DataProtectionKind_str = "data_protection_kind"; static const char* ProtectionKindNone_str = "NONE"; static const char* ProtectionKindSign_str = "SIGN"; static const char* ProtectionKindEncrypt_str = "ENCRYPT"; +static const char* ProtectionKindSignAuth_str = "SIGN_WITH_ORIGIN_AUTHENTICATION"; +static const char* ProtectionKindEncryptAuth_str = "ENCRYPT_WITH_ORIGIN_AUTHENTICATION"; using namespace eprosima::fastrtps::rtps::security; @@ -268,6 +270,14 @@ bool GovernanceParser::parse_domain_rule(tinyxml2::XMLElement* root, DomainRule& { rule.discovery_protection_kind = ProtectionKind::ENCRYPT; } + else if(strcmp(text, ProtectionKindSignAuth_str) == 0) + { + rule.discovery_protection_kind = ProtectionKind::SIGN_WITH_ORIGIN_AUTHENTICATION; + } + else if(strcmp(text, ProtectionKindEncryptAuth_str) == 0) + { + rule.discovery_protection_kind = ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION; + } else { logError(XMLPARSER, "Invalid text in " << DiscoveryProtectionKind_str << " tag. Line " << PRINTLINE(node)); @@ -305,15 +315,23 @@ bool GovernanceParser::parse_domain_rule(tinyxml2::XMLElement* root, DomainRule& { if(strcmp(text, ProtectionKindNone_str) == 0) { - rule.LivelinessProtectionKind_str = ProtectionKind::NONE; + rule.liveliness_protection_kind = ProtectionKind::NONE; } else if(strcmp(text, ProtectionKindSign_str) == 0) { - rule.LivelinessProtectionKind_str = ProtectionKind::SIGN; + rule.liveliness_protection_kind = ProtectionKind::SIGN; } else if(strcmp(text, ProtectionKindEncrypt_str) == 0) { - rule.LivelinessProtectionKind_str = ProtectionKind::ENCRYPT; + rule.liveliness_protection_kind = ProtectionKind::ENCRYPT; + } + else if(strcmp(text, ProtectionKindSignAuth_str) == 0) + { + rule.liveliness_protection_kind = ProtectionKind::SIGN_WITH_ORIGIN_AUTHENTICATION; + } + else if(strcmp(text, ProtectionKindEncryptAuth_str) == 0) + { + rule.liveliness_protection_kind = ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION; } else { @@ -362,6 +380,14 @@ bool GovernanceParser::parse_domain_rule(tinyxml2::XMLElement* root, DomainRule& { rule.rtps_protection_kind = ProtectionKind::ENCRYPT; } + else if(strcmp(text, ProtectionKindSignAuth_str) == 0) + { + rule.rtps_protection_kind = ProtectionKind::SIGN_WITH_ORIGIN_AUTHENTICATION; + } + else if(strcmp(text, ProtectionKindEncryptAuth_str) == 0) + { + rule.rtps_protection_kind = ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION; + } else { logError(XMLPARSER, "Invalid text in " << RtpsProtectionKind_str << " tag. Line " << PRINTLINE(node)); @@ -609,6 +635,14 @@ bool GovernanceParser::parse_topic_rule(tinyxml2::XMLElement* root, TopicRule& r { rule.metadata_protection_kind = ProtectionKind::ENCRYPT; } + else if (strcmp(text, ProtectionKindSignAuth_str) == 0) + { + rule.metadata_protection_kind = ProtectionKind::SIGN_WITH_ORIGIN_AUTHENTICATION; + } + else if (strcmp(text, ProtectionKindEncryptAuth_str) == 0) + { + rule.metadata_protection_kind = ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION; + } else { logError(XMLPARSER, "Invalid text in " << MetadataProtectionKind_str << " tag. Line " << PRINTLINE(node)); diff --git a/src/cpp/security/accesscontrol/GovernanceParser.h b/src/cpp/security/accesscontrol/GovernanceParser.h index d379b2e5ea5..f2fed809375 100644 --- a/src/cpp/security/accesscontrol/GovernanceParser.h +++ b/src/cpp/security/accesscontrol/GovernanceParser.h @@ -28,7 +28,9 @@ enum class ProtectionKind { NONE, SIGN, - ENCRYPT + ENCRYPT, + SIGN_WITH_ORIGIN_AUTHENTICATION, + ENCRYPT_WITH_ORIGIN_AUTHENTICATION }; struct TopicRule @@ -48,7 +50,7 @@ struct DomainRule bool allow_unauthenticated_participants; bool enable_join_access_control; ProtectionKind discovery_protection_kind; - ProtectionKind LivelinessProtectionKind_str; + ProtectionKind liveliness_protection_kind; ProtectionKind rtps_protection_kind; std::vector topic_rules; }; diff --git a/src/cpp/security/accesscontrol/Permissions.cpp b/src/cpp/security/accesscontrol/Permissions.cpp index 2a104140021..34b2694923c 100644 --- a/src/cpp/security/accesscontrol/Permissions.cpp +++ b/src/cpp/security/accesscontrol/Permissions.cpp @@ -187,6 +187,16 @@ static bool get_signature_algorithm(X509* certificate, std::string& signature_al signature_algorithm = ECDSA_SHA256; returnedValue = true; } + else if (strncmp(ptr->data, "sha256WithRSAEncryption", ptr->length) == 0) + { + signature_algorithm = RSA_SHA256; + returnedValue = true; + } + else if (strncmp(ptr->data, "sha1WithRSAEncryption", ptr->length) == 0) + { + signature_algorithm = RSA_SHA256; + returnedValue = true; + } } else exception = _SecurityException_("OpenSSL library cannot retrieve mem ptr"); @@ -550,6 +560,14 @@ static bool verify_permissions_file(const AccessPermissionsHandle& local_handle, return returned_value; } +static void process_protection_kind(const ProtectionKind kind, bool& protected_flag, bool& encrypted_flag, bool& orig_auth_flag) +{ + protected_flag = kind != ProtectionKind::NONE; + encrypted_flag = (kind == ProtectionKind::ENCRYPT) || (kind == ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION); + orig_auth_flag = (kind == ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION) || + (kind == ProtectionKind::SIGN_WITH_ORIGIN_AUTHENTICATION); +} + static bool check_subject_name(const IdentityHandle& ih, AccessPermissionsHandle& ah, const uint32_t domain_id, DomainAccessRules& governance, PermissionsData& permissions, SecurityException& exception) { @@ -595,57 +613,64 @@ static bool check_subject_name(const IdentityHandle& ih, AccessPermissionsHandle { ah->governance_rule_.is_access_protected = rule.enable_join_access_control; - if(rule.discovery_protection_kind == ProtectionKind::NONE) - { - ah->governance_rule_.is_discovered_protected = false; - } - else - { - ah->governance_rule_.is_discovered_protected = true; - } + PluginParticipantSecurityAttributes plug_part_attr; - if(rule.rtps_protection_kind == ProtectionKind::NONE) - { - ah->governance_rule_.is_rtps_protected = false; - } - else - { - ah->governance_rule_.is_rtps_protected = true; - } + process_protection_kind(rule.discovery_protection_kind, + ah->governance_rule_.is_discovery_protected, + plug_part_attr.is_discovery_encrypted, + plug_part_attr.is_discovery_origin_authenticated); + + process_protection_kind(rule.rtps_protection_kind, + ah->governance_rule_.is_rtps_protected, + plug_part_attr.is_rtps_encrypted, + plug_part_attr.is_rtps_origin_authenticated); + + process_protection_kind(rule.liveliness_protection_kind, + ah->governance_rule_.is_liveliness_protected, + plug_part_attr.is_liveliness_encrypted, + plug_part_attr.is_liveliness_origin_authenticated); + + ah->governance_rule_.plugin_participant_attributes = plug_part_attr.mask(); for(auto topic_rule : rule.topic_rules) { std::string topic_expression = topic_rule.topic_expression; EndpointSecurityAttributes reader_attributes; EndpointSecurityAttributes writer_attributes; - - reader_attributes.is_discovered_protected = topic_rule.enable_discovery_protection; - writer_attributes.is_discovered_protected = topic_rule.enable_discovery_protection; - reader_attributes.is_access_protected = topic_rule.enable_read_access_control; - writer_attributes.is_access_protected = topic_rule.enable_write_access_control; - - if(topic_rule.metadata_protection_kind == ProtectionKind::NONE) - { - reader_attributes.is_submessage_protected = false; - writer_attributes.is_submessage_protected = false; - } - else - { - reader_attributes.is_submessage_protected = true; - writer_attributes.is_submessage_protected = true; - } - - if(topic_rule.data_protection_kind == ProtectionKind::NONE) - { - reader_attributes.is_payload_protected = false; - writer_attributes.is_payload_protected = false; - } - else - { - reader_attributes.is_payload_protected = true; - writer_attributes.is_payload_protected = true; - } - + PluginEndpointSecurityAttributes plugin_attributes; + + reader_attributes.is_discovery_protected = topic_rule.enable_discovery_protection; + writer_attributes.is_discovery_protected = topic_rule.enable_discovery_protection; + reader_attributes.is_liveliness_protected = topic_rule.enable_liveliness_protection; + writer_attributes.is_liveliness_protected = topic_rule.enable_liveliness_protection; + reader_attributes.is_read_protected = topic_rule.enable_read_access_control; + reader_attributes.is_write_protected = topic_rule.enable_write_access_control; + writer_attributes.is_read_protected = topic_rule.enable_read_access_control; + writer_attributes.is_write_protected = topic_rule.enable_write_access_control; + + bool hasEncryption = + (topic_rule.metadata_protection_kind == ProtectionKind::ENCRYPT) || + (topic_rule.metadata_protection_kind == ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION); + bool hasOriginAuth = + (topic_rule.metadata_protection_kind == ProtectionKind::ENCRYPT_WITH_ORIGIN_AUTHENTICATION) || + (topic_rule.metadata_protection_kind == ProtectionKind::SIGN_WITH_ORIGIN_AUTHENTICATION); + plugin_attributes.is_submessage_encrypted = hasEncryption; + plugin_attributes.is_submessage_origin_authenticated = hasOriginAuth; + + reader_attributes.is_submessage_protected = + writer_attributes.is_submessage_protected = + (topic_rule.metadata_protection_kind != ProtectionKind::NONE); + + plugin_attributes.is_payload_encrypted = + reader_attributes.is_key_protected = + writer_attributes.is_key_protected = + (topic_rule.data_protection_kind == ProtectionKind::ENCRYPT); + reader_attributes.is_payload_protected = + writer_attributes.is_payload_protected = + (topic_rule.data_protection_kind != ProtectionKind::NONE); + + reader_attributes.plugin_endpoint_attributes = plugin_attributes.mask(); + writer_attributes.plugin_endpoint_attributes = plugin_attributes.mask(); ah->governance_reader_topic_rules_.insert(std::pair( topic_expression, std::move(reader_attributes))); @@ -921,7 +946,8 @@ PermissionsHandle* Permissions::validate_remote_permissions(Authentication&, { if(is_validation_in_time(grant.validity)) { - if(rfc2253_string_compare(grant.subject_name, rih->cert_sn_rfc2253_)) + if(rfc2253_string_compare(grant.subject_name, rih->cert_sn_rfc2253_) || + strcmp(grant.subject_name.c_str(), rih->cert_sn_.c_str()) == 0) { remote_grant = std::move(grant); break; @@ -1029,7 +1055,7 @@ bool Permissions::check_create_datawriter(const PermissionsHandle& local_handle, if((attributes = is_topic_in_sec_attributes(topic_name, lah->governance_writer_topic_rules_)) != nullptr) { - if(!attributes->is_access_protected) + if(!attributes->is_write_protected) { return true; } @@ -1105,7 +1131,7 @@ bool Permissions::check_create_datareader(const PermissionsHandle& local_handle, if((attributes = is_topic_in_sec_attributes(topic_name, lah->governance_reader_topic_rules_)) != nullptr) { - if(!attributes->is_access_protected) + if(!attributes->is_read_protected) { return true; } @@ -1181,7 +1207,7 @@ bool Permissions::check_remote_datawriter(const PermissionsHandle& remote_handle if((attributes = is_topic_in_sec_attributes(publication_data.topicName(),rah->governance_writer_topic_rules_)) != nullptr) { - if(!attributes->is_access_protected) + if(!attributes->is_write_protected) { return true; } @@ -1224,11 +1250,13 @@ bool Permissions::check_remote_datawriter(const PermissionsHandle& remote_handle bool Permissions::check_remote_datareader(const PermissionsHandle& remote_handle, const uint32_t domain_id, const ReaderProxyData& subscription_data, - SecurityException& exception) + bool& relay_only, SecurityException& exception) { bool returned_value = false; const AccessPermissionsHandle& rah = AccessPermissionsHandle::narrow(remote_handle); + relay_only = false; + if(rah.nil()) { exception = _SecurityException_("Bad precondition"); @@ -1240,7 +1268,7 @@ bool Permissions::check_remote_datareader(const PermissionsHandle& remote_handle if((attributes = is_topic_in_sec_attributes(subscription_data.topicName(),rah->governance_reader_topic_rules_)) != nullptr) { - if(!attributes->is_access_protected) + if(!attributes->is_read_protected) { return true; } @@ -1269,6 +1297,17 @@ bool Permissions::check_remote_datareader(const PermissionsHandle& remote_handle break; } + + if (is_topic_in_criterias(subscription_data.topicName(), rule.relays)) + { + if (rule.allow) + { + relay_only = true; + returned_value = true; + } + + break; + } } } diff --git a/src/cpp/security/accesscontrol/Permissions.h b/src/cpp/security/accesscontrol/Permissions.h index 242c1239338..e8b34d6bc1c 100644 --- a/src/cpp/security/accesscontrol/Permissions.h +++ b/src/cpp/security/accesscontrol/Permissions.h @@ -81,7 +81,7 @@ class Permissions : public AccessControl bool check_remote_datareader(const PermissionsHandle& remote_handle, const uint32_t domain_id, const ReaderProxyData& subscription_data, - SecurityException& exception) override; + bool& relay_only, SecurityException& exception) override; bool get_participant_sec_attributes(const PermissionsHandle& local_handle, ParticipantSecurityAttributes& attributes, SecurityException& exception) override; diff --git a/src/cpp/security/authentication/PKIDH.cpp b/src/cpp/security/authentication/PKIDH.cpp index 18d015d265c..4b6ac63e638 100644 --- a/src/cpp/security/authentication/PKIDH.cpp +++ b/src/cpp/security/authentication/PKIDH.cpp @@ -48,80 +48,17 @@ using namespace eprosima::fastrtps; using namespace eprosima::fastrtps::rtps; using namespace eprosima::fastrtps::rtps::security; -static size_t alignment(size_t current_alignment, size_t dataSize) { return (dataSize - (current_alignment % dataSize)) & (dataSize-1);} - -size_t BN_serialized_size(const BIGNUM* bn, size_t current_alignment = 0) -{ - size_t initial_alignment = current_alignment; - - current_alignment += 4 + alignment(current_alignment, 4) + BN_num_bytes(bn); - - return current_alignment - initial_alignment; -} - -static unsigned char* BN_serialize(const BIGNUM* bn, const unsigned char* orig_pointer, unsigned char* current_pointer) -{ - assert(bn); - assert(orig_pointer); - assert(current_pointer); - - size_t align = alignment(current_pointer - orig_pointer, 4); - unsigned char* pointer = current_pointer + align; - int32_t len = (int32_t)BN_num_bytes(bn); - -#if __BIG_ENDIAN__ - pointer[0] = ((char*)&len)[0]; - pointer[1] = ((char*)&len)[1]; - pointer[2] = ((char*)&len)[2]; - pointer[3] = ((char*)&len)[3]; -#else - pointer[0] = ((char*)&len)[3]; - pointer[1] = ((char*)&len)[2]; - pointer[2] = ((char*)&len)[1]; - pointer[3] = ((char*)&len)[0]; -#endif - - pointer += 4; - - if(BN_bn2bin(bn, pointer) == len) - return pointer + len; - - return nullptr; -} - -static const unsigned char* BN_deserialize(BIGNUM** bn, const unsigned char* orig_pointer, - const unsigned char* current_pointer, SecurityException& exception) +static const unsigned char* BN_deserialize_raw(BIGNUM** bn, const unsigned char* raw_pointer, + size_t length, SecurityException& exception) { - assert(bn); - assert(orig_pointer); - assert(current_pointer); - - size_t align = alignment(current_pointer - orig_pointer, 4); - const unsigned char* pointer = current_pointer + align; - uint32_t length = 0; - -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - - pointer += 4; - BIGNUM *bnn = BN_new(); - if(bnn != nullptr) + if (bnn != nullptr) { - if(BN_bin2bn(pointer, length, bnn) != nullptr) + if (BN_bin2bn(raw_pointer, length, bnn) != nullptr) { *bn = bnn; - return pointer + length; + return raw_pointer + length; } else exception = _SecurityException_("Cannot deserialize DH"); @@ -160,6 +97,16 @@ static bool get_signature_algorithm(X509* certificate, std::string& signature_al signature_algorithm = ECDSA_SHA256; returnedValue = true; } + else if (strncmp(ptr->data, "sha256WithRSAEncryption", ptr->length) == 0) + { + signature_algorithm = RSA_SHA256; + returnedValue = true; + } + else if (strncmp(ptr->data, "sha1WithRSAEncryption", ptr->length) == 0) + { + signature_algorithm = RSA_SHA256; + returnedValue = true; + } } else exception = _SecurityException_("OpenSSL library cannot retrieve mem ptr"); @@ -325,16 +272,24 @@ static bool verify_certificate(X509_STORE* store, X509* cert, const bool there_a unsigned long flags = there_are_crls ? X509_V_FLAG_CRL_CHECK : 0; if(X509_STORE_CTX_init(ctx, store, cert, NULL) > 0) { - X509_STORE_CTX_set_flags(ctx, flags | X509_V_FLAG_X509_STRICT | + X509_STORE_CTX_set_flags(ctx, flags | /*X509_V_FLAG_X509_STRICT |*/ X509_V_FLAG_CHECK_SS_SIGNATURE | X509_V_FLAG_POLICY_CHECK); - if(X509_verify_cert(ctx) > 0 && X509_STORE_CTX_get_error(ctx) == X509_V_OK) + if(X509_verify_cert(ctx) > 0) { returnedValue = true; } else { - logWarning(SECURITY_AUTHENTICATION, "Invalidation error of certificate (" << X509_STORE_CTX_get_error(ctx) << ")"); + int errorCode = X509_STORE_CTX_get_error(ctx); + if (errorCode == X509_V_OK) + { + logWarning(SECURITY_AUTHENTICATION, "Invalidation error of certificate, but no error code returned."); + } + else + { + logWarning(SECURITY_AUTHENTICATION, "Invalidation error of certificate (" << X509_verify_cert_error_string(errorCode) << ")"); + } } X509_STORE_CTX_cleanup(ctx); @@ -440,16 +395,23 @@ static bool sign_sha256(EVP_PKEY* private_key, const unsigned char* data, const assert(data); bool returnedValue = false; - EVP_MD_CTX* ctx = + #if IS_OPENSSL_1_1 - EVP_MD_CTX_new(); + EVP_MD_CTX* ctx = EVP_MD_CTX_new(); #else - (EVP_MD_CTX*)malloc(sizeof(EVP_MD_CTX)); + EVP_MD_CTX* ctx = (EVP_MD_CTX*)malloc(sizeof(EVP_MD_CTX)); #endif EVP_MD_CTX_init(ctx); + EVP_PKEY_CTX* pkey; - if(EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, private_key) == 1) + auto md = EVP_sha256(); + if(EVP_DigestSignInit(ctx, &pkey, md, NULL, private_key) == 1) { + // TODO (Miguel) don't do this for ECDSA + EVP_PKEY_CTX_set_rsa_padding(pkey, RSA_PKCS1_PSS_PADDING); + EVP_PKEY_CTX_set_rsa_mgf1_md(pkey, md); + EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey, -1); + if(EVP_DigestSignUpdate(ctx, data, data_length) == 1) { size_t length = 0; @@ -504,8 +466,15 @@ static bool check_sign_sha256(X509* certificate, const unsigned char* data, cons if(pubkey != nullptr) { - if(EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, pubkey) == 1) + auto md = EVP_sha256(); + EVP_PKEY_CTX* pkey; + if(EVP_DigestVerifyInit(ctx, &pkey, md, NULL, pubkey) == 1) { + // TODO (Miguel) don't do this for ECDSA + EVP_PKEY_CTX_set_rsa_padding(pkey, RSA_PKCS1_PSS_PADDING); + EVP_PKEY_CTX_set_rsa_mgf1_md(pkey, md); + EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey, -2); + if(EVP_DigestVerifyUpdate(ctx, data, data_length) == 1) { if(EVP_DigestVerifyFinal(ctx, signature.data(), signature.size()) == 1) @@ -628,9 +597,10 @@ static bool adjust_participant_key(X509* cert, const GUID_t& candidate_participa static int get_dh_type(const std::string& algorithm) { - if(algorithm.compare(DH_2048_256) == 0) + auto raw_alg = algorithm.c_str(); + if(strcmp(DH_2048_256, raw_alg) == 0) return EVP_PKEY_DH; - else if(algorithm.compare(ECDH_prime256v1) == 0) + else if(strcmp(ECDH_prime256v1, raw_alg) == 0) return EVP_PKEY_EC; return 0; @@ -638,53 +608,75 @@ static int get_dh_type(const std::string& algorithm) static EVP_PKEY* generate_dh_key(int type, SecurityException& exception) { - EVP_PKEY* keys = nullptr; - EVP_PKEY* params = EVP_PKEY_new(); - EVP_PKEY_CTX* context = nullptr; + EVP_PKEY_CTX* pctx = nullptr; + EVP_PKEY* params = nullptr; - if(params != nullptr) + if (type == EVP_PKEY_EC) { - DH* dh = nullptr; - - switch(type) + pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL); + if (pctx != nullptr) { - case EVP_PKEY_DH: - dh = DH_get_2048_256(); - break; - }; - - if(dh != nullptr) + if ((1 != EVP_PKEY_paramgen_init(pctx)) || + (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1)) || + (1 != EVP_PKEY_paramgen(pctx, ¶ms))) + { + exception = _SecurityException_("Cannot set default paremeters: "); + EVP_PKEY_CTX_free(pctx); + return nullptr; + } + } + else { - int ret = EVP_PKEY_set1_DH(params, dh); - - if(ret) + exception = _SecurityException_("Cannot allocate EVP parameters"); + return nullptr; + } + } + else + { + params = EVP_PKEY_new(); + if (params != nullptr) + { + if (1 != EVP_PKEY_set1_DH(params, DH_get_2048_256())) { - if((context = EVP_PKEY_CTX_new(params, NULL)) != nullptr) - { - if(EVP_PKEY_keygen_init(context)) - { - if(!EVP_PKEY_keygen(context, &keys)) - exception = _SecurityException_("Cannot generate EVP key"); - } - else - exception = _SecurityException_("Cannot init EVP key"); - - EVP_PKEY_CTX_free(context); - } - else - exception = _SecurityException_("Cannot create EVP context"); + exception = _SecurityException_("Cannot set default paremeters: "); + EVP_PKEY_free(params); + return nullptr; } - else - exception = _SecurityException_("Cannot set default paremeters"); - - DH_free(dh); } + else + { + exception = _SecurityException_("Cannot allocate EVP parameters"); + return nullptr; + } + } - EVP_PKEY_free(params); + EVP_PKEY* keys = nullptr; + EVP_PKEY_CTX* kctx = EVP_PKEY_CTX_new(params, NULL); + + if(kctx != nullptr) + { + if(1 == EVP_PKEY_keygen_init(kctx)) + { + if (1 != EVP_PKEY_keygen(kctx, &keys)) + { + exception = _SecurityException_("Cannot generate EVP key"); + } + } + else + { + exception = _SecurityException_("Cannot init EVP key"); + } + + EVP_PKEY_CTX_free(kctx); } else - exception = _SecurityException_("Cannot allocate EVP parameters"); - + { + exception = _SecurityException_("Cannot create EVP context"); + } + + ERR_clear_error(); + EVP_PKEY_free(params); + if (pctx != nullptr) EVP_PKEY_CTX_free(pctx); return keys; } @@ -692,118 +684,130 @@ static bool store_dh_public_key(EVP_PKEY* dhkey, std::vector& buffer, SecurityException& exception) { bool returnedValue = false; - DH* dh = EVP_PKEY_get1_DH(dhkey); + DH* dh = EVP_PKEY_get0_DH(dhkey); if(dh != nullptr) { #if IS_OPENSSL_1_1 - const BIGNUM* p = nullptr; - const BIGNUM* q = nullptr; - const BIGNUM* g = nullptr; - DH_get0_pqg(dh, &p, &q, &g); - const BIGNUM* pub_key = nullptr; const BIGNUM* priv_key = nullptr; DH_get0_key(dh, &pub_key, &priv_key); #else - const BIGNUM* p = dh->p; - const BIGNUM* g = dh->g; const BIGNUM* pub_key = dh->pub_key; #endif - size_t len = BN_serialized_size(p); - len += BN_serialized_size(g); - len += BN_serialized_size(pub_key); + int len = BN_num_bytes(pub_key); buffer.resize(len); unsigned char* pointer = buffer.data(); - if((pointer = BN_serialize(p, buffer.data(), pointer)) != nullptr) + if (BN_bn2bin(pub_key, pointer) == len) + { + returnedValue = true; + } + else + exception = _SecurityException_("Cannot serialize public key"); + } + else + { + EC_KEY* ec = EVP_PKEY_get0_EC_KEY(dhkey); + if (ec != nullptr) { - if((pointer = BN_serialize(g, buffer.data(), pointer)) != nullptr) + auto grp = EC_KEY_get0_group(ec); + auto pub_key = EC_KEY_get0_public_key(ec); + auto len = EC_POINT_point2oct(grp, pub_key, EC_KEY_get_conv_form(ec), NULL, 0, NULL); + buffer.resize(len); + if(EC_POINT_point2oct(grp, pub_key, EC_KEY_get_conv_form(ec), buffer.data(), len, NULL) == len) { - if((pointer = BN_serialize(pub_key, buffer.data(), pointer)) != nullptr) - { - returnedValue = true; - } - else - exception = _SecurityException_("Cannot serialize public key"); + returnedValue = true; } else - exception = _SecurityException_("Cannot serialize g"); + exception = _SecurityException_("Cannot serialize public key"); } - else - exception = _SecurityException_("Cannot serialize p"); - - DH_free(dh); + else + exception = _SecurityException_("OpenSSL library doesn't retrieve DH"); } - else - exception = _SecurityException_("OpenSSL library doesn't retrieve DH"); return returnedValue; } -static EVP_PKEY* generate_dh_peer_key(const std::vector& buffer, SecurityException& exception) +static EVP_PKEY* generate_dh_peer_key(const std::vector& buffer, SecurityException& exception, int alg_kind = EVP_PKEY_DH) { - DH* dh = DH_new(); - - if(dh != nullptr) + if (alg_kind == EVP_PKEY_DH) { - const unsigned char* pointer = buffer.data(); + DH* dh = DH_get_2048_256(); + + if (dh != nullptr) + { + const unsigned char* pointer = buffer.data(); #if IS_OPENSSL_1_1 - BIGNUM* p_ptr = BN_new(); - BIGNUM** p = &p_ptr; - BIGNUM* g_ptr = BN_new(); - BIGNUM** g = &g_ptr; - BIGNUM* pub_key_ptr = BN_new(); - BIGNUM** pub_key = &pub_key_ptr; + BIGNUM* pub_key_ptr; + BIGNUM** pub_key = &pub_key_ptr; #else - BIGNUM** p = &dh->p; - BIGNUM** g = &dh->g; - BIGNUM** pub_key = &dh->pub_key; + BIGNUM** pub_key = &dh->pub_key; #endif - if((pointer = BN_deserialize(p, buffer.data(), pointer, exception)) != nullptr) - { - if((pointer = BN_deserialize(g, buffer.data(), pointer, exception)) != nullptr) + if ((pointer = BN_deserialize_raw(pub_key, buffer.data(), buffer.size(), exception)) != nullptr) { #if IS_OPENSSL_1_1 - DH_set0_pqg(dh, *p, NULL, *g); -#endif - if((pointer = BN_deserialize(pub_key, buffer.data(), pointer, exception)) != nullptr) - { -#if IS_OPENSSL_1_1 - DH_set0_key(dh, *pub_key, NULL); + DH_set0_key(dh, *pub_key, NULL); #endif - EVP_PKEY* key = EVP_PKEY_new(); + EVP_PKEY* key = EVP_PKEY_new(); - if(key != nullptr) + if (key != nullptr) + { + if (EVP_PKEY_assign_DH(key, dh) > 0) { - if(EVP_PKEY_assign_DH(key, dh) > 0) - { - return key; - } - else - exception = _SecurityException_("OpenSSL library cannot set dh in pkey"); - - EVP_PKEY_free(key); + return key; } else - exception = _SecurityException_("OpenSSL library cannot create pkey"); + exception = _SecurityException_("OpenSSL library cannot set dh in pkey"); + + EVP_PKEY_free(key); } else - exception = _SecurityException_("Cannot deserialize public key"); + exception = _SecurityException_("OpenSSL library cannot create pkey"); } else - exception = _SecurityException_("Cannot deserialize g"); + exception = _SecurityException_("Cannot deserialize public key"); } else - exception = _SecurityException_("Cannot deserialize p"); - - DH_free(dh); + exception = _SecurityException_("OpenSSL library cannot create dh"); } else - exception = _SecurityException_("OpenSSL library cannot create dh"); + { + EC_KEY* ec = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); + + if (ec != nullptr) + { + const unsigned char* pointer = buffer.data(); + + if(EC_KEY_oct2key(ec, pointer, buffer.size(), NULL) > 0) + { + EVP_PKEY* key = EVP_PKEY_new(); + + if (key != nullptr) + { + if (EVP_PKEY_assign_EC_KEY(key, ec) > 0) + { + return key; + } + else + exception = _SecurityException_("OpenSSL library cannot set ec in pkey"); + + EVP_PKEY_free(key); + } + else + exception = _SecurityException_("OpenSSL library cannot create pkey"); + } + else + exception = _SecurityException_("Cannot deserialize public key"); + + EC_KEY_free(ec); + } + else + exception = _SecurityException_("OpenSSL library cannot create ec"); + } return nullptr; } @@ -813,7 +817,7 @@ static bool generate_challenge(std::vector& vector, SecurityException& bool returnedValue = false; BIGNUM* bn = BN_new(); - if(BN_rand(bn, 512, 0 /*BN_RAND_TOP_ONE*/, 0 /*BN_RAND_BOTTOM_ANY*/)) + if(BN_rand(bn, 256, 0 /*BN_RAND_TOP_ONE*/, 0 /*BN_RAND_BOTTOM_ANY*/)) { int len = BN_num_bytes(bn); vector.resize(len); @@ -853,7 +857,9 @@ static SharedSecretHandle* generate_sharedsecret(EVP_PKEY* private_key, EVP_PKEY if(EVP_PKEY_derive(ctx, data.value().data(), &length) > 0) { - data.value().resize(length); + uint8_t md[32]; + EVP_Digest(data.value().data(), length, md, NULL, EVP_sha256(), NULL); + data.value().assign(md, md + 32); handle = new SharedSecretHandle(); (*handle)->data_.push_back(std::move(data)); } @@ -1061,62 +1067,22 @@ ValidationResult_t PKIDH::validate_remote_identity(IdentityHandle** remote_ident const PKIIdentityHandle& lih = PKIIdentityHandle::narrow(local_identity_handle); - if(!lih.nil()) + if(!lih.nil() && !remote_identity_token.is_nil()) { // dds.ca.sn const std::string* ca_sn = DataHolderHelper::find_property_value(remote_identity_token, "dds.ca.sn"); - if(ca_sn == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Not found property \"dds.ca.sn\" in remote identity token"); - return ValidationResult_t::VALIDATION_FAILED; - } - - if(*ca_sn != lih->sn) - { - logWarning(SECURITY_AUTHENTICATION, "Invalid CA subject name in remote identity token"); - return ValidationResult_t::VALIDATION_FAILED; - } - - // dds.ca.algo - const std::string* property = DataHolderHelper::find_property_value(remote_identity_token, "dds.ca.algo"); - - if(property == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Not found property \"dds.ca.algo\" in remote identity token"); - return ValidationResult_t::VALIDATION_FAILED; - } - - if(*property != lih->algo) - { - logWarning(SECURITY_AUTHENTICATION, "Invalid CA signature algorithm in remote identity token"); - return ValidationResult_t::VALIDATION_FAILED; - } - // dds.cert.sn - const std::string* cert_sn = DataHolderHelper::find_property_value(remote_identity_token, "dds.cert.sn"); - - if(cert_sn == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Not found property \"dds.cert.sn\" in remote identity token"); - return ValidationResult_t::VALIDATION_FAILED; - } + // const std::string* cert_sn = DataHolderHelper::find_property_value(remote_identity_token, "dds.cert.sn"); // dds.cert.algo const std::string* cert_algo = DataHolderHelper::find_property_value(remote_identity_token, "dds.cert.algo"); - if(cert_algo == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Not found property \"dds.cert.algo\" in remote identity token"); - return ValidationResult_t::VALIDATION_FAILED; - } - - PKIIdentityHandle* rih = new PKIIdentityHandle(); - (*rih)->sn = *ca_sn; - (*rih)->cert_sn_ = *cert_sn; - (*rih)->algo = *cert_algo; + (*rih)->sn = ca_sn ? *ca_sn : ""; + (*rih)->cert_sn_ = ""; // cert_sn ? *cert_sn : ""; + (*rih)->algo = cert_algo ? *cert_algo : ""; (*rih)->participant_key_ = remote_participant_key; *remote_identity_handle = rih; @@ -1218,7 +1184,7 @@ ValidationResult_t PKIDH::begin_handshake_request(HandshakeHandle** handshake_ha // TODO(Ricardo) Have to add +3 because current serialization add alignment bytes at the end. CDRMessage_t message(static_cast(BinaryPropertyHelper::serialized_size((*handshake_handle_aux)->handshake_message_.binary_properties())) + 3); message.msg_endian = BIGEND; - CDRMessage::addBinaryPropertySeq(&message, (*handshake_handle_aux)->handshake_message_.binary_properties()); + CDRMessage::addBinaryPropertySeq(&message, (*handshake_handle_aux)->handshake_message_.binary_properties(),false); if(!EVP_Digest(message.buffer, message.length, md, NULL, EVP_sha256(), NULL)) { exception = _SecurityException_("OpenSSL library cannot hash sha256"); @@ -1319,12 +1285,13 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand assert(cert_sn != nullptr); char* cert_sn_str = X509_NAME_oneline(cert_sn, 0, 0); assert(cert_sn_str != nullptr); - if(rih->cert_sn_.compare(cert_sn_str) != 0) + if(!rih->cert_sn_.empty() && rih->cert_sn_.compare(cert_sn_str) != 0) { OPENSSL_free(cert_sn_str); logWarning(SECURITY_AUTHENTICATION, "Certificated subject name invalid"); return ValidationResult_t::VALIDATION_FAILED; } + rih->cert_sn_.assign(cert_sn_str); OPENSSL_free(cert_sn_str); BIO* cert_sn_rfc2253_str = BIO_new(BIO_s_mem()); X509_NAME_print_ex(cert_sn_rfc2253_str, cert_sn, 0, XN_FLAG_RFC2253 & ~ASN1_STRFLGS_ESC_MSB); @@ -1374,7 +1341,7 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand cdr_pdata.max_size = (uint32_t)pdata->size(); cdr_pdata.buffer = (octet*)pdata->data(); ParticipantProxyData remote_participant_data; - if(!remote_participant_data.readFromCDRMessage(&cdr_pdata)) + if(!remote_participant_data.readFromCDRMessage(&cdr_pdata, false)) { logWarning(SECURITY_AUTHENTICATION, "Cannot deserialize ParticipantProxyData in property c.pdata"); return ValidationResult_t::VALIDATION_FAILED; @@ -1387,6 +1354,7 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand } unsigned char md[SHA256_DIGEST_LENGTH]; + unsigned char hash_c1[SHA256_DIGEST_LENGTH]; unsigned int length = 0; if(!X509_NAME_digest(cert_sn, EVP_sha256(), md, &length) || length != SHA256_DIGEST_LENGTH) @@ -1422,8 +1390,8 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand // Check signature algorithm std::string s_dsign_algo(dsign_algo->begin(), dsign_algo->end()); - if(s_dsign_algo.compare(RSA_SHA256) != 0 && - s_dsign_algo.compare(ECDSA_SHA256) != 0) + if(strcmp(RSA_SHA256, s_dsign_algo.c_str()) != 0 && + strcmp(ECDSA_SHA256, s_dsign_algo.c_str()) != 0) { logWarning(SECURITY_AUTHENTICATION, "Not supported signature algorithm (" << s_dsign_algo << ")"); return ValidationResult_t::VALIDATION_FAILED; @@ -1441,44 +1409,37 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand // Check key agreement algorithm std::string s_kagree_algo(kagree_algo->begin(), kagree_algo->end()); - if(s_kagree_algo.compare(DH_2048_256) != 0 && - s_kagree_algo.compare(ECDH_prime256v1) != 0) + if(strcmp(DH_2048_256, s_kagree_algo.c_str()) != 0 && + strcmp(ECDH_prime256v1, s_kagree_algo.c_str()) != 0) { logWarning(SECURITY_AUTHENTICATION, "Not supported key agreement algorithm (" << s_kagree_algo << ")"); return ValidationResult_t::VALIDATION_FAILED; } rih->kagree_alg_ = std::move(s_kagree_algo); - // hash_c1 - std::vector* hash_c1 = DataHolderHelper::find_binary_property_value(handshake_message_in, "hash_c1"); - - if(hash_c1 == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property hash_c1"); - return ValidationResult_t::VALIDATION_FAILED; - } - - if(hash_c1->size() != SHA256_DIGEST_LENGTH) - { - logWarning(SECURITY_AUTHENTICATION, "Wrong size of hash_c1"); - return ValidationResult_t::VALIDATION_FAILED; - } - // TODO(Ricardo) Have to add +3 because current serialization add alignment bytes at the end. CDRMessage_t cdrmessage(static_cast(BinaryPropertyHelper::serialized_size(handshake_message_in.binary_properties())) + 3); cdrmessage.msg_endian = BIGEND; - CDRMessage::addBinaryPropertySeq(&cdrmessage, handshake_message_in.binary_properties(), "hash_c1"); + CDRMessage::addBinaryPropertySeq(&cdrmessage, handshake_message_in.binary_properties(), "c.", false); - if(!EVP_Digest(cdrmessage.buffer, cdrmessage.length, md, NULL, EVP_sha256(), NULL)) + if (!EVP_Digest(cdrmessage.buffer, cdrmessage.length, hash_c1, NULL, EVP_sha256(), NULL)) { - exception = _SecurityException_("Cannot generate SHA256 of request"); + logWarning(SECURITY_AUTHENTICATION, "Cannot generate SHA256 of request"); return ValidationResult_t::VALIDATION_FAILED; } - - if(memcmp(md, hash_c1->data(), SHA256_DIGEST_LENGTH) != 0) + else { - logWarning(SECURITY_AUTHENTICATION, "Wrong hash_c1"); - return ValidationResult_t::VALIDATION_FAILED; + // hash_c1 + std::vector* hash_c1_vec = DataHolderHelper::find_binary_property_value(handshake_message_in, "hash_c1"); + + if (hash_c1_vec != nullptr) + { + if( (hash_c1_vec->size() == SHA256_DIGEST_LENGTH) && + (memcmp(hash_c1, hash_c1_vec->data(), SHA256_DIGEST_LENGTH) != 0) ) + { + logWarning(SECURITY_AUTHENTICATION, "Wrong hash_c1"); + } + } } // dh1 @@ -1504,8 +1465,10 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand (*handshake_handle_aux)->kagree_alg_ = rih->kagree_alg_; (*handshake_handle_aux)->handshake_message_.class_id("DDS:Auth:PKI-DH:1.0+Reply"); + int kagree_kind = get_dh_type((*handshake_handle_aux)->kagree_alg_); + // Store dh1 - if(((*handshake_handle_aux)->peerkeys_ = generate_dh_peer_key(*dh1, exception)) == nullptr) + if(((*handshake_handle_aux)->peerkeys_ = generate_dh_peer_key(*dh1, exception, kagree_kind)) == nullptr) { exception = _SecurityException_("Cannot store peer key from dh1"); return ValidationResult_t::VALIDATION_FAILED; @@ -1566,7 +1529,7 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand // TODO(Ricardo) Have to add +3 because current serialization add alignment bytes at the end. CDRMessage_t message(static_cast(BinaryPropertyHelper::serialized_size((*handshake_handle_aux)->handshake_message_.binary_properties())) + 3); message.msg_endian = BIGEND; - CDRMessage::addBinaryPropertySeq(&message, (*handshake_handle_aux)->handshake_message_.binary_properties()); + CDRMessage::addBinaryPropertySeq(&message, (*handshake_handle_aux)->handshake_message_.binary_properties(), false); if(!EVP_Digest(message.buffer, message.length, md, NULL, EVP_sha256(), NULL)) { exception = _SecurityException_("OpenSSL library cannot hash sha256"); @@ -1579,7 +1542,7 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand (*handshake_handle_aux)->handshake_message_.binary_properties().push_back(std::move(bproperty)); // dh2 - if(((*handshake_handle_aux)->dhkeys_ = generate_dh_key(get_dh_type((*handshake_handle_aux)->kagree_alg_), exception)) != nullptr) + if(((*handshake_handle_aux)->dhkeys_ = generate_dh_key(kagree_kind, exception)) != nullptr) { bproperty.name("dh2"); bproperty.propagate(true); @@ -1590,7 +1553,7 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand // hash_c1 bproperty.name("hash_c1"); - bproperty.value(std::move(*hash_c1)); + bproperty.value().assign(hash_c1, hash_c1 + SHA256_DIGEST_LENGTH); bproperty.propagate(true); (*handshake_handle_aux)->handshake_message_.binary_properties().push_back(std::move(bproperty)); @@ -1629,7 +1592,7 @@ ValidationResult_t PKIDH::begin_handshake_reply(HandshakeHandle** handshake_hand //add dh1 CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property((*handshake_handle_aux)->handshake_message_, "dh1")); //add hash_c1 - CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property((*handshake_handle_aux)->handshake_message_, "hash_c1")); + CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property((*handshake_handle_aux)->handshake_message_, "hash_c1"), false); bproperty.name("signature"); bproperty.propagate("true"); @@ -1675,7 +1638,7 @@ ValidationResult_t PKIDH::process_handshake(HandshakeMessageToken** handshake_me { returnedValue = process_handshake_reply(handshake_message_out, std::move(handshake_message_in), handshake, exception); - } + } else { logWarning(SECURITY_AUTHENTICATION, "Handshake message not supported (" << handshake->handshake_message_.class_id() << ")"); @@ -1721,7 +1684,7 @@ ValidationResult_t PKIDH::process_handshake_request(HandshakeMessageToken** hand assert(cert_sn != nullptr); char* cert_sn_str = X509_NAME_oneline(cert_sn, 0, 0); assert(cert_sn_str != nullptr); - if(rih->cert_sn_.compare(cert_sn_str) != 0) + if(!rih->cert_sn_.empty() && rih->cert_sn_.compare(cert_sn_str) != 0) { OPENSSL_free(cert_sn_str); logWarning(SECURITY_AUTHENTICATION, "Certificated subject name invalid"); @@ -1776,7 +1739,7 @@ ValidationResult_t PKIDH::process_handshake_request(HandshakeMessageToken** hand cdr_pdata.max_size = (uint32_t)pdata->size(); cdr_pdata.buffer = (octet*)pdata->data(); ParticipantProxyData remote_participant_data; - if(!remote_participant_data.readFromCDRMessage(&cdr_pdata)) + if(!remote_participant_data.readFromCDRMessage(&cdr_pdata, false)) { logWarning(SECURITY_AUTHENTICATION, "Cannot deserialize ParticipantProxyData in property c.pdata"); return ValidationResult_t::VALIDATION_FAILED; @@ -1865,9 +1828,10 @@ ValidationResult_t PKIDH::process_handshake_request(HandshakeMessageToken** hand } // TODO(Ricardo) Have to add +3 because current serialization add alignment bytes at the end. - CDRMessage_t cdrmessage(static_cast(BinaryPropertyHelper::serialized_size(handshake_message_in.binary_properties()))+ 3); + uint32_t digestInLen = static_cast(BinaryPropertyHelper::serialized_size(handshake_message_in.binary_properties())); + CDRMessage_t cdrmessage(digestInLen + 3); cdrmessage.msg_endian = BIGEND; - CDRMessage::addBinaryPropertySeq(&cdrmessage, handshake_message_in.binary_properties(), "hash_c2"); + CDRMessage::addBinaryPropertySeq(&cdrmessage, handshake_message_in.binary_properties(), "c.", false); if(!EVP_Digest(cdrmessage.buffer, cdrmessage.length, md, NULL, EVP_sha256(), NULL)) { @@ -1996,7 +1960,7 @@ ValidationResult_t PKIDH::process_handshake_request(HandshakeMessageToken** hand //add dh1 CDRMessage::addBinaryProperty(&cdrmessage2, *dh1); //add hash_c1 - CDRMessage::addBinaryProperty(&cdrmessage2, *hash_c1); + CDRMessage::addBinaryProperty(&cdrmessage2, *hash_c1, false); if(!check_sign_sha256(rih->cert_, cdrmessage2.buffer, cdrmessage2.length, *signature, exception)) { @@ -2063,7 +2027,7 @@ ValidationResult_t PKIDH::process_handshake_request(HandshakeMessageToken** hand //add dh2 CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property(final_message, "dh2")); //add hash_c2 - CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property(final_message, "hash_c2")); + CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property(final_message, "hash_c2"), false); bproperty.name("signature"); bproperty.propagate("true"); @@ -2109,167 +2073,142 @@ ValidationResult_t PKIDH::process_handshake_reply(HandshakeMessageToken** /*hand } // Check incomming handshake. - // hash_c1 - BinaryProperty* hash_c1 = DataHolderHelper::find_binary_property(handshake_message_in, "hash_c1"); - - if(hash_c1 == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property hash_c1"); - return ValidationResult_t::VALIDATION_FAILED; - } - std::vector* hash_c1_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "hash_c1"); - - if(hash_c1_reply == nullptr) - { - exception = _SecurityException_("Cannot find property hash_c1 in reply message"); - return ValidationResult_t::VALIDATION_FAILED; - } - - if(hash_c1->value() != *hash_c1_reply) - { - logWarning(SECURITY_AUTHENTICATION, "Invalid hash_c1"); - return ValidationResult_t::VALIDATION_FAILED; - } - - // hash_c2 - BinaryProperty* hash_c2 = DataHolderHelper::find_binary_property(handshake_message_in, "hash_c2"); - - if(hash_c2 == nullptr) - { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property hash_c2"); - return ValidationResult_t::VALIDATION_FAILED; - } - - std::vector* hash_c2_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "hash_c2"); - - if(hash_c2_reply == nullptr) + // challenge1 (mandatory) + BinaryProperty* challenge1 = DataHolderHelper::find_binary_property(handshake_message_in, "challenge1"); + if (challenge1 == nullptr) { - exception = _SecurityException_("Cannot find property hash_c2 in reply message"); + logWarning(SECURITY_AUTHENTICATION, "Cannot find property challenge1"); return ValidationResult_t::VALIDATION_FAILED; } - if(hash_c2->value() != *hash_c2_reply) + std::vector* challenge1_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "challenge1"); + if (challenge1_reply == nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Invalid hash_c2"); + exception = _SecurityException_("Cannot find property challenge1 in reply message"); return ValidationResult_t::VALIDATION_FAILED; } - // dh1 - BinaryProperty* dh1 = DataHolderHelper::find_binary_property(handshake_message_in, "dh1"); - - if(dh1 == nullptr) + if (challenge1->value() != *challenge1_reply) { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property dh1"); + logWarning(SECURITY_AUTHENTICATION, "Invalid challenge1"); return ValidationResult_t::VALIDATION_FAILED; } - std::vector* dh1_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "dh1"); - - if(dh1_reply == nullptr) + // challenge2 (mandatory) + BinaryProperty* challenge2 = DataHolderHelper::find_binary_property(handshake_message_in, "challenge2"); + if (challenge2 == nullptr) { - exception = _SecurityException_("Cannot find property dh1 in reply message"); + logWarning(SECURITY_AUTHENTICATION, "Cannot find property challenge2"); return ValidationResult_t::VALIDATION_FAILED; } - if(dh1->value() != *dh1_reply) + std::vector* challenge2_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "challenge2"); + if (challenge2_reply == nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Invalid dh1"); + exception = _SecurityException_("Cannot find property challenge2 in reply message"); return ValidationResult_t::VALIDATION_FAILED; } - // dh2 - BinaryProperty* dh2 = DataHolderHelper::find_binary_property(handshake_message_in, "dh2"); - - if(dh2 == nullptr) + if (challenge2->value() != *challenge2_reply) { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property dh2"); + logWarning(SECURITY_AUTHENTICATION, "Invalid challenge2"); return ValidationResult_t::VALIDATION_FAILED; } - std::vector* dh2_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "dh2"); - - if(dh2_reply == nullptr) + // signature (mandatory) + const std::vector* signature = DataHolderHelper::find_binary_property_value(handshake_message_in, "signature"); + if (signature == nullptr) { - exception = _SecurityException_("Cannot find property dh2 in reply message"); + logWarning(SECURITY_AUTHENTICATION, "Cannot find property signature"); return ValidationResult_t::VALIDATION_FAILED; } - if(dh2->value() != *dh2_reply) + // hash_c1 (optional) + BinaryProperty* hash_c1_reply = DataHolderHelper::find_binary_property(handshake_handle->handshake_message_, "hash_c1"); + if(hash_c1_reply == nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Invalid dh2"); + exception = _SecurityException_("Cannot find property hash_c1 in reply message"); return ValidationResult_t::VALIDATION_FAILED; } - BinaryProperty* challenge1 = DataHolderHelper::find_binary_property(handshake_message_in, "challenge1"); - - if(challenge1 == nullptr) + BinaryProperty* hash_c1 = DataHolderHelper::find_binary_property(handshake_message_in, "hash_c1"); + if (hash_c1 != nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property challenge1"); - return ValidationResult_t::VALIDATION_FAILED; + if (hash_c1->value() != hash_c1_reply->value()) + { + logWarning(SECURITY_AUTHENTICATION, "Invalid hash_c1"); + } } - std::vector* challenge1_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "challenge1"); - - if(challenge1_reply == nullptr) + // hash_c2 (optional) + BinaryProperty* hash_c2_reply = DataHolderHelper::find_binary_property(handshake_handle->handshake_message_, "hash_c2"); + if(hash_c2_reply == nullptr) { - exception = _SecurityException_("Cannot find property challenge1 in reply message"); + exception = _SecurityException_("Cannot find property hash_c2 in reply message"); return ValidationResult_t::VALIDATION_FAILED; } - if(challenge1->value() != *challenge1_reply) + BinaryProperty* hash_c2 = DataHolderHelper::find_binary_property(handshake_message_in, "hash_c2"); + if (hash_c2 != nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Invalid challenge1"); - return ValidationResult_t::VALIDATION_FAILED; + if (hash_c2->value() != hash_c2_reply->value()) + { + logWarning(SECURITY_AUTHENTICATION, "Invalid hash_c2"); + } } - BinaryProperty* challenge2 = DataHolderHelper::find_binary_property(handshake_message_in, "challenge2"); - - if(challenge2 == nullptr) + // dh1 (optional) + BinaryProperty* dh1_reply = DataHolderHelper::find_binary_property(handshake_handle->handshake_message_, "dh1"); + if(dh1_reply == nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property challenge2"); + exception = _SecurityException_("Cannot find property dh1 in reply message"); return ValidationResult_t::VALIDATION_FAILED; } - std::vector* challenge2_reply = DataHolderHelper::find_binary_property_value(handshake_handle->handshake_message_, "challenge2"); - - if(challenge2_reply == nullptr) + BinaryProperty* dh1 = DataHolderHelper::find_binary_property(handshake_message_in, "dh1"); + if (dh1 != nullptr) { - exception = _SecurityException_("Cannot find property challenge2 in reply message"); - return ValidationResult_t::VALIDATION_FAILED; + if (dh1->value() != dh1_reply->value()) + { + logWarning(SECURITY_AUTHENTICATION, "Invalid dh1"); + } } - if(challenge2->value() != *challenge2_reply) + // dh2 (optional) + BinaryProperty* dh2_reply = DataHolderHelper::find_binary_property(handshake_handle->handshake_message_, "dh2"); + if(dh2_reply == nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Invalid challenge2"); + exception = _SecurityException_("Cannot find property dh2 in reply message"); return ValidationResult_t::VALIDATION_FAILED; } - const std::vector* signature = DataHolderHelper::find_binary_property_value(handshake_message_in, "signature"); - - if(signature == nullptr) + BinaryProperty* dh2 = DataHolderHelper::find_binary_property(handshake_message_in, "dh2"); + if (dh2 != nullptr) { - logWarning(SECURITY_AUTHENTICATION, "Cannot find property signature"); - return ValidationResult_t::VALIDATION_FAILED; + if (dh2->value() != dh2_reply->value()) + { + logWarning(SECURITY_AUTHENTICATION, "Invalid dh2"); + } } // signature - CDRMessage_t cdrmessage(static_cast(BinaryPropertyHelper::serialized_size(handshake_message_in.binary_properties()))); + CDRMessage_t cdrmessage(static_cast(BinaryPropertyHelper::serialized_size(handshake_handle->handshake_message_.binary_properties()))); cdrmessage.msg_endian = BIGEND; // add sequence length CDRMessage::addUInt32(&cdrmessage, 6); //add hash_c1 - CDRMessage::addBinaryProperty(&cdrmessage, *hash_c1); + CDRMessage::addBinaryProperty(&cdrmessage, *hash_c1_reply); //add challenge1 CDRMessage::addBinaryProperty(&cdrmessage, *challenge1); //add dh1 - CDRMessage::addBinaryProperty(&cdrmessage, *dh1); + CDRMessage::addBinaryProperty(&cdrmessage, *dh1_reply); //add challenge2 CDRMessage::addBinaryProperty(&cdrmessage, *challenge2); //add dh2 - CDRMessage::addBinaryProperty(&cdrmessage, *dh2); + CDRMessage::addBinaryProperty(&cdrmessage, *dh2_reply); //add hash_c2 - CDRMessage::addBinaryProperty(&cdrmessage, *hash_c2); + CDRMessage::addBinaryProperty(&cdrmessage, *hash_c2_reply, false); if(!check_sign_sha256(rih->cert_, cdrmessage.buffer, cdrmessage.length, *signature, exception)) { diff --git a/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.cpp b/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.cpp index 6c65e065a25..4e180b08f01 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.cpp +++ b/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.cpp @@ -62,7 +62,7 @@ bool AESGCMGMAC_KeyExchange::create_local_participant_crypto_tokens( BinaryProperty prop; prop.name() = std::string("dds.cryp.keymat"); std::vector plaintext= KeyMaterialCDRSerialize(remote_participant->Participant2ParticipantKeyMaterial.at(0)); - prop.value() = aes_128_gcm_encrypt(plaintext, remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key); + prop.value() = plaintext; // aes_128_gcm_encrypt(plaintext, remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key); prop.propagate(true); if(prop.value().size() == 0) @@ -107,14 +107,15 @@ bool AESGCMGMAC_KeyExchange::set_remote_participant_crypto_tokens( return false; } //Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial - std::vector plaintext = aes_128_gcm_decrypt(remote_participant_tokens.at(0).binary_properties().at(0).value(), - remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key); + std::vector plaintext = remote_participant_tokens.at(0).binary_properties().at(0).value(); + // std::vector plaintext = aes_128_gcm_decrypt(remote_participant_tokens.at(0).binary_properties().at(0).value(), + // remote_participant->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key); if(plaintext.size() == 0) return false; KeyMaterial_AES_GCM_GMAC keymat; - keymat = KeyMaterialCDRDeserialize(&plaintext); + KeyMaterialCDRDeserialize(keymat, &plaintext); remote_participant->RemoteParticipant2ParticipantKeyMaterial.push_back(keymat); return true; @@ -138,20 +139,23 @@ bool AESGCMGMAC_KeyExchange::create_local_datawriter_crypto_tokens( //Flush previously present CryptoTokens local_datawriter_crypto_tokens.clear(); - //Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant - DatawriterCryptoToken temp; - temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC"); - BinaryProperty prop; - prop.name() = std::string("dds.cryp.keymat"); - std::vector plaintext= KeyMaterialCDRSerialize(remote_reader->Remote2EntityKeyMaterial.at(0)); - prop.value() = aes_128_gcm_encrypt(plaintext, remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key); - prop.propagate(true); - - if(prop.value().size() == 0) - return false; + for (auto& it : remote_reader->Remote2EntityKeyMaterial) + { + //Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant + DatawriterCryptoToken temp; + temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC"); + BinaryProperty prop; + prop.name() = std::string("dds.cryp.keymat"); + std::vector plaintext = KeyMaterialCDRSerialize(it); + prop.value() = plaintext; // aes_128_gcm_encrypt(plaintext, remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key); + prop.propagate(true); + + if (prop.value().size() == 0) + return false; - temp.binary_properties().push_back(std::move(prop)); - local_datawriter_crypto_tokens.push_back(std::move(temp)); + temp.binary_properties().push_back(std::move(prop)); + local_datawriter_crypto_tokens.push_back(std::move(temp)); + } return true; } @@ -174,14 +178,15 @@ bool AESGCMGMAC_KeyExchange::create_local_datareader_crypto_tokens( local_datareader_crypto_tokens.clear(); //Participant2ParticipantKeyMaterial will be come RemoteParticipant2ParticipantKeyMaterial on the other side + for (auto& it : remote_writer->Remote2EntityKeyMaterial) { //Only the KeyMaterial used in conjunction with the remote_participant are tokenized. In this implementation only on Pariticipant2ParticipantKeyMaterial exists per matched Participant DatareaderCryptoToken temp; temp.class_id() = std::string("DDS:Crypto:AES_GCM_GMAC"); BinaryProperty prop; prop.name() = std::string("dds.cryp.keymat"); - std::vector plaintext= KeyMaterialCDRSerialize(remote_writer->Remote2EntityKeyMaterial.at(0)); - prop.value() = aes_128_gcm_encrypt(plaintext, remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key); + std::vector plaintext= KeyMaterialCDRSerialize(it); + prop.value() = plaintext; // aes_128_gcm_encrypt(plaintext, remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key); prop.propagate(true); if(prop.value().size() == 0) @@ -206,44 +211,50 @@ bool AESGCMGMAC_KeyExchange::set_remote_datareader_crypto_tokens( logWarning(SECURITY_CRYPTO,"Invalid CryptoHandle received"); return false; } - //As only relevant KeyMaterials are tokenized, only one Token is exchanged - if(remote_datareader_tokens.size() != 1){ + //As only relevant KeyMaterials are tokenized, only one or two Token are exchanged + auto nTokens = remote_datareader_tokens.size(); + if(nTokens != 1 && nTokens != 2){ logWarning(SECURITY_CRYPTO,"Malformed CryptoTokenSequence"); exception = SecurityException("Incorrect remote CryptoSequence length"); return false; } - if(remote_datareader_tokens.at(0).class_id() != "DDS:Crypto:AES_GCM_GMAC"){ - logWarning(SECURITY_CRYPTO,"Malformed CryptoToken"); - exception = SecurityException("Incorrect token type received"); - return false; - } - - if(remote_datareader_tokens.at(0).binary_properties().size() !=1 || remote_datareader_tokens.at(0).properties().size() != 0 || - remote_datareader_tokens.at(0).binary_properties().at(0).name() != "dds.cryp.keymat") + for (size_t i = 0; i < nTokens; i++) { - logWarning(SECURITY_CRYPTO,"Malformed CryptoToken"); - exception = SecurityException("Malformed CryptoToken"); - return false; - } + if (remote_datareader_tokens.at(i).class_id() != "DDS:Crypto:AES_GCM_GMAC") + { + logWarning(SECURITY_CRYPTO, "Malformed CryptoToken"); + exception = SecurityException("Incorrect token type received"); + return false; + } + + if (remote_datareader_tokens.at(i).binary_properties().size() != 1 || remote_datareader_tokens.at(i).properties().size() != 0 || + remote_datareader_tokens.at(i).binary_properties().at(0).name() != "dds.cryp.keymat") + { + logWarning(SECURITY_CRYPTO, "Malformed CryptoToken"); + exception = SecurityException("Malformed CryptoToken"); + return false; + } - std::unique_lock remote_reader_lock(remote_reader->mutex_); + std::unique_lock remote_reader_lock(remote_reader->mutex_); - //Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial - std::vector plaintext = aes_128_gcm_decrypt(remote_datareader_tokens.at(0).binary_properties().at(0).value(), - remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key); + //Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial + std::vector plaintext = remote_datareader_tokens.at(i).binary_properties().at(0).value(); + // std::vector plaintext = aes_128_gcm_decrypt(remote_datareader_tokens.at(i).binary_properties().at(0).value(), + // remote_reader->Participant2ParticipantKxKeyMaterial.master_sender_key); - if(plaintext.size() == 0) - return false; + if (plaintext.size() == 0) + return false; - KeyMaterial_AES_GCM_GMAC keymat; - keymat = KeyMaterialCDRDeserialize(&plaintext); - remote_reader->Entity2RemoteKeyMaterial.push_back(keymat); + KeyMaterial_AES_GCM_GMAC keymat; + KeyMaterialCDRDeserialize(keymat, &plaintext); + remote_reader->Entity2RemoteKeyMaterial.push_back(keymat); - remote_reader_lock.unlock(); + remote_reader_lock.unlock(); - std::unique_lock local_writer_lock(local_writer->mutex_); + std::unique_lock local_writer_lock(local_writer->mutex_); - local_writer->Remote2EntityKeyMaterial.push_back(keymat); + local_writer->Remote2EntityKeyMaterial.push_back(keymat); + } return true; } @@ -261,46 +272,53 @@ bool AESGCMGMAC_KeyExchange::set_remote_datawriter_crypto_tokens( logWarning(SECURITY_CRYPTO,"Invalid CryptoHandle"); return false; } - //As only relevant KeyMaterials are tokenized, only one Token is exchanged - if(remote_datawriter_tokens.size() != 1){ + //As only relevant KeyMaterials are tokenized, only one or two Token are exchanged + auto nTokens = remote_datawriter_tokens.size(); + if(nTokens != 1 && nTokens != 2){ logWarning(SECURITY_CRYPTO,"Malformed CryptoTokenSequence"); exception = SecurityException("Incorrect remote CryptoSequence length"); return false; } - if(remote_datawriter_tokens.at(0).class_id() != "DDS:Crypto:AES_GCM_GMAC"){ - logWarning(SECURITY_CRYPTO,"Malformed CryptoToken"); - exception = SecurityException("Incorrect token type received"); - return false; - } - if(remote_datawriter_tokens.at(0).binary_properties().size() !=1 || remote_datawriter_tokens.at(0).properties().size() != 0 || - remote_datawriter_tokens.at(0).binary_properties().at(0).name() != "dds.cryp.keymat") + for (size_t i = 0; i < nTokens; i++) { - logWarning(SECURITY_CRYPTO,"Malformed CryptoToken"); - exception = SecurityException("Malformed CryptoToken"); - return false; - } + if (remote_datawriter_tokens.at(i).class_id() != "DDS:Crypto:AES_GCM_GMAC") + { + logWarning(SECURITY_CRYPTO, "Malformed CryptoToken"); + exception = SecurityException("Incorrect token type received"); + return false; + } - std::unique_lock remote_writer_lock(remote_writer->mutex_); + if (remote_datawriter_tokens.at(i).binary_properties().size() != 1 || remote_datawriter_tokens.at(i).properties().size() != 0 || + remote_datawriter_tokens.at(i).binary_properties().at(0).name() != "dds.cryp.keymat") + { + logWarning(SECURITY_CRYPTO, "Malformed CryptoToken"); + exception = SecurityException("Malformed CryptoToken"); + return false; + } - //Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial - std::vector plaintext = aes_128_gcm_decrypt(remote_datawriter_tokens.at(0).binary_properties().at(0).value(), - remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key); + std::unique_lock remote_writer_lock(remote_writer->mutex_); - if(plaintext.size() == 0) - return false; + //Valid CryptoToken, we can decrypt and push the resulting KeyMaterial in as a RemoteParticipant2ParticipantKeyMaterial + std::vector plaintext = remote_datawriter_tokens.at(i).binary_properties().at(0).value(); + // std::vector plaintext = aes_128_gcm_decrypt(remote_datawriter_tokens.at(i).binary_properties().at(0).value(), + // remote_writer->Participant2ParticipantKxKeyMaterial.master_sender_key); - KeyMaterial_AES_GCM_GMAC keymat; - keymat = KeyMaterialCDRDeserialize(&plaintext); + if (plaintext.size() == 0) + return false; + + KeyMaterial_AES_GCM_GMAC keymat; + KeyMaterialCDRDeserialize(keymat, &plaintext); - remote_writer->Entity2RemoteKeyMaterial.push_back(keymat); + remote_writer->Entity2RemoteKeyMaterial.push_back(keymat); - remote_writer_lock.unlock(); + remote_writer_lock.unlock(); - std::unique_lock local_writer_lock(local_reader->mutex_); + std::unique_lock local_writer_lock(local_reader->mutex_); - //TODO(Ricardo) Why? - local_reader->Remote2EntityKeyMaterial.push_back(keymat); + //TODO(Ricardo) Why? + local_reader->Remote2EntityKeyMaterial.push_back(keymat); + } return true; } @@ -314,63 +332,155 @@ bool AESGCMGMAC_KeyExchange::return_crypto_tokens( return false; } -std::vector AESGCMGMAC_KeyExchange::KeyMaterialCDRSerialize(KeyMaterial_AES_GCM_GMAC &key){ - -std::vector buffer; +std::vector AESGCMGMAC_KeyExchange::KeyMaterialCDRSerialize(KeyMaterial_AES_GCM_GMAC &key) +{ + std::vector buffer; - // TODO(Ricardo) If it is stored as sequences, wrong serialization. Review - buffer.push_back(4); + // transform_kind : octet[4] for(int i=0;i<4;i++){ buffer.push_back(key.transformation_kind[i]); } - buffer.push_back(2); - for(int i=0;i<32;i++){ - buffer.push_back(key.master_salt[i]); - } - buffer.push_back(4); - for(int i=0;i<4;i++){ - buffer.push_back(key.sender_key_id[i]); - } - buffer.push_back(32); - for(int i=0;i<32;i++){ - buffer.push_back(key.master_sender_key[i]); - } - buffer.push_back(4); - for(int i=0;i<4;i++){ - buffer.push_back(key.receiver_specific_key_id[i]); + + // Only last byte different from 0 + auto kind = key.transformation_kind[3]; + if (kind == 0) + { + // KIND = NONE => empty key material + + // empty master_salt - 0 0 0 0 + // empty sender_key_id - 0 0 0 0 + // empty master_sender_key - 0 0 0 0 + // empty receiver_specific_key_id - 0 0 0 0 + // empty master_receiver_specific_key - 0 0 0 0 + // Total 40 bytes to 0 + buffer.insert(buffer.end(), 40, 0x00); } - buffer.push_back(32); - for(int i=0;i<32;i++){ - buffer.push_back(key.master_receiver_specific_key[i]); + else + { + // 128 bits for kinds 1 and 2. 256 bits for kinds 3 and 4. + uint8_t key_len = kind <= 2 ? 16 : 32; + + // master_salt : sequence + buffer.insert(buffer.end(), 3, 0); + buffer.push_back(key_len); + for (uint8_t i=0; i + buffer.insert(buffer.end(), 3, 0); + buffer.push_back(key_len); + for (uint8_t i=0; i + buffer.insert(buffer.end(), 3, 0); + buffer.push_back(key_len); + for (uint8_t i=0; i *CDR) +void AESGCMGMAC_KeyExchange::KeyMaterialCDRDeserialize(KeyMaterial_AES_GCM_GMAC& buffer, std::vector *CDR) { - KeyMaterial_AES_GCM_GMAC buffer; - for(int i=1; i<5; i++){ - buffer.transformation_kind[i-1] = CDR->at(i); - } - for(int i=6; i<38; i++){ - buffer.master_salt[i-6] = CDR->at(i); - } - for(int i=39; i<43; i++){ - buffer.sender_key_id[i-39] = CDR->at(i); - } - for(int i=44; i<76; i++){ - buffer.master_sender_key[i-44] = CDR->at(i); - } - for(int i=77; i<81; i++){ - buffer.receiver_specific_key_id[i-77] = CDR->at(i); + buffer.transformation_kind.fill(0); + buffer.master_salt.fill(0); + buffer.master_sender_key.fill(0); + buffer.master_receiver_specific_key.fill(0); + + // transformation kind is always 0 0 0 n + // TODO: Check 0 values + const uint8_t* data = CDR->data(); + uint8_t kind = data[3]; + buffer.transformation_kind[3] = kind; + if (kind == 0) + { + // empty key material + buffer.sender_key_id.fill(0); + buffer.receiver_specific_key_id.fill(0); } - for(int i=82; i< 114; i++){ - buffer.master_receiver_specific_key[i-82] = CDR->at(i); + else + { + // 128 bits for kinds 1 and 2. 256 bits for kinds 3 and 4. + // TODO: Check desired length + // uint8_t desired_key_len = kind <= 2 ? 16 : 32; + + uint8_t key_len; + uint8_t pos; + + // master_salt : sequence + // seq_len would always be 0 0 0 n + // TODO: check 0 values + pos = 4 + 3; // 4 - transformation_kind. 3 - 0's + key_len = data[pos++]; + // TODO: check key_len + std::copy(data + pos, data + pos + key_len, buffer.master_salt.data()); + pos += key_len; + + // sender_key_id : octet[4] + std::copy(data + pos, data + pos + 4, buffer.sender_key_id.data()); + pos += 4; + + // master_sender_key : sequence + // seq_len would always be 0 0 0 n + // TODO: check 0 values + pos += 3; + key_len = data[pos++]; + // TODO: check key_len + std::copy(data + pos, data + pos + key_len, buffer.master_sender_key.data()); + pos += key_len; + + // receiver_specific_key_id : octet[4] + uint8_t has_specific_key = 0; + for (uint8_t i = 0; i < 4; i++) + { + buffer.receiver_specific_key_id[i] = data[pos++]; + has_specific_key |= buffer.receiver_specific_key_id[i]; + } + + if (has_specific_key != 0) + { + // master_receiver_specific_key : sequence + // seq_len would always be 0 0 0 n + // TODO: check 0 values + pos += 3; + key_len = data[pos++]; + // TODO: check key_len + std::copy(data + pos, data + pos + key_len, buffer.master_receiver_specific_key.data()); + } } - return buffer; } +/* std::vector AESGCMGMAC_KeyExchange::aes_128_gcm_encrypt(const std::vector& plaintext, const std::array& key) { @@ -456,3 +566,4 @@ std::vector AESGCMGMAC_KeyExchange::aes_128_gcm_decrypt(const std::vect return plaintext; } +*/ diff --git a/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.h b/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.h index 4e5bbbf28e7..0195d1803bb 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.h +++ b/src/cpp/security/cryptography/AESGCMGMAC_KeyExchange.h @@ -78,11 +78,11 @@ class AESGCMGMAC_KeyExchange : public CryptoKeyExchange //CDR Serialization and Deserialization of KeyMaterials std::vector KeyMaterialCDRSerialize(KeyMaterial_AES_GCM_GMAC &key); - KeyMaterial_AES_GCM_GMAC KeyMaterialCDRDeserialize(std::vector *CDR); + void KeyMaterialCDRDeserialize(KeyMaterial_AES_GCM_GMAC& buffer, std::vector *CDR); //Aux functions to cipher and decipher CryptoTokens - std::vector aes_128_gcm_encrypt(const std::vector& plaintext, const std::array& key); - std::vector aes_128_gcm_decrypt(const std::vector& crypto, const std::array& key); + // std::vector aes_128_gcm_encrypt(const std::vector& plaintext, const std::array& key); + // std::vector aes_128_gcm_decrypt(const std::vector& crypto, const std::array& key); }; diff --git a/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.cpp b/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.cpp index 204ae1cbab8..9ce35a554e7 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.cpp +++ b/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.cpp @@ -39,6 +39,59 @@ #undef max #endif +static bool create_kx_key(std::array& out_data, const std::vector* first_data, + const char* cookie, const std::vector* second_data, const std::vector* shared_secret) +{ + uint8_t tmp_data[32 + 16 + 32]; + uint8_t sha256[32]; + + out_data.fill(0); + + memcpy(tmp_data, first_data->data(), 32); + memcpy(&tmp_data[32], cookie, 16); + memcpy(&tmp_data[32 + 16], second_data->data(), 32); + + if (!EVP_Digest(tmp_data, 32 + 16 + 32, sha256, NULL, EVP_sha256(), NULL)) + { + return false; + } + + //The result of p_master_salt is now the key to perform an HMACsha256 of the shared secret + EVP_PKEY *key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sha256, 32); + EVP_MD_CTX* ctx = +#if IS_OPENSSL_1_1 + EVP_MD_CTX_new(); +#else + (EVP_MD_CTX*)malloc(sizeof(EVP_MD_CTX)); +#endif + EVP_MD_CTX_init(ctx); + EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, key); + EVP_DigestSignUpdate(ctx, shared_secret->data(), shared_secret->size()); + size_t length = 0; + EVP_DigestSignFinal(ctx, NULL, &length); + if (length > 32) + { + EVP_PKEY_free(key); +#if IS_OPENSSL_1_1 + EVP_MD_CTX_free(ctx); +#else + EVP_MD_CTX_cleanup(ctx); + free(ctx); +#endif + return false; + } + EVP_DigestSignFinal(ctx, out_data.data(), &length); + EVP_PKEY_free(key); +#if IS_OPENSSL_1_1 + EVP_MD_CTX_free(ctx); +#else + EVP_MD_CTX_cleanup(ctx); + free(ctx); +#endif + + return true; +} + using namespace eprosima::fastrtps::rtps; using namespace eprosima::fastrtps::rtps::security; @@ -48,6 +101,7 @@ ParticipantCryptoHandle* AESGCMGMAC_KeyFactory::register_local_participant( const IdentityHandle& /*participant_identity*/, const PermissionsHandle& /*participant_permissions*/, const PropertySeq &participant_properties, + const ParticipantSecurityAttributes& participant_security_attributes, SecurityException& /*exception*/) { @@ -55,50 +109,40 @@ ParticipantCryptoHandle* AESGCMGMAC_KeyFactory::register_local_participant( AESGCMGMAC_ParticipantCryptoHandle* PCrypto = nullptr; PCrypto = new AESGCMGMAC_ParticipantCryptoHandle(); + auto plugin_attrs = participant_security_attributes.plugin_participant_attributes; + (*PCrypto)->ParticipantPluginAttributes = plugin_attrs; //Fill ParticipantKeyMaterial - This will be used to cipher full rpts messages - std::array transformationtype{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}; //Default to AES128_GCM if the user does not specify otherwise + //Default to AES128 if the user does not specify otherwise (GCM / GMAC depending of RTPS protection kind) + bool is_rtps_encrypted = (plugin_attrs & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED) != 0; + bool is_origin_auth = (plugin_attrs & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED) != 0; + bool use_256_bits = true; int maxblockspersession = 32; //Default to key update every 32 usages if the user does not specify otherwise if(!participant_properties.empty()){ - for(auto it=participant_properties.begin(); it!=participant_properties.end(); ++it){ - if( (it)->name() == "dds.sec.crypto.cryptotransformkind"){ - if( it->value() == std::string("AES128_GCM") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}; - if( it->value() == std::string("AES128_GMAC") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}; - if( it->value() == std::string("AES256_GCM") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM}; - if( it->value() == std::string("AES256_GMAC") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}; - }// endif - if( (it)->name() == "dds.sec.crypto.maxblockspersession"){ - try{ - maxblockspersession = std::stoi( (it)->value() ); - }catch(std::invalid_argument){} - } - }//endfor + for(auto it=participant_properties.begin(); it!=participant_properties.end(); ++it){ + if( (it)->name().compare("dds.sec.crypto.keysize") == 0) + { + if (it->value().compare("128") == 0) + { + use_256_bits = false; + } + } + if( (it)->name().compare("dds.sec.crypto.maxblockspersession") == 0) + { + try{ + maxblockspersession = std::stoi( (it)->value() ); + }catch(std::invalid_argument){} + } + }//endfor }//endif - (*PCrypto)->ParticipantKeyMaterial.transformation_kind = - transformationtype; - (*PCrypto)->transformation_kind = transformationtype; - (*PCrypto)->ParticipantKeyMaterial.master_salt.fill(0); - RAND_bytes( (*PCrypto)->ParticipantKeyMaterial.master_salt.data(), 16 ); - - (*PCrypto)->ParticipantKeyMaterial.sender_key_id = make_unique_KeyId(); - - (*PCrypto)->ParticipantKeyMaterial.master_sender_key.fill(0); - RAND_bytes( (*PCrypto)->ParticipantKeyMaterial.master_sender_key.data(), 16 ); - - //These values are set by the standard - (*PCrypto)->ParticipantKeyMaterial.receiver_specific_key_id = {{0, 0, 0, 0}}; //No receiver specific, as this is the Master Participant Key - (*PCrypto)->ParticipantKeyMaterial.master_receiver_specific_key = (*PCrypto)->ParticipantKeyMaterial.master_sender_key; + create_key((*PCrypto)->ParticipantKeyMaterial, is_rtps_encrypted, use_256_bits); //Set values related to key update policy (*PCrypto)->max_blocks_per_session = maxblockspersession; (*PCrypto)->session_block_counter = maxblockspersession+1; //Set to update upon first usage - RAND_bytes( (unsigned char *)( &( (*PCrypto)->session_id ) ), sizeof(uint16_t)); + RAND_bytes( (unsigned char *)( &( (*PCrypto)->session_id ) ), sizeof(uint32_t)); // Fill data to use with ourselves. KeyMaterial_AES_GCM_GMAC buffer; //Buffer = Participant2ParticipantKeyMaterial @@ -108,8 +152,16 @@ ParticipantCryptoHandle* AESGCMGMAC_KeyFactory::register_local_participant( buffer.master_salt = (*PCrypto)->ParticipantKeyMaterial.master_salt; buffer.master_sender_key = (*PCrypto)->ParticipantKeyMaterial.master_sender_key; buffer.sender_key_id = (*PCrypto)->ParticipantKeyMaterial.sender_key_id; - buffer.receiver_specific_key_id = (*PCrypto)->ParticipantKeyMaterial.sender_key_id; - buffer.master_receiver_specific_key = (*PCrypto)->ParticipantKeyMaterial.master_receiver_specific_key; + if (is_origin_auth) + { + buffer.receiver_specific_key_id = (*PCrypto)->ParticipantKeyMaterial.sender_key_id; + buffer.master_receiver_specific_key = (*PCrypto)->ParticipantKeyMaterial.master_sender_key; + } + else + { + buffer.receiver_specific_key_id = c_transformKeyIdZero; + buffer.master_receiver_specific_key.fill(0); + } (*PCrypto)->Participant2ParticipantKeyMaterial.push_back(buffer); (*PCrypto)->RemoteParticipant2ParticipantKeyMaterial.push_back(buffer); @@ -139,9 +191,11 @@ ParticipantCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_partici //Put both elements in the local and remote ParticipantCryptoHandle const AESGCMGMAC_ParticipantCryptoHandle& local_participant_handle = AESGCMGMAC_ParticipantCryptoHandle::narrow(local_participant_crypto_handle); + auto plugin_attrs = local_participant_handle->ParticipantPluginAttributes; + bool is_origin_auth = (plugin_attrs & PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED) != 0; AESGCMGMAC_ParticipantCryptoHandle* RPCrypto = new AESGCMGMAC_ParticipantCryptoHandle(); // Remote Participant CryptoHandle, to be returned at the end of the function - (*RPCrypto)->transformation_kind = local_participant_handle->transformation_kind; + (*RPCrypto)->ParticipantPluginAttributes = plugin_attrs; /*Fill values for Participant2ParticipantKeyMaterial - Used to encrypt outgoing data */ { //scope for temp var buffer @@ -151,12 +205,15 @@ ParticipantCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_partici buffer.transformation_kind = local_participant_handle->ParticipantKeyMaterial.transformation_kind; buffer.master_salt = local_participant_handle->ParticipantKeyMaterial.master_salt; buffer.master_sender_key = local_participant_handle->ParticipantKeyMaterial.master_sender_key; + buffer.sender_key_id = local_participant_handle->ParticipantKeyMaterial.sender_key_id; //Generation of remainder values (Remote specific key) - buffer.sender_key_id = make_unique_KeyId(); - buffer.receiver_specific_key_id = make_unique_KeyId(); buffer.master_receiver_specific_key.fill(0); - RAND_bytes( buffer.master_receiver_specific_key.data(), 16 ); - + buffer.receiver_specific_key_id = c_transformKeyIdZero; + if (is_origin_auth) + { + buffer.receiver_specific_key_id = make_unique_KeyId(); + RAND_bytes(buffer.master_receiver_specific_key.data(), 32); + } //Attach to both local and remote CryptoHandles (*RPCrypto)->Participant2ParticipantKeyMaterial.push_back(buffer); } @@ -165,110 +222,27 @@ ParticipantCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_partici { //scope for temp var buffer KeyMaterial_AES_GCM_GMAC buffer; //Buffer = Participant2ParticipantKxKeyMaterial - buffer.transformation_kind = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}; - buffer.master_salt.fill(0); - - std::vector concatenation(challenge_1->size() + 16 + - challenge_2->size()); //Assembly of the source concatenated sequence that is used to generate master_salt - - std::string KxKeyCookie("key exchange key"); - memcpy(concatenation.data(), challenge_1->data(), challenge_1->size()); - memcpy(concatenation.data() + challenge_1->size(), KxKeyCookie.data(), 16); - memcpy(concatenation.data() + challenge_1->size() + 16, challenge_2->data(), challenge_2->size()); + buffer.transformation_kind = c_transfrom_kind_aes256_gcm; + buffer.sender_key_id.fill(0); + buffer.receiver_specific_key_id.fill(0); + buffer.master_receiver_specific_key.fill(0); - //concatenation is used to generate the key to encode the shared_secret and produce the master_salt - buffer.master_salt.fill(0); - std::array p_master_salt; - if(!EVP_Digest(concatenation.data(), challenge_1->size() + 16 + challenge_2->size(), p_master_salt.data(), NULL, EVP_sha256(), NULL)){ - logWarning(SECURITY_CRYPTO,"Error generating the keys to perform token transaction"); - delete RPCrypto; - return nullptr; - } - //The result of p_master_salt is now the key to perform an HMACsha256 of the shared secret - EVP_PKEY *key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, p_master_salt.data(), 32); - EVP_MD_CTX* ctx = -#if IS_OPENSSL_1_1 - EVP_MD_CTX_new(); -#else - (EVP_MD_CTX*)malloc(sizeof(EVP_MD_CTX)); -#endif - EVP_MD_CTX_init(ctx); - EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, key); - EVP_DigestSignUpdate(ctx, shared_secret_ss->data(), shared_secret_ss->size()); - size_t length = 0; - EVP_DigestSignFinal(ctx, NULL, &length); - if(length > 32){ - logWarning(SECURITY_CRYPTO,"Error generating the keys to perform token transaction"); + if (!create_kx_key(buffer.master_salt, challenge_1, "keyexchange salt", challenge_2, shared_secret_ss)) + { + logWarning(SECURITY_CRYPTO, "Error generating the keys to perform token transaction"); exception = SecurityException("Encountered an error while creating KxKeyMaterials"); delete RPCrypto; - EVP_PKEY_free(key); -#if IS_OPENSSL_1_1 - EVP_MD_CTX_free(ctx); -#else - EVP_MD_CTX_cleanup(ctx); - free(ctx); -#endif return nullptr; } - EVP_DigestSignFinal(ctx, buffer.master_salt.data(), &length); - EVP_PKEY_free(key); -#if IS_OPENSSL_1_1 - EVP_MD_CTX_free(ctx); -#else - EVP_MD_CTX_cleanup(ctx); - free(ctx); -#endif - //Repeat process - concatenation is used to store the sequence to generate master_sender_key - std::string KxSaltCookie("keyexchange salt"); - memcpy(concatenation.data(), challenge_2->data(), challenge_2->size()); - memcpy(concatenation.data() + challenge_2->size(), KxSaltCookie.data(), 16); - memcpy(concatenation.data() + challenge_2->size() + 16, challenge_1->data(), challenge_1->size() ); - //Compute key to produce master_sender_key - buffer.master_sender_key.fill(0); - if(!EVP_Digest(concatenation.data(), challenge_1->size() + 16 + challenge_2->size(), p_master_salt.data(), NULL, EVP_sha256(), NULL)){ - logWarning(SECURITY_CRYPTO,"Error generating master key material"); - delete RPCrypto; - return nullptr; - } - //The result of p_master_salt is now the key to perform an HMACsha256 of the shared secret that will go into master_sender_key - key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, p_master_salt.data(), 32); - ctx = -#if IS_OPENSSL_1_1 - EVP_MD_CTX_new(); -#else - (EVP_MD_CTX*)malloc(sizeof(EVP_MD_CTX)); -#endif - EVP_MD_CTX_init(ctx); - - EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, key); - EVP_DigestSignUpdate(ctx, shared_secret_ss->data(), shared_secret_ss->size()); - length = 0; - EVP_DigestSignFinal(ctx, NULL, &length); - if(length > 32){ - logWarning(SECURITY_CRYPTO,"Error generating master key material"); + if(!create_kx_key(buffer.master_sender_key, challenge_2, "key exchange key", challenge_1, shared_secret_ss)) + { + logWarning(SECURITY_CRYPTO, "Error generating the keys to perform token transaction"); + exception = SecurityException("Encountered an error while creating KxKeyMaterials"); delete RPCrypto; - EVP_PKEY_free(key); -#if IS_OPENSSL_1_1 - EVP_MD_CTX_free(ctx); -#else - EVP_MD_CTX_cleanup(ctx); - free(ctx); -#endif return nullptr; } - EVP_DigestSignFinal(ctx, buffer.master_sender_key.data(), &length); - EVP_PKEY_free(key); -#if IS_OPENSSL_1_1 - EVP_MD_CTX_free(ctx); -#else - EVP_MD_CTX_cleanup(ctx); - free(ctx); -#endif - buffer.sender_key_id.fill(0); //Specified by standard - buffer.receiver_specific_key_id.fill(0); //Specified by standard - buffer.master_receiver_specific_key.fill(0); //Specified by standard (*RPCrypto)->max_blocks_per_session = local_participant_handle->max_blocks_per_session; (*RPCrypto)->session_block_counter = local_participant_handle->session_block_counter; @@ -278,6 +252,32 @@ ParticipantCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_partici //Attack to PartipantCryptoHandles - both local and remote (*RPCrypto)->Participant2ParticipantKxKeyMaterial.push_back(buffer); + + // Create builtin key exchange writer handle + AESGCMGMAC_WriterCryptoHandle* wHandle = new AESGCMGMAC_WriterCryptoHandle(); + (*wHandle)->EndpointPluginAttributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + (*wHandle)->Participant_master_key_id = c_transformKeyIdZero; + (*wHandle)->Parent_participant = RPCrypto; + (*wHandle)->EntityKeyMaterial.push_back(buffer); + (*wHandle)->Entity2RemoteKeyMaterial.push_back(buffer); + (*wHandle)->Remote2EntityKeyMaterial.push_back(buffer); + (*wHandle)->Sessions[0].session_id = (*RPCrypto)->session_id; + (*wHandle)->max_blocks_per_session = (*RPCrypto)->max_blocks_per_session; + (*wHandle)->Sessions[0].session_block_counter = (*RPCrypto)->session_block_counter; + (*RPCrypto)->Writers.push_back(wHandle); + + // Create builtin key exchange reader handle + AESGCMGMAC_ReaderCryptoHandle* rHandle = new AESGCMGMAC_ReaderCryptoHandle(); + (*rHandle)->EndpointPluginAttributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + (*rHandle)->Participant_master_key_id = c_transformKeyIdZero; + (*rHandle)->Parent_participant = RPCrypto; + (*rHandle)->EntityKeyMaterial.push_back(buffer); + (*rHandle)->Entity2RemoteKeyMaterial.push_back(buffer); + (*rHandle)->Remote2EntityKeyMaterial.push_back(buffer); + (*rHandle)->Sessions[0].session_id = (*RPCrypto)->session_id; + (*rHandle)->max_blocks_per_session = (*RPCrypto)->max_blocks_per_session; + (*rHandle)->Sessions[0].session_block_counter = (*RPCrypto)->session_block_counter; + (*RPCrypto)->Readers.push_back(rHandle); } return RPCrypto; @@ -286,6 +286,7 @@ ParticipantCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_partici DatawriterCryptoHandle * AESGCMGMAC_KeyFactory::register_local_datawriter( ParticipantCryptoHandle &participant_crypto, const PropertySeq &datawriter_prop, + const EndpointSecurityAttributes& datawriter_security_properties, SecurityException& /*exception*/){ AESGCMGMAC_ParticipantCryptoHandle& participant_handle = AESGCMGMAC_ParticipantCryptoHandle::narrow(participant_crypto); @@ -294,50 +295,74 @@ DatawriterCryptoHandle * AESGCMGMAC_KeyFactory::register_local_datawriter( return nullptr; } - //Create ParticipantCryptoHandle, fill Participant KeyMaterial and return it - AESGCMGMAC_WriterCryptoHandle* WCrypto = new AESGCMGMAC_WriterCryptoHandle(); - - std::array transformationtype{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}; //Default to AES128_GCM + auto plugin_attrs = datawriter_security_properties.plugin_endpoint_attributes; + bool is_sub_encrypted = plugin_attrs & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED; + bool is_payload_encrypted = plugin_attrs & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED; + bool use_256_bits = false; + bool use_kx_keys = false; int maxblockspersession = 32; //Default to key update every 32 usages if(!datawriter_prop.empty()){ for(auto it=datawriter_prop.begin(); it!=datawriter_prop.end(); ++it) { - if( (it)->name() == "dds.sec.crypto.cryptotransformkind") + if(it->name().compare("dds.sec.crypto.keysize") == 0) + { + if (it->value().compare("256") == 0) + { + use_256_bits = true; + } + } + else if(it->name().compare("dds.sec.crypto.maxblockspersession") == 0) { - if(it->value() == std::string("AES128_GCM")) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}; - if(it->value() == std::string("AES128_GMAC")) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}; - if(it->value() == std::string("AES256_GCM")) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM}; - if(it->value() == std::string("AES256_GMAC")) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}; - }// endif - if( (it)->name() == "dds.sec.crypto.maxblockspersession"){ try{ maxblockspersession = std::stoi( (it)->value() ); }catch(std::invalid_argument){} } + else if (it->name().compare("dds.sec.builtin_endpoint_name") == 0) + { + if (it->value().compare("BuiltinParticipantVolatileMessageSecureWriter") == 0) + { + use_kx_keys = true; + } + } }//endfor }//endif - (*WCrypto)->transformation_kind = transformationtype; - //Fill WriterKeyMaterial - This will be used to cipher full rpts messages - (*WCrypto)->EntityKeyMaterial.transformation_kind = transformationtype; - (*WCrypto)->EntityKeyMaterial.master_salt.fill(0); - RAND_bytes( (*WCrypto)->EntityKeyMaterial.master_salt.data(), 16 ); + if (use_kx_keys) + { + return participant_handle->Writers.at(0); + } - (*WCrypto)->EntityKeyMaterial.sender_key_id = make_unique_KeyId(); + //Create ParticipantCryptoHandle, fill Participant KeyMaterial and return it + AESGCMGMAC_WriterCryptoHandle* WCrypto = new AESGCMGMAC_WriterCryptoHandle(); + (*WCrypto)->EndpointPluginAttributes = plugin_attrs; - (*WCrypto)->EntityKeyMaterial.master_sender_key.fill(0); - RAND_bytes( (*WCrypto)->EntityKeyMaterial.master_sender_key.data(), 16 ); + auto session = &(*WCrypto)->Sessions[0]; - (*WCrypto)->EntityKeyMaterial.receiver_specific_key_id = {{0, 0, 0, 0}}; //No receiver specific, as this is the Master Participant Key - (*WCrypto)->EntityKeyMaterial.master_receiver_specific_key.fill(0); + if (datawriter_security_properties.is_submessage_protected) + { + KeyMaterial_AES_GCM_GMAC buffer; + create_key(buffer, is_sub_encrypted, use_256_bits); + (*WCrypto)->EntityKeyMaterial.push_back(buffer); + session->session_block_counter = maxblockspersession + 1; //Set to update upon first usage + RAND_bytes((unsigned char *)(&(session->session_id)), sizeof(uint32_t)); + session++; + } + if (datawriter_security_properties.is_payload_protected) + { + // TODO: let user decide on key reuse + if (!datawriter_security_properties.is_submessage_protected || + (is_payload_encrypted != is_sub_encrypted) ) + { + KeyMaterial_AES_GCM_GMAC buffer; + create_key(buffer, is_payload_encrypted, use_256_bits); + (*WCrypto)->EntityKeyMaterial.push_back(buffer); + session->session_block_counter = maxblockspersession + 1; //Set to update upon first usage + RAND_bytes((unsigned char *)(&(session->session_id)), sizeof(uint32_t)); + } + } + (*WCrypto)->max_blocks_per_session = maxblockspersession; - (*WCrypto)->session_block_counter = maxblockspersession+1; //Set to update upon first usage - RAND_bytes( (unsigned char *)( &( (*WCrypto)->session_id ) ), sizeof(uint16_t)); std::unique_lock(participant_handle->mutex_); @@ -354,7 +379,7 @@ DatareaderCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_dataread DatawriterCryptoHandle &local_datawriter_crypto_handle, ParticipantCryptoHandle &remote_participant_crypto, const SharedSecretHandle& /*shared_secret*/, - const bool /*relay_only*/, + const bool relay_only, SecurityException& /*exception*/) { //Create Participant2ParticipantKeyMaterial (Based on local ParticipantKeyMaterial) and ParticipantKxKeyMaterial (based on the SharedSecret) @@ -366,47 +391,84 @@ DatareaderCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_dataread return nullptr; } - std::unique_lock writer_lock(local_writer_handle->mutex_); + AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypto); + std::unique_lock writer_lock(local_writer_handle->mutex_); + auto plugin_attrs = local_writer_handle->EndpointPluginAttributes; + bool is_origin_auth = (plugin_attrs & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED) != 0; AESGCMGMAC_ReaderCryptoHandle* RRCrypto = new AESGCMGMAC_ReaderCryptoHandle(); // Remote Reader CryptoHandle, to be returned at the end of the function - (*RRCrypto)->transformation_kind = local_writer_handle->transformation_kind; - + (*RRCrypto)->EndpointPluginAttributes = plugin_attrs; (*RRCrypto)->Participant_master_key_id = local_writer_handle->Participant_master_key_id; - /*Fill values for Writer2ReaderKeyMaterial - Used to encrypt outgoing data */ - { //scope for temp var buffer + + if (local_writer_handle->EntityKeyMaterial.size() == 0) + { + // This means the local writer is a key exchange writer + (*RRCrypto)->Remote2EntityKeyMaterial.push_back(remote_participant->Participant2ParticipantKxKeyMaterial.at(0)); + (*RRCrypto)->Entity2RemoteKeyMaterial.push_back(remote_participant->Participant2ParticipantKxKeyMaterial.at(0)); + } + else + { + /*Fill values for Writer2ReaderKeyMaterial - Used to encrypt outgoing data */ KeyMaterial_AES_GCM_GMAC buffer; //Buffer = Writer2ReaderKeyMaterial //These values must match the ones in ParticipantKeymaterial - buffer.transformation_kind = local_writer_handle->EntityKeyMaterial.transformation_kind; - buffer.master_salt = local_writer_handle->EntityKeyMaterial.master_salt; - buffer.master_sender_key = local_writer_handle->EntityKeyMaterial.master_sender_key; + buffer.transformation_kind = local_writer_handle->EntityKeyMaterial.at(0).transformation_kind; + buffer.master_salt = local_writer_handle->EntityKeyMaterial.at(0).master_salt; + buffer.master_sender_key = local_writer_handle->EntityKeyMaterial.at(0).master_sender_key; - buffer.sender_key_id = local_writer_handle->EntityKeyMaterial.sender_key_id; - //buffer.sender_key_id = make_unique_KeyId(); //Unique identifier within the Participant (used to identity submessage types) + buffer.sender_key_id = local_writer_handle->EntityKeyMaterial.at(0).sender_key_id; //Generation of remainder values (Remote specific key) - buffer.receiver_specific_key_id = make_unique_KeyId(); buffer.master_receiver_specific_key.fill(0); - RAND_bytes( buffer.master_receiver_specific_key.data(), 16 ); + buffer.receiver_specific_key_id = c_transformKeyIdZero; + if (is_origin_auth) + { + buffer.receiver_specific_key_id = make_unique_KeyId(); + RAND_bytes(buffer.master_receiver_specific_key.data(), 16); + } //Attach to both local and remote CryptoHandles (*RRCrypto)->Remote2EntityKeyMaterial.push_back(buffer); - local_writer_handle->Entity2RemoteKeyMaterial.push_back(buffer); + if (is_origin_auth) + { + local_writer_handle->Entity2RemoteKeyMaterial.push_back(buffer); + } + } + + auto session = &(*RRCrypto)->Sessions[0]; + session->session_block_counter = local_writer_handle->Sessions[0].session_block_counter; + session->session_id = std::numeric_limits::max(); + if (session->session_id == local_writer_handle->Sessions[0].session_id) + session->session_id -= 1; + + if (!relay_only && local_writer_handle->EntityKeyMaterial.size() > 1) + { + KeyMaterial_AES_GCM_GMAC buffer; //Buffer = Writer2ReaderKeyMaterial + + buffer.transformation_kind = local_writer_handle->EntityKeyMaterial.at(1).transformation_kind; + buffer.master_salt = local_writer_handle->EntityKeyMaterial.at(1).master_salt; + buffer.master_sender_key = local_writer_handle->EntityKeyMaterial.at(1).master_sender_key; + buffer.sender_key_id = local_writer_handle->EntityKeyMaterial.at(1).sender_key_id; + buffer.master_receiver_specific_key.fill(0); + buffer.receiver_specific_key_id = c_transformKeyIdZero; + + //Attach only to remote CryptoHandles + (*RRCrypto)->Remote2EntityKeyMaterial.push_back(buffer); + + session++; + session->session_block_counter = local_writer_handle->Sessions[0].session_block_counter; + session->session_id = std::numeric_limits::max(); + if (session->session_id == local_writer_handle->Sessions[0].session_id) + session->session_id -= 1; } (*RRCrypto)->max_blocks_per_session = local_writer_handle->max_blocks_per_session; - (*RRCrypto)->session_block_counter = local_writer_handle->session_block_counter; - (*RRCrypto)->session_id = std::numeric_limits::max(); - if((*RRCrypto)->session_id == local_writer_handle->session_id) - (*RRCrypto)->session_id -= 1; writer_lock.unlock(); - AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypto); - std::unique_lock remote_participant_lock(remote_participant->mutex_); - (*RRCrypto)->Participant2ParticipantKxKeyMaterial = remote_participant->Participant2ParticipantKxKeyMaterial.at(0); + // (*RRCrypto)->Participant2ParticipantKxKeyMaterial = remote_participant->Participant2ParticipantKxKeyMaterial.at(0); (*RRCrypto)->Parent_participant = &remote_participant_crypto; //Save this CryptoHandle as part of the remote participant @@ -419,6 +481,7 @@ DatareaderCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_dataread DatareaderCryptoHandle * AESGCMGMAC_KeyFactory::register_local_datareader( ParticipantCryptoHandle &participant_crypto, const PropertySeq &datareader_properties, + const EndpointSecurityAttributes& datareder_security_attributes, SecurityException& /*exception*/) { AESGCMGMAC_ParticipantCryptoHandle& participant_handle = AESGCMGMAC_ParticipantCryptoHandle::narrow(participant_crypto); @@ -430,49 +493,58 @@ DatareaderCryptoHandle * AESGCMGMAC_KeyFactory::register_local_datareader( //Create ParticipantCryptoHandle, fill Participant KeyMaterial and return it AESGCMGMAC_ReaderCryptoHandle* RCrypto = nullptr; - RCrypto = new AESGCMGMAC_ReaderCryptoHandle(); - - std::array transformationtype{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}; //Default to AES128_GCM + auto plugin_attrs = datareder_security_attributes.plugin_endpoint_attributes; + bool is_sub_encrypted = (plugin_attrs & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED) != 0; + bool use_256_bits = false; + bool use_kx_keys = false; int maxblockspersession = 32; //Default to key update every 32 usages if(!datareader_properties.empty()){ - for(auto it=datareader_properties.begin(); it!=datareader_properties.end(); ++it){ - if( (it)->name() == "dds.sec.crypto.cryptotransformkind"){ - if( it->value() == std::string("AES128_GCM") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}; - if( it->value() == std::string("AES128_GMAC") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}; - if( it->value() == std::string("AES256_GCM") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM}; - if( it->value() == std::string("AES256_GMAC") ) - transformationtype = std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}; - }// endif - if( (it)->name() == "dds.sec.crypto.maxblockspersession"){ - try{ - maxblockspersession = std::stoi( (it)->value() ); - }catch(std::invalid_argument){} - } - }//endfor + for(auto it=datareader_properties.begin(); it!=datareader_properties.end(); ++it){ + if (it->name().compare("dds.sec.crypto.keysize") == 0) + { + if (it->value().compare("256") == 0) + { + use_256_bits = true; + } + } + else if (it->name().compare("dds.sec.crypto.maxblockspersession") == 0) + { + try + { + maxblockspersession = std::stoi((it)->value()); + } + catch (std::invalid_argument) + { + } + } + else if (it->name().compare("dds.sec.builtin_endpoint_name") == 0) + { + if (it->value().compare("BuiltinParticipantVolatileMessageSecureReader") == 0) + { + use_kx_keys = true; + } + } + }//endfor }//endif - (*RCrypto)->transformation_kind = transformationtype; - //Fill ParticipantKeyMaterial - This will be used to cipher full rpts messages - - (*RCrypto)->EntityKeyMaterial.transformation_kind = transformationtype; - - (*RCrypto)->EntityKeyMaterial.master_salt.fill(0); - RAND_bytes( (*RCrypto)->EntityKeyMaterial.master_salt.data(), 16 ); - - (*RCrypto)->EntityKeyMaterial.sender_key_id = make_unique_KeyId(); + if (use_kx_keys) + { + return participant_handle->Readers.at(0); + } - (*RCrypto)->EntityKeyMaterial.master_sender_key.fill(0); - RAND_bytes( (*RCrypto)->EntityKeyMaterial.master_sender_key.data(), 16 ); + RCrypto = new AESGCMGMAC_ReaderCryptoHandle(); + (*RCrypto)->EndpointPluginAttributes = plugin_attrs; - (*RCrypto)->EntityKeyMaterial.receiver_specific_key_id = {{0, 0, 0, 0}}; //No receiver specific, as this is the Master Participant Key - (*RCrypto)->EntityKeyMaterial.master_receiver_specific_key.fill(0); + { + //Fill ParticipantKeyMaterial - This will be used to cipher full rpts messages + KeyMaterial_AES_GCM_GMAC buffer; + create_key(buffer, is_sub_encrypted, use_256_bits); + (*RCrypto)->EntityKeyMaterial.push_back(buffer); + } (*RCrypto)->max_blocks_per_session = maxblockspersession; - (*RCrypto)->session_block_counter = maxblockspersession+1; - RAND_bytes( (unsigned char *)( &( (*RCrypto)->session_id ) ), sizeof(uint16_t)); + (*RCrypto)->Sessions[0].session_block_counter = maxblockspersession+1; + RAND_bytes( (unsigned char *)( &( (*RCrypto)->Sessions[0].session_id ) ), sizeof(uint32_t)); std::unique_lock lock(participant_handle->mutex_); @@ -501,46 +573,62 @@ DatawriterCryptoHandle * AESGCMGMAC_KeyFactory::register_matched_remote_datawrit return nullptr; } + AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypt); + std::unique_lock reader_lock(local_reader_handle->mutex_); + auto plugin_attrs = local_reader_handle->EndpointPluginAttributes; + bool is_origin_auth = (plugin_attrs & PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED) != 0; AESGCMGMAC_WriterCryptoHandle* RWCrypto = new AESGCMGMAC_WriterCryptoHandle(); // Remote Writer CryptoHandle, to be returned at the end of the function (*RWCrypto)->Participant_master_key_id = local_reader_handle->Participant_master_key_id; - (*RWCrypto)->transformation_kind = local_reader_handle->transformation_kind; - /*Fill values for Writer2ReaderKeyMaterial - Used to encrypt outgoing data */ - { //scope for temp var buffer + (*RWCrypto)->EndpointPluginAttributes = local_reader_handle->EndpointPluginAttributes; + + if (local_reader_handle->EntityKeyMaterial.size() == 0) + { + // This means the local reader is a key exchange writer + (*RWCrypto)->Remote2EntityKeyMaterial.push_back(remote_participant->Participant2ParticipantKxKeyMaterial.at(0)); + (*RWCrypto)->Entity2RemoteKeyMaterial.push_back(remote_participant->Participant2ParticipantKxKeyMaterial.at(0)); + } + else + { + /*Fill values for Writer2ReaderKeyMaterial - Used to encrypt outgoing data */ KeyMaterial_AES_GCM_GMAC buffer; //Buffer = Writer2ReaderKeyMaterial //These values must match the ones in ParticipantKeymaterial - buffer.transformation_kind = local_reader_handle->EntityKeyMaterial.transformation_kind; - buffer.master_salt = local_reader_handle->EntityKeyMaterial.master_salt; - buffer.master_sender_key = local_reader_handle->EntityKeyMaterial.master_sender_key; + buffer.transformation_kind = local_reader_handle->EntityKeyMaterial.at(0).transformation_kind; + buffer.master_salt = local_reader_handle->EntityKeyMaterial.at(0).master_salt; + buffer.master_sender_key = local_reader_handle->EntityKeyMaterial.at(0).master_sender_key; + buffer.sender_key_id = local_reader_handle->EntityKeyMaterial.at(0).sender_key_id; //Generation of remainder values (Remote specific key) - - buffer.sender_key_id = local_reader_handle->EntityKeyMaterial.sender_key_id; - //buffer.sender_key_id = make_unique_KeyId(); - buffer.receiver_specific_key_id = make_unique_KeyId(); buffer.master_receiver_specific_key.fill(0); - RAND_bytes( buffer.master_receiver_specific_key.data(), 16 ); + buffer.receiver_specific_key_id = c_transformKeyIdZero; + if (is_origin_auth) + { + buffer.receiver_specific_key_id = make_unique_KeyId(); + RAND_bytes(buffer.master_receiver_specific_key.data(), 16); + } //Attach to both local and remote CryptoHandles (*RWCrypto)->Remote2EntityKeyMaterial.push_back(buffer); - local_reader_handle->Entity2RemoteKeyMaterial.push_back(buffer); + if (is_origin_auth) + { + local_reader_handle->Entity2RemoteKeyMaterial.push_back(buffer); + } } (*RWCrypto)->max_blocks_per_session = local_reader_handle->max_blocks_per_session; - (*RWCrypto)->session_block_counter = local_reader_handle->session_block_counter; - (*RWCrypto)->session_id = std::numeric_limits::max(); - if((*RWCrypto)->session_id == local_reader_handle->session_id) - (*RWCrypto)->session_id -= 1; + auto session = &(*RWCrypto)->Sessions[0]; + session->session_block_counter = local_reader_handle->Sessions[0].session_block_counter; + session->session_id = std::numeric_limits::max(); + if(session->session_id == local_reader_handle->Sessions[0].session_id) + session->session_id -= 1; reader_lock.unlock(); - AESGCMGMAC_ParticipantCryptoHandle& remote_participant = AESGCMGMAC_ParticipantCryptoHandle::narrow(remote_participant_crypt); - std::unique_lock remote_participant_lock(remote_participant->mutex_); - (*RWCrypto)->Participant2ParticipantKxKeyMaterial = remote_participant->Participant2ParticipantKxKeyMaterial.at(0); + // (*RWCrypto)->Participant2ParticipantKxKeyMaterial = remote_participant->Participant2ParticipantKxKeyMaterial.at(0); (*RWCrypto)->Parent_participant = &remote_participant_crypt; @@ -668,6 +756,31 @@ bool AESGCMGMAC_KeyFactory::unregister_datareader( return false; } +void AESGCMGMAC_KeyFactory::create_key(KeyMaterial_AES_GCM_GMAC& key, bool encrypt_then_sign, bool use_256_bits) +{ + std::array transformationtype = encrypt_then_sign + ? use_256_bits + ? c_transfrom_kind_aes256_gcm + : c_transfrom_kind_aes128_gcm + : use_256_bits + ? c_transfrom_kind_aes256_gmac + : c_transfrom_kind_aes128_gmac; + + int nBytes = use_256_bits ? 32 : 16; + + key.transformation_kind = transformationtype; + + key.master_salt.fill(0); + RAND_bytes(key.master_salt.data(), nBytes); + + key.sender_key_id = make_unique_KeyId(); + key.master_sender_key.fill(0); + RAND_bytes(key.master_sender_key.data(), nBytes); + + key.receiver_specific_key_id = c_transformKeyIdZero; + key.master_receiver_specific_key.fill(0); +} + CryptoTransformKeyId AESGCMGMAC_KeyFactory::make_unique_KeyId(){ CryptoTransformKeyId buffer{{0, 0, 0, 0}}; bool unique = false; diff --git a/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.h b/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.h index 654188bf5be..22dcb277a40 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.h +++ b/src/cpp/security/cryptography/AESGCMGMAC_KeyFactory.h @@ -31,59 +31,67 @@ namespace security { class AESGCMGMAC_KeyFactory : public CryptoKeyFactory { - public: - - AESGCMGMAC_KeyFactory(); - - ParticipantCryptoHandle * register_local_participant( - const IdentityHandle &participant_identity, - const PermissionsHandle &participant_permissions, - const PropertySeq &participant_properties, - SecurityException &exception) override; - - ParticipantCryptoHandle * register_matched_remote_participant( - const ParticipantCryptoHandle& local_participant_crypto_handle, - const IdentityHandle& remote_participant_identity, - const PermissionsHandle& remote_participant_permissions, - const SharedSecretHandle& shared_secret, - SecurityException &exception) override; - - DatawriterCryptoHandle * register_local_datawriter( - ParticipantCryptoHandle &participant_crypto, - const PropertySeq &datawriter_prop, - SecurityException &exception) override; - - DatareaderCryptoHandle * register_matched_remote_datareader( - DatawriterCryptoHandle &local_datawriter_crypto_handle, - ParticipantCryptoHandle &remote_participant_crypto, - const SharedSecretHandle &shared_secret, - const bool relay_only, - SecurityException &exception) override; - - DatareaderCryptoHandle * register_local_datareader( - ParticipantCryptoHandle &participant_crypto, - const PropertySeq &datareader_properties, - SecurityException &exception) override; - - DatawriterCryptoHandle * register_matched_remote_datawriter( - DatareaderCryptoHandle &local_datareader_crypto_handle, - ParticipantCryptoHandle &remote_participant_crypt, - const SharedSecretHandle &shared_secret, - SecurityException &exception) override; - - bool unregister_participant( - ParticipantCryptoHandle* participant_crypto_handle, - SecurityException &exception) override; - - bool unregister_datawriter( - DatawriterCryptoHandle *datawriter_crypto_handle, - SecurityException &exception) override; - - bool unregister_datareader( - DatareaderCryptoHandle *datareader_crypto_handle, - SecurityException &exception) override; - - private: +public: + + AESGCMGMAC_KeyFactory(); + + ParticipantCryptoHandle * register_local_participant( + const IdentityHandle &participant_identity, + const PermissionsHandle &participant_permissions, + const PropertySeq &participant_properties, + const ParticipantSecurityAttributes &participant_security_attributes, + SecurityException &exception) override; + + ParticipantCryptoHandle * register_matched_remote_participant( + const ParticipantCryptoHandle& local_participant_crypto_handle, + const IdentityHandle& remote_participant_identity, + const PermissionsHandle& remote_participant_permissions, + const SharedSecretHandle& shared_secret, + SecurityException &exception) override; + + DatawriterCryptoHandle * register_local_datawriter( + ParticipantCryptoHandle &participant_crypto, + const PropertySeq &datawriter_prop, + const EndpointSecurityAttributes &datawriter_security_properties, + SecurityException &exception) override; + + DatareaderCryptoHandle * register_matched_remote_datareader( + DatawriterCryptoHandle &local_datawriter_crypto_handle, + ParticipantCryptoHandle &remote_participant_crypto, + const SharedSecretHandle &shared_secret, + const bool relay_only, + SecurityException &exception) override; + + DatareaderCryptoHandle * register_local_datareader( + ParticipantCryptoHandle &participant_crypto, + const PropertySeq &datareader_properties, + const EndpointSecurityAttributes &datareader_security_properties, + SecurityException &exception) override; + + DatawriterCryptoHandle * register_matched_remote_datawriter( + DatareaderCryptoHandle &local_datareader_crypto_handle, + ParticipantCryptoHandle &remote_participant_crypt, + const SharedSecretHandle &shared_secret, + SecurityException &exception) override; + + bool unregister_participant( + ParticipantCryptoHandle* participant_crypto_handle, + SecurityException &exception) override; + + bool unregister_datawriter( + DatawriterCryptoHandle *datawriter_crypto_handle, + SecurityException &exception) override; + + bool unregister_datareader( + DatareaderCryptoHandle *datareader_crypto_handle, + SecurityException &exception) override; + +private: + /* + * Create a new key material without receiver specific key + */ + void create_key(KeyMaterial_AES_GCM_GMAC& key, bool encrypt_then_sign, bool use_256_bits); + /* * make_unique_KeyId(); * Generates an unique, unused CryptoTransformKeyId within the cryptographic domain diff --git a/src/cpp/security/cryptography/AESGCMGMAC_Transform.cpp b/src/cpp/security/cryptography/AESGCMGMAC_Transform.cpp index 79e9857ff6e..fbe467e30be 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_Transform.cpp +++ b/src/cpp/security/cryptography/AESGCMGMAC_Transform.cpp @@ -26,6 +26,12 @@ #include #include +#if OPENSSL_VERSION_NUMBER >= 0x10100000L +#define IS_OPENSSL_1_1 1 +#else +#define IS_OPENSSL_1_1 0 +#endif + // Solve error with Win32 macro #ifdef WIN32 #undef max @@ -36,6 +42,23 @@ using namespace eprosima::fastrtps::rtps::security; CONSTEXPR int initialization_vector_suffix_length = 8; +static KeyMaterial_AES_GCM_GMAC* find_key(KeyMaterial_AES_GCM_GMAC_Seq& keys, const CryptoTransformIdentifier& id) +{ + for (auto& it : keys) + { + if (it.transformation_kind == id.transformation_kind) + { + if ((it.sender_key_id == id.transformation_key_id) || + (it.receiver_specific_key_id == id.transformation_key_id)) + { + return ⁢ + } + } + } + + return nullptr; +} + AESGCMGMAC_Transform::AESGCMGMAC_Transform() { } @@ -69,35 +92,38 @@ bool AESGCMGMAC_Transform::encode_serialized_payload( std::unique_lock lock(local_writer->mutex_); + // Payload is always protected by the last key + auto nKeys = local_writer->EntityKeyMaterial.size(); + auto& keyMat = local_writer->EntityKeyMaterial.at(nKeys - 1); + auto session = &local_writer->Sessions[nKeys - 1]; + //If the maximum number of blocks have been processed, generate a new SessionKey - if(local_writer->session_block_counter >= local_writer->max_blocks_per_session) + if(session->session_block_counter >= local_writer->max_blocks_per_session) { - local_writer->session_id += 1; + session->session_id += 1; - local_writer->SessionKey = compute_sessionkey(local_writer->EntityKeyMaterial.master_sender_key, - local_writer->EntityKeyMaterial.master_salt, - local_writer->session_id); + compute_sessionkey(session->SessionKey, keyMat, session->session_id); //ReceiverSpecific keys shall be computed specifically when needed - local_writer->session_block_counter = 0; + session->session_block_counter = 0; } //In any case, increment session block counter - local_writer->session_block_counter += 1; + session->session_block_counter += 1; //Build NONCE elements (Build once, use once) std::array initialization_vector_suffix; //iv suffix changes with every operation RAND_bytes(initialization_vector_suffix.data(), initialization_vector_suffix_length); std::array initialization_vector; //96 bytes, session_id + suffix - memcpy(initialization_vector.data(),&(local_writer->session_id),4); + memcpy(initialization_vector.data(),&(session->session_id),4); memcpy(initialization_vector.data() + 4, initialization_vector_suffix.data(), 8); std::array session_id; - memcpy(session_id.data(), &(local_writer->session_id), 4); + memcpy(session_id.data(), &(session->session_id), 4); //Header try { - serialize_SecureDataHeader(serializer, local_writer->EntityKeyMaterial.transformation_kind, - local_writer->EntityKeyMaterial.sender_key_id, session_id, initialization_vector_suffix); + serialize_SecureDataHeader(serializer, keyMat.transformation_kind, + keyMat.sender_key_id, session_id, initialization_vector_suffix); } catch(eprosima::fastcdr::exception::NotEnoughMemoryException&) { @@ -110,8 +136,8 @@ bool AESGCMGMAC_Transform::encode_serialized_payload( // Body try { - if(!serialize_SecureDataBody(serializer, local_writer->transformation_kind, local_writer->SessionKey, - initialization_vector, output_buffer, payload.data, payload.length, tag)) + if(!serialize_SecureDataBody(serializer, keyMat.transformation_kind, session->SessionKey, + initialization_vector, output_buffer, payload.data, payload.length, tag, false)) { return false; } @@ -125,8 +151,8 @@ bool AESGCMGMAC_Transform::encode_serialized_payload( try { std::vector receiving_datareader_crypto_list; - if(!serialize_SecureDataTag(serializer, local_writer->transformation_kind, local_writer->session_id, - initialization_vector, receiving_datareader_crypto_list, false, tag)) + if(!serialize_SecureDataTag(serializer, keyMat.transformation_kind, session->session_id, + initialization_vector, receiving_datareader_crypto_list, false, tag, nKeys - 1)) { return false; } @@ -169,30 +195,32 @@ bool AESGCMGMAC_Transform::encode_datawriter_submessage( std::unique_lock lock(local_writer->mutex_); + // Submessage is always protected by the first key + auto& keyMat = local_writer->EntityKeyMaterial.at(0); + auto session = &local_writer->Sessions[0]; + bool update_specific_keys = false; //If the maximum number of blocks have been processed, generate a new SessionKey - if(local_writer->session_block_counter >= local_writer->max_blocks_per_session) + if(session->session_block_counter >= local_writer->max_blocks_per_session) { - local_writer->session_id += 1; + session->session_id += 1; update_specific_keys = true; - local_writer->SessionKey = compute_sessionkey(local_writer->EntityKeyMaterial.master_sender_key, - local_writer->EntityKeyMaterial.master_salt, - local_writer->session_id); + compute_sessionkey(session->SessionKey, keyMat, session->session_id); //ReceiverSpecific keys shall be computed specifically when needed - local_writer->session_block_counter = 0; + session->session_block_counter = 0; } - local_writer->session_block_counter += 1; + session->session_block_counter += 1; //Build remaining NONCE elements std::array initialization_vector_suffix; //iv suffix changes with every operation RAND_bytes(initialization_vector_suffix.data(), initialization_vector_suffix_length); std::array initialization_vector; //96 bytes, session_id + suffix - memcpy(initialization_vector.data(),&(local_writer->session_id),4); + memcpy(initialization_vector.data(),&(session->session_id),4); memcpy(initialization_vector.data() + 4, initialization_vector_suffix.data(), 8); std::array session_id; - memcpy(session_id.data(), &(local_writer->session_id), 4); + memcpy(session_id.data(), &(session->session_id), 4); #if __BIG_ENDIAN__ octet flags = 0x0; @@ -212,8 +240,8 @@ bool AESGCMGMAC_Transform::encode_datawriter_submessage( const char* length_position = serializer.getCurrentPosition(); - serialize_SecureDataHeader(serializer, local_writer->EntityKeyMaterial.transformation_kind, - local_writer->EntityKeyMaterial.sender_key_id, session_id, initialization_vector_suffix); + serialize_SecureDataHeader(serializer, keyMat.transformation_kind, + keyMat.sender_key_id, session_id, initialization_vector_suffix); eprosima::fastcdr::Cdr::state current_state = serializer.getState(); //TODO(Ricardo) fastcdr functinality: length substracting two Cdr::state. @@ -233,9 +261,9 @@ bool AESGCMGMAC_Transform::encode_datawriter_submessage( // Body try { - if(!serialize_SecureDataBody(serializer, local_writer->transformation_kind, local_writer->SessionKey, + if(!serialize_SecureDataBody(serializer, keyMat.transformation_kind, session->SessionKey, initialization_vector, output_buffer, &plain_rtps_submessage.buffer[plain_rtps_submessage.pos], - plain_rtps_submessage.length - plain_rtps_submessage.pos, tag)) + plain_rtps_submessage.length - plain_rtps_submessage.pos, tag, true)) { return false; } @@ -256,8 +284,8 @@ bool AESGCMGMAC_Transform::encode_datawriter_submessage( const char* length_position = serializer.getCurrentPosition(); - if(!serialize_SecureDataTag(serializer, local_writer->transformation_kind, local_writer->session_id, - initialization_vector, receiving_datareader_crypto_list, update_specific_keys, tag)) + if(!serialize_SecureDataTag(serializer, keyMat.transformation_kind, session->session_id, + initialization_vector, receiving_datareader_crypto_list, update_specific_keys, tag, 0)) { return false; } @@ -308,28 +336,28 @@ bool AESGCMGMAC_Transform::encode_datareader_submessage( std::unique_lock lock(local_reader->mutex_); //Step 2 - If the maximum number of blocks have been processed, generate a new SessionKey + auto session = &local_reader->Sessions[0]; bool update_specific_keys = false; - if(local_reader->session_block_counter >= local_reader->max_blocks_per_session){ - local_reader->session_id += 1; + if(session->session_block_counter >= local_reader->max_blocks_per_session){ + session->session_id += 1; update_specific_keys = true; - local_reader->SessionKey = compute_sessionkey(local_reader->EntityKeyMaterial.master_sender_key, - local_reader->EntityKeyMaterial.master_salt, - local_reader->session_id); + compute_sessionkey(session->SessionKey, local_reader->EntityKeyMaterial.at(0), + session->session_id); //ReceiverSpecific keys shall be computed specifically when needed - local_reader->session_block_counter = 0; + session->session_block_counter = 0; } - local_reader->session_block_counter += 1; + session->session_block_counter += 1; //Build remaining NONCE elements std::array initialization_vector_suffix; //iv suffix changes with every operation RAND_bytes(initialization_vector_suffix.data(), initialization_vector_suffix_length); std::array initialization_vector; //96 bytes, session_id + suffix - memcpy(initialization_vector.data(),&(local_reader->session_id),4); + memcpy(initialization_vector.data(),&(session->session_id),4); memcpy(initialization_vector.data() + 4, initialization_vector_suffix.data(), 8); std::array session_id; - memcpy(session_id.data(), &(local_reader->session_id), 4); + memcpy(session_id.data(), &(session->session_id), 4); #if __BIG_ENDIAN__ octet flags = 0x0; @@ -349,8 +377,8 @@ bool AESGCMGMAC_Transform::encode_datareader_submessage( const char* length_position = serializer.getCurrentPosition(); - serialize_SecureDataHeader(serializer, local_reader->EntityKeyMaterial.transformation_kind, - local_reader->EntityKeyMaterial.sender_key_id, session_id, initialization_vector_suffix); + serialize_SecureDataHeader(serializer, local_reader->EntityKeyMaterial.at(0).transformation_kind, + local_reader->EntityKeyMaterial.at(0).sender_key_id, session_id, initialization_vector_suffix); eprosima::fastcdr::Cdr::state current_state = serializer.getState(); //TODO(Ricardo) fastcdr functinality: length substracting two Cdr::state. @@ -370,9 +398,9 @@ bool AESGCMGMAC_Transform::encode_datareader_submessage( // Body try { - if(!serialize_SecureDataBody(serializer, local_reader->transformation_kind, local_reader->SessionKey, + if(!serialize_SecureDataBody(serializer, local_reader->EntityKeyMaterial.at(0).transformation_kind, session->SessionKey, initialization_vector, output_buffer, &plain_rtps_submessage.buffer[plain_rtps_submessage.pos], - plain_rtps_submessage.length - plain_rtps_submessage.pos, tag)) + plain_rtps_submessage.length - plain_rtps_submessage.pos, tag, true)) { return false; } @@ -393,8 +421,8 @@ bool AESGCMGMAC_Transform::encode_datareader_submessage( const char* length_position = serializer.getCurrentPosition(); - if(!serialize_SecureDataTag(serializer, local_reader->transformation_kind, local_reader->session_id, - initialization_vector, receiving_datawriter_crypto_list, update_specific_keys, tag)) + if(!serialize_SecureDataTag(serializer, local_reader->EntityKeyMaterial.at(0).transformation_kind, session->session_id, + initialization_vector, receiving_datawriter_crypto_list, update_specific_keys, tag, 0)) { return false; } @@ -451,8 +479,7 @@ bool AESGCMGMAC_Transform::encode_rtps_message( { local_participant->session_id += 1; update_specific_keys = true; - local_participant->SessionKey = compute_sessionkey(local_participant->ParticipantKeyMaterial.master_sender_key, - local_participant->ParticipantKeyMaterial.master_salt, + compute_sessionkey(local_participant->SessionKey, local_participant->ParticipantKeyMaterial, local_participant->session_id); //ReceiverSpecific keys shall be computed specifically when needed @@ -510,9 +537,9 @@ bool AESGCMGMAC_Transform::encode_rtps_message( // Body try { - if(!serialize_SecureDataBody(serializer, local_participant->transformation_kind, local_participant->SessionKey, + if(!serialize_SecureDataBody(serializer, local_participant->ParticipantKeyMaterial.transformation_kind, local_participant->SessionKey, initialization_vector, output_buffer, &plain_rtps_message.buffer[plain_rtps_message.pos], - plain_rtps_message.length - plain_rtps_message.pos, tag)) + plain_rtps_message.length - plain_rtps_message.pos, tag, true)) { return false; } @@ -641,9 +668,9 @@ bool AESGCMGMAC_Transform::decode_rtps_message( memcpy(&session_id, header.session_id.data(), 4); //Sessionkey - std::array session_key = compute_sessionkey( - sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).master_sender_key, - sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).master_salt, + std::array session_key; + compute_sessionkey(session_key, + sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0), session_id); //IV std::array initialization_vector; @@ -652,13 +679,12 @@ bool AESGCMGMAC_Transform::decode_rtps_message( // Body uint32_t body_length = 0, body_align = 0; + eprosima::fastcdr::Cdr::state protected_body_state = decoder.getState(); + bool is_encrypted = false; try - { if(!predeserialize_SecureDataBody(decoder, body_length, body_align)) - { - logError(SECURITY_CRYPTO, "Error deserializing SecureDataBody header"); - return false; - } + { + is_encrypted = predeserialize_SecureDataBody(decoder, body_length, body_align); } catch(eprosima::fastcdr::exception::NotEnoughMemoryException&) { @@ -699,7 +725,7 @@ bool AESGCMGMAC_Transform::decode_rtps_message( SecurityException exception; - if(!deserialize_SecureDataTag(decoder, tag, sending_participant->transformation_kind, + if(!deserialize_SecureDataTag(decoder, tag, sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).transformation_kind, sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).receiver_specific_key_id, sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).master_receiver_specific_key, sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).master_salt, @@ -721,9 +747,11 @@ bool AESGCMGMAC_Transform::decode_rtps_message( } uint32_t length = plain_buffer.max_size - plain_buffer.pos; - if(!deserialize_SecureDataBody(decoder, body_state, tag, body_length, - sending_participant->transformation_kind, session_key, initialization_vector, - &plain_buffer.buffer[plain_buffer.pos], length)) + if(!deserialize_SecureDataBody(decoder, is_encrypted ? body_state : protected_body_state, tag, + is_encrypted ? body_length : body_length + 4, + sending_participant->RemoteParticipant2ParticipantKeyMaterial.at(0).transformation_kind, + session_key, initialization_vector, + &plain_buffer.buffer[plain_buffer.pos], length)) { logError(SECURITY_CRYPTO, "Error decoding content"); return false; @@ -803,6 +831,9 @@ bool AESGCMGMAC_Transform::preprocess_secure_submsg( return false; } + bool is_key_id_zero = (header.transform_identifier.transformation_key_id == c_transformKeyIdZero); + auto& key_id = header.transform_identifier.transformation_key_id; + //TODO(Ricardo) Deserializing header two times, here preprocessing and decoding submessage. //KeyId is present in Header->transform_identifier->transformation_key_id and contains the sender_key_id @@ -810,75 +841,88 @@ bool AESGCMGMAC_Transform::preprocess_secure_submsg( it != remote_participant->Writers.end(); ++it) { AESGCMGMAC_WriterCryptoHandle& writer = AESGCMGMAC_WriterCryptoHandle::narrow(**it); + auto& wKeyMats = writer->Entity2RemoteKeyMaterial; - if(writer->Entity2RemoteKeyMaterial.size() == 0) + if (wKeyMats.size() == 0) { logWarning(SECURITY_CRYPTO, "No key material yet"); continue; } - if(writer->Entity2RemoteKeyMaterial.at(0).sender_key_id == header.transform_identifier.transformation_key_id) + if (wKeyMats.at(0).sender_key_id == key_id) { + // Remote writer found secure_submessage_category = DATAWRITER_SUBMESSAGE; *datawriter_crypto = *it; + //We have the remote writer, now lets look for the local datareader - for(std::vector::iterator itt = local_participant->Readers.begin(); itt != local_participant->Readers.end(); ++itt) + AESGCMGMAC_ParticipantCryptoHandle& lookup_participant = is_key_id_zero ? remote_participant : local_participant; + for (std::vector::iterator itt = lookup_participant->Readers.begin(); itt != lookup_participant->Readers.end(); ++itt) { AESGCMGMAC_ReaderCryptoHandle& reader = AESGCMGMAC_ReaderCryptoHandle::narrow(**itt); - if(reader->Entity2RemoteKeyMaterial.size() == 0) + if (reader->Remote2EntityKeyMaterial.size() == 0) { logWarning(SECURITY_CRYPTO, "No key material yet"); continue; } - for(size_t i=0; i < reader->Entity2RemoteKeyMaterial.size(); ++i) + for (size_t i = 0; i < reader->Remote2EntityKeyMaterial.size(); ++i) { - if(reader->Entity2RemoteKeyMaterial.at(i).receiver_specific_key_id == - writer->Remote2EntityKeyMaterial.at(0).receiver_specific_key_id) + if (reader->Remote2EntityKeyMaterial.at(i).sender_key_id == key_id) { *datareader_crypto = *itt; return true; } } //For each Reader2WriterKeyMaterial in the local datareader } //For each datareader present in the local participant - } - } + } //Remote writer key found + } //For each datawriter present in the remote participant for(std::vector::iterator it = remote_participant->Readers.begin(); it != remote_participant->Readers.end(); ++it) { AESGCMGMAC_ReaderCryptoHandle& reader = AESGCMGMAC_ReaderCryptoHandle::narrow(**it); - if(reader->Entity2RemoteKeyMaterial.size() == 0) + auto& rKeyMats = reader->Entity2RemoteKeyMaterial; + + if (rKeyMats.size() == 0) { logWarning(SECURITY_CRYPTO, "No key material yet"); continue; } - if(reader->Entity2RemoteKeyMaterial.at(0).sender_key_id == header.transform_identifier.transformation_key_id) + if (rKeyMats.at(0).sender_key_id == key_id) { + // Remote reader found secure_submessage_category = DATAREADER_SUBMESSAGE; *datareader_crypto = *it; //We have the remote reader, now lets look for the local datawriter - for(std::vector::iterator itt = local_participant->Writers.begin(); itt != local_participant->Writers.end(); ++itt) + AESGCMGMAC_ParticipantCryptoHandle& lookup_participant = is_key_id_zero ? remote_participant : local_participant; + for (std::vector::iterator itt = lookup_participant->Writers.begin(); itt != lookup_participant->Writers.end(); ++itt) { - AESGCMGMAC_WriterCryptoHandle& writer = AESGCMGMAC_WriterCryptoHandle::narrow(**itt); - for(size_t i = 0; i < writer->Entity2RemoteKeyMaterial.size(); ++i) + AESGCMGMAC_WriterCryptoHandle& writer = AESGCMGMAC_ReaderCryptoHandle::narrow(**itt); + + if (writer->Remote2EntityKeyMaterial.size() == 0) { - if(writer->Entity2RemoteKeyMaterial.at(i).receiver_specific_key_id == - reader->Remote2EntityKeyMaterial.at(0).receiver_specific_key_id) + logWarning(SECURITY_CRYPTO, "No key material yet"); + continue; + } + + for (size_t i = 0; i < writer->Remote2EntityKeyMaterial.size(); ++i) + { + if (writer->Remote2EntityKeyMaterial.at(i).sender_key_id == key_id) { *datawriter_crypto = *itt; return true; } } //For each Writer2ReaderKeyMaterial in the local datawriter } //For each datawriter present in the local participant - } - } - logWarning(SECURITY_CRYPTO,"Unable to determine the nature of the message"); + } //Remote reader key found + } //For each datareader present in the remote participant + // logWarning(SECURITY_CRYPTO,"Unable to determine the nature of the message"); return false; } @@ -958,13 +1002,18 @@ bool AESGCMGMAC_Transform::decode_datawriter_submessage( return false; } + auto keyMat = find_key(sending_writer->Entity2RemoteKeyMaterial, header.transform_identifier); + if (keyMat == nullptr) + { + logWarning(SECURITY_CRYPTO, "Key material not found"); + return false; + } + uint32_t session_id; memcpy(&session_id,header.session_id.data(),4); //Sessionkey - std::array session_key = compute_sessionkey( - sending_writer->Entity2RemoteKeyMaterial.at(0).master_sender_key, - sending_writer->Entity2RemoteKeyMaterial.at(0).master_salt, - session_id); + std::array session_key; + compute_sessionkey(session_key, *keyMat, session_id); //IV std::array initialization_vector; memcpy(initialization_vector.data(), header.session_id.data(), 4); @@ -972,15 +1021,14 @@ bool AESGCMGMAC_Transform::decode_datawriter_submessage( // Body uint32_t body_length = 0, body_align = 0; + eprosima::fastcdr::Cdr::state protected_body_state = decoder.getState(); + bool is_encrypted = false; try - { if(!predeserialize_SecureDataBody(decoder, body_length, body_align)) - { - logError(SECURITY_CRYPTO, "Error deserializing SecureDataBody header"); - return false; - } + { + is_encrypted = predeserialize_SecureDataBody(decoder, body_length, body_align); } - catch(eprosima::fastcdr::exception::NotEnoughMemoryException&) + catch (eprosima::fastcdr::exception::NotEnoughMemoryException&) { logError(SECURITY_CRYPTO, "Not enough memory to deserialize SecureDataBody header"); return false; @@ -1019,10 +1067,10 @@ bool AESGCMGMAC_Transform::decode_datawriter_submessage( SecurityException exception; - if(!deserialize_SecureDataTag(decoder, tag, sending_writer->transformation_kind, - sending_writer->Entity2RemoteKeyMaterial.at(0).receiver_specific_key_id, - sending_writer->Entity2RemoteKeyMaterial.at(0).master_receiver_specific_key, - sending_writer->Entity2RemoteKeyMaterial.at(0).master_salt, + if(!deserialize_SecureDataTag(decoder, tag, keyMat->transformation_kind, + keyMat->receiver_specific_key_id, + keyMat->master_receiver_specific_key, + keyMat->master_salt, initialization_vector, session_id, exception)) { return false; @@ -1041,9 +1089,10 @@ bool AESGCMGMAC_Transform::decode_datawriter_submessage( } uint32_t length = plain_rtps_submessage.max_size - plain_rtps_submessage.pos; - if(!deserialize_SecureDataBody(decoder, body_state, tag, body_length, - sending_writer->transformation_kind, session_key, initialization_vector, - &plain_rtps_submessage.buffer[plain_rtps_submessage.pos], length)) + if(!deserialize_SecureDataBody(decoder, is_encrypted ? body_state : protected_body_state, tag, + is_encrypted ? body_length : body_length + 4, + keyMat->transformation_kind, session_key, initialization_vector, + &plain_rtps_submessage.buffer[plain_rtps_submessage.pos], length)) { logError(SECURITY_CRYPTO, "Error decoding content"); return false; @@ -1131,13 +1180,18 @@ bool AESGCMGMAC_Transform::decode_datareader_submessage( return false; } + auto keyMat = find_key(sending_reader->Entity2RemoteKeyMaterial, header.transform_identifier); + if (keyMat == nullptr) + { + logWarning(SECURITY_CRYPTO, "Could not find key material"); + return false; + } + uint32_t session_id; memcpy(&session_id,header.session_id.data(),4); //Sessionkey - std::array session_key = compute_sessionkey( - sending_reader->Entity2RemoteKeyMaterial.at(0).master_sender_key, - sending_reader->Entity2RemoteKeyMaterial.at(0).master_salt, - session_id); + std::array session_key; + compute_sessionkey(session_key, *keyMat, session_id); //IV std::array initialization_vector; memcpy(initialization_vector.data(), header.session_id.data(), 4); @@ -1145,15 +1199,14 @@ bool AESGCMGMAC_Transform::decode_datareader_submessage( // Body uint32_t body_length = 0, body_align = 0; + eprosima::fastcdr::Cdr::state protected_body_state = decoder.getState(); + bool is_encrypted = false; try - { if(!predeserialize_SecureDataBody(decoder, body_length, body_align)) - { - logError(SECURITY_CRYPTO, "Error deserializing SecureDataBody header"); - return false; - } + { + is_encrypted = predeserialize_SecureDataBody(decoder, body_length, body_align); } - catch(eprosima::fastcdr::exception::NotEnoughMemoryException&) + catch (eprosima::fastcdr::exception::NotEnoughMemoryException&) { logError(SECURITY_CRYPTO, "Not enough memory to deserialize SecureDataBody header"); return false; @@ -1192,10 +1245,10 @@ bool AESGCMGMAC_Transform::decode_datareader_submessage( SecurityException exception; - if(!deserialize_SecureDataTag(decoder, tag, sending_reader->transformation_kind, - sending_reader->Entity2RemoteKeyMaterial.at(0).receiver_specific_key_id, - sending_reader->Entity2RemoteKeyMaterial.at(0).master_receiver_specific_key, - sending_reader->Entity2RemoteKeyMaterial.at(0).master_salt, + if(!deserialize_SecureDataTag(decoder, tag, keyMat->transformation_kind, + keyMat->receiver_specific_key_id, + keyMat->master_receiver_specific_key, + keyMat->master_salt, initialization_vector, session_id, exception)) { return false; @@ -1214,9 +1267,10 @@ bool AESGCMGMAC_Transform::decode_datareader_submessage( } uint32_t length = plain_rtps_submessage.max_size - plain_rtps_submessage.pos; - if(!deserialize_SecureDataBody(decoder, body_state, tag, body_length, - sending_reader->transformation_kind, session_key, initialization_vector, - &plain_rtps_submessage.buffer[plain_rtps_submessage.pos], length)) + if(!deserialize_SecureDataBody(decoder, is_encrypted ? body_state : protected_body_state, tag, + is_encrypted ? body_length : body_length + 4, + keyMat->transformation_kind, session_key, initialization_vector, + &plain_rtps_submessage.buffer[plain_rtps_submessage.pos], length)) { logError(SECURITY_CRYPTO, "Error decoding content"); return false; @@ -1256,6 +1310,12 @@ bool AESGCMGMAC_Transform::decode_serialized_payload( return false; } + if (encoded_payload.length == 0) + { + plain_payload.length = 0; + return true; + } + eprosima::fastcdr::FastBuffer input_buffer((char*)encoded_payload.data, encoded_payload.max_size); eprosima::fastcdr::Cdr decoder(input_buffer); @@ -1273,14 +1333,19 @@ bool AESGCMGMAC_Transform::decode_serialized_payload( return false; } + auto keyMat = find_key(sending_writer->Entity2RemoteKeyMaterial, header.transform_identifier); + if (keyMat == nullptr) + { + logWarning(SECURITY_CRYPTO, "Key material not found"); + return false; + } + uint32_t session_id; memcpy(&session_id, header.session_id.data(), 4); //Sessionkey - std::array session_key = compute_sessionkey( - sending_writer->Entity2RemoteKeyMaterial.at(0).master_sender_key, - sending_writer->Entity2RemoteKeyMaterial.at(0).master_salt, - session_id); + std::array session_key; + compute_sessionkey(session_key, *keyMat, session_id); //IV std::array initialization_vector; memcpy(initialization_vector.data(), header.session_id.data(), 4); @@ -1288,21 +1353,32 @@ bool AESGCMGMAC_Transform::decode_serialized_payload( // Body uint32_t body_length = 0, body_align = 0; + eprosima::fastcdr::Cdr::state protected_body_state = decoder.getState(); + bool is_encrypted = false; try - { if(!predeserialize_SecureDataBody(decoder, body_length, body_align)) + { + is_encrypted = + (header.transform_identifier.transformation_kind == c_transfrom_kind_aes128_gcm) || + (header.transform_identifier.transformation_kind == c_transfrom_kind_aes256_gcm); + if (is_encrypted) { - logError(SECURITY_CRYPTO, "Error deserializing SecureDataBody header"); - return false; + decoder.deserialize(body_length, eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); + } + else + { + body_length = encoded_payload.length; + body_length -= sizeof(header); + // TODO: consider origin authentication case + body_length -= sizeof(uint32_t) + 16; } } - catch(eprosima::fastcdr::exception::NotEnoughMemoryException&) + catch (eprosima::fastcdr::exception::NotEnoughMemoryException&) { logError(SECURITY_CRYPTO, "Not enough memory to deserialize SecureDataBody header"); return false; } - eprosima::fastcdr::Cdr::state body_state = decoder.getState(); decoder.jump(body_length + body_align); // Tag @@ -1317,9 +1393,9 @@ bool AESGCMGMAC_Transform::decode_serialized_payload( } uint32_t length = plain_payload.max_size; - if(!deserialize_SecureDataBody(decoder, body_state, tag, body_length, - sending_writer->transformation_kind, session_key, initialization_vector, - plain_payload.data, length)) + if(!deserialize_SecureDataBody(decoder, protected_body_state, tag, body_length, + keyMat->transformation_kind, session_key, initialization_vector, + plain_payload.data, length)) { logError(SECURITY_CRYPTO, "Error decoding content"); return false; @@ -1331,22 +1407,61 @@ bool AESGCMGMAC_Transform::decode_serialized_payload( return true; } -std::array AESGCMGMAC_Transform::compute_sessionkey(const std::array& master_sender_key, - const std::array& master_salt , const uint32_t session_id) +void AESGCMGMAC_Transform::compute_sessionkey(std::array& session_key, + const KeyMaterial_AES_GCM_GMAC& key_mat, const uint32_t session_id) { + bool use_256_bits = (key_mat.transformation_kind == c_transfrom_kind_aes256_gcm || + key_mat.transformation_kind == c_transfrom_kind_aes256_gmac); + int key_len = use_256_bits ? 32 : 16; - std::array session_key; - unsigned char *source = (unsigned char*)malloc(32 + 10 + 32 + 4); - memcpy(source, master_sender_key.data(), 32); - char seq[] = "SessionKey"; - memcpy(source+32, seq, 10); - memcpy(source+32+10, master_salt.data(),32); - memcpy(source+32+10+32, &(session_id),4); + compute_sessionkey(session_key, false, key_mat.master_sender_key, key_mat.master_salt, session_id, key_len); +} - EVP_Digest(source, 32+10+32+4, session_key.data(), NULL, EVP_sha256(), NULL); +void AESGCMGMAC_Transform::compute_sessionkey(std::array& session_key, bool receiver_specific, + const std::array& master_key, const std::array& master_salt, + const uint32_t session_id, int key_len) +{ + int sourceLen = 0; + unsigned char source[18 + 32 + 4]; + const char seq[] = "SessionKey"; + const char receiver_seq[] = "SessionReceiverKey"; + if (receiver_specific) + { + memcpy(source, receiver_seq, 18); + sourceLen = 18; + } + else + { + memcpy(source, seq, 10); + sourceLen = 10; + } + memcpy(source + sourceLen, master_salt.data(), key_len); + sourceLen += key_len; + memcpy(source + sourceLen, &session_id, 4); + sourceLen += 4; + + EVP_PKEY *key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, master_key.data(), key_len); + EVP_MD_CTX* ctx = +#if IS_OPENSSL_1_1 + EVP_MD_CTX_new(); +#else + (EVP_MD_CTX*)malloc(sizeof(EVP_MD_CTX)); +#endif + EVP_MD_CTX_init(ctx); + EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, key); + EVP_DigestSignUpdate(ctx, source, sourceLen); + + size_t finalLen; + EVP_DigestSignFinal(ctx, NULL, &finalLen); + EVP_DigestSignFinal(ctx, session_key.data(), &finalLen); - free(source); - return session_key; + EVP_PKEY_free(key); +#if IS_OPENSSL_1_1 + EVP_MD_CTX_free(ctx); +#else + EVP_MD_CTX_cleanup(ctx); + free(ctx); +#endif } void AESGCMGMAC_Transform::serialize_SecureDataHeader(eprosima::fastcdr::Cdr& serializer, @@ -1360,119 +1475,156 @@ bool AESGCMGMAC_Transform::serialize_SecureDataBody(eprosima::fastcdr::Cdr& seri const std::array& transformation_kind, const std::array& session_key, const std::array& initialization_vector, eprosima::fastcdr::FastBuffer& output_buffer, octet* plain_buffer, uint32_t plain_buffer_len, - SecureDataTag& tag) + SecureDataTag& tag, bool submessage) { -#if __BIG_ENDIAN__ - octet flags = 0x0; - serializer.changeEndianness(eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); -#else - octet flags = BIT(0); - serializer.changeEndianness(eprosima::fastcdr::Cdr::Endianness::LITTLE_ENDIANNESS); -#endif - - serializer << SecureBodySubmessage << flags; - - // Store current state to serialize sequence length at the end of the function - eprosima::fastcdr::Cdr::state sequence_length_state = serializer.getState(); - - // Serialize dummy length - uint16_t length = 0; - serializer << length; - - //Cypher the plain rtps message -> SecureDataBody + bool do_encryption = (transformation_kind == c_transfrom_kind_aes128_gcm || + transformation_kind == c_transfrom_kind_aes256_gcm); + bool use_256_bits = (transformation_kind == c_transfrom_kind_aes256_gcm || + transformation_kind == c_transfrom_kind_aes256_gmac); // AES_BLOCK_SIZE = 16 int cipher_block_size = 0, actual_size = 0, final_size = 0; - char* output_buffer_raw = nullptr; EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new(); - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}) + if (!use_256_bits) { - if(!EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)(session_key.data()), - initialization_vector.data())) + if (!EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)(session_key.data()), + initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptInit function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); return false; } cipher_block_size = EVP_CIPHER_block_size(EVP_aes_128_gcm()); - - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) - { - output_buffer_raw = serializer.getCurrentPosition(); - } } - else if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}) + else { - if(!EVP_EncryptInit(e_ctx, EVP_aes_256_gcm(), (const unsigned char*)(session_key.data()), - initialization_vector.data())) + if (!EVP_EncryptInit(e_ctx, EVP_aes_256_gcm(), (const unsigned char*)(session_key.data()), + initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptInit function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); return false; } cipher_block_size = EVP_CIPHER_block_size(EVP_aes_256_gcm()); + } - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM}) + if (!do_encryption) + { + // Auth only. SEC_BODY should not be created. Plain buffer should be copied instead. + if ((output_buffer.getBufferSize() - (serializer.getCurrentPosition() - serializer.getBufferPointer())) < + plain_buffer_len) { - output_buffer_raw = serializer.getCurrentPosition(); + logError(SECURITY_CRYPTO, "Not enough memory to copy payload"); + EVP_CIPHER_CTX_free(e_ctx); + return false; } - } + memcpy(serializer.getCurrentPosition(), plain_buffer, plain_buffer_len); + serializer.jump(plain_buffer_len); - if(output_buffer_raw != nullptr) + if (!EVP_EncryptUpdate(e_ctx, nullptr, &actual_size, plain_buffer, static_cast(plain_buffer_len))) + { + logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptUpdate function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); + return false; + } + + if (!EVP_EncryptFinal(e_ctx, nullptr, &final_size)) + { + logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptFinal function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); + return false; + } + } + else { +#if __BIG_ENDIAN__ + octet flags = 0x0; + serializer.changeEndianness(eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); +#else + octet flags = BIT(0); + serializer.changeEndianness(eprosima::fastcdr::Cdr::Endianness::LITTLE_ENDIANNESS); +#endif + + if(submessage) serializer << SecureBodySubmessage << flags; + + // Store current state to serialize sequence length at the end of the function + eprosima::fastcdr::Cdr::state sequence_length_state = serializer.getState(); + + if (submessage) + { + // Serialize dummy length + uint16_t length = 0; + serializer << length; + } + + // Serialize dummy content length + uint32_t cnt_length = 0; + serializer << cnt_length; + + //Cypher the plain rtps message -> SecureDataBody + + unsigned char* output_buffer_raw = (unsigned char*)serializer.getCurrentPosition(); + // Check output_buffer contains enough memory to cypher. // - EVP_EncryptUpdate needs at maximum: plain_buffer_len + cipher_block_size - 1. // - EVP_EncryptFinal needs ad maximun cipher_block_size. - if((output_buffer.getBufferSize() - (serializer.getCurrentPosition() - serializer.getBufferPointer())) < - (plain_buffer_len + (2* cipher_block_size) - 1)) + if ((output_buffer.getBufferSize() - (serializer.getCurrentPosition() - serializer.getBufferPointer())) < + (plain_buffer_len + (2 * cipher_block_size) - 1)) { logError(SECURITY_CRYPTO, "Not enough memory to cipher payload"); + EVP_CIPHER_CTX_free(e_ctx); return false; } - } - if(!EVP_EncryptUpdate(e_ctx, (unsigned char*)output_buffer_raw, &actual_size, plain_buffer, - static_cast(plain_buffer_len))) - { - logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptUpdate function returns an error"); - return false; - } + if (!EVP_EncryptUpdate(e_ctx, output_buffer_raw, &actual_size, plain_buffer, + static_cast(plain_buffer_len))) + { + logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptUpdate function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); + return false; + } - if(!EVP_EncryptFinal(e_ctx, (unsigned char*)output_buffer_raw, &final_size)) - { - logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptFinal function returns an error"); - return false; - } + if (!EVP_EncryptFinal(e_ctx, output_buffer_raw, &final_size)) + { + logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptFinal function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); + return false; + } - if(output_buffer_raw != nullptr) - { serializer.jump(actual_size + final_size); - } - else - { - memcpy(serializer.getCurrentPosition(), plain_buffer, plain_buffer_len); - serializer.jump(plain_buffer_len); - } - EVP_CIPHER_CTX_ctrl(e_ctx, EVP_CTRL_GCM_GET_TAG, AES_BLOCK_SIZE, tag.common_mac.data()); - EVP_CIPHER_CTX_free(e_ctx); + eprosima::fastcdr::Cdr::state current_state = serializer.getState(); - eprosima::fastcdr::Cdr::state current_state = serializer.getState(); + // Serialize body sequence length; + cnt_length = static_cast(actual_size + final_size); + serializer.setState(sequence_length_state); + if (submessage) + { + uint16_t length = static_cast(actual_size + final_size + sizeof(uint32_t)); + serializer << length; + } - // Serialize body sequence length; - serializer.setState(sequence_length_state); - serializer << static_cast(actual_size + final_size); + serializer.serialize(cnt_length, eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); - serializer.setState(current_state); + serializer.setState(current_state); - // Align submessage to 4. - size_t alignment = serializer.alignment(serializer.getCurrentPosition() - serializer.getBufferPointer(), sizeof(int32_t)); - for(size_t count = 0; count != alignment; ++count) + } + + // Get commmon_mac + EVP_CIPHER_CTX_ctrl(e_ctx, EVP_CTRL_GCM_GET_TAG, AES_BLOCK_SIZE, tag.common_mac.data()); + EVP_CIPHER_CTX_free(e_ctx); + + if (submessage) { - uint8_t c = 0; - serializer << c; + // Align submessage to 4. + size_t alignment = serializer.alignment(serializer.getCurrentPosition() - serializer.getBufferPointer(), sizeof(int32_t)); + for (size_t count = 0; count != alignment; ++count) + { + uint8_t c = 0; + serializer << c; + } } return true; @@ -1482,8 +1634,12 @@ bool AESGCMGMAC_Transform::serialize_SecureDataTag(eprosima::fastcdr::Cdr& seria const std::array& transformation_kind, const uint32_t session_id, const std::array& initialization_vector, std::vector& receiving_crypto_list, bool update_specific_keys, - SecureDataTag& tag) + SecureDataTag& tag, size_t sessionIndex) { + bool use_256_bits = (transformation_kind == c_transfrom_kind_aes256_gcm || + transformation_kind == c_transfrom_kind_aes256_gmac); + int key_len = use_256_bits ? 32 : 16; + serializer << tag.common_mac; eprosima::fastcdr::Cdr::state length_state = serializer.getState(); @@ -1508,47 +1664,58 @@ bool AESGCMGMAC_Transform::serialize_SecureDataTag(eprosima::fastcdr::Cdr& seria continue; } + auto& keyMat = remote_entity->Remote2EntityKeyMaterial.at(0); + if (keyMat.receiver_specific_key_id == c_transformKeyIdZero) + { + // This means origin authentication is disabled. As it is configured on the writer, we know all other + // receiving entities will have its specific key to null value, and we can skip the whole loop + break; + } + //Update the key if needed - if(update_specific_keys || remote_entity->session_id != session_id) + if(update_specific_keys || remote_entity->Sessions[sessionIndex].session_id != session_id) { //Update triggered! - remote_entity->session_id = session_id; - remote_entity->SessionKey = compute_sessionkey(remote_entity->Remote2EntityKeyMaterial.at(0).master_receiver_specific_key, - remote_entity->Remote2EntityKeyMaterial.at(0).master_salt, - remote_entity->session_id); + remote_entity->Sessions[sessionIndex].session_id = session_id; + compute_sessionkey(remote_entity->Sessions[sessionIndex].SessionKey, true, + keyMat.master_receiver_specific_key, keyMat.master_salt, session_id, key_len); } //Obtain MAC using ReceiverSpecificKey and the same Initialization Vector as before int actual_size = 0, final_size = 0; EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new(); - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}) + if(transformation_kind == c_transfrom_kind_aes128_gcm || + transformation_kind == c_transfrom_kind_aes128_gmac) { - if(!EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)(remote_entity->SessionKey.data()), + if(!EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)(remote_entity->Sessions[sessionIndex].SessionKey.data()), initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptInit function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } } - else if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}) + else if(transformation_kind == c_transfrom_kind_aes256_gcm || + transformation_kind == c_transfrom_kind_aes256_gmac) { - if(!EVP_EncryptInit(e_ctx, EVP_aes_256_gcm(), (const unsigned char*)(remote_entity->SessionKey.data()), + if(!EVP_EncryptInit(e_ctx, EVP_aes_256_gcm(), (const unsigned char*)(remote_entity->Sessions[sessionIndex].SessionKey.data()), initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptInit function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } } if(!EVP_EncryptUpdate(e_ctx, NULL, &actual_size, tag.common_mac.data(), 16)) { logError(SECURITY_CRYPTO, "Unable to create authentication for the datawriter submessage. EVP_EncryptUpdate function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } if(!EVP_EncryptFinal(e_ctx, NULL, &final_size)) { logError(SECURITY_CRYPTO, "Unable to create authentication for the datawriter submessage. EVP_EncryptFinal function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } serializer << remote_entity->Remote2EntityKeyMaterial.at(0).receiver_specific_key_id; @@ -1561,7 +1728,7 @@ bool AESGCMGMAC_Transform::serialize_SecureDataTag(eprosima::fastcdr::Cdr& seria eprosima::fastcdr::Cdr::state current_state = serializer.getState(); serializer.setState(length_state); - serializer << length; + serializer.serialize(length, eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); serializer.setState(current_state); return true; } @@ -1596,50 +1763,64 @@ bool AESGCMGMAC_Transform::serialize_SecureDataTag(eprosima::fastcdr::Cdr& seria continue; } + auto& keyMat = remote_participant->Participant2ParticipantKeyMaterial.at(0); + if (keyMat.receiver_specific_key_id == c_transformKeyIdZero) + { + // This means origin authentication is disabled. As it is configured on the writer, we know all other + // receiving entities will have its specific key to null value, and we can skip the whole loop + break; + } + + bool use_256_bits = (keyMat.transformation_kind == c_transfrom_kind_aes256_gcm || + keyMat.transformation_kind == c_transfrom_kind_aes256_gmac); + int key_len = use_256_bits ? 32 : 16; + //Update the key if needed if((update_specific_keys || remote_participant->session_id != local_participant->session_id) && (*remote_participant != *local_participant)) { //Update triggered! remote_participant->session_id = local_participant->session_id; - remote_participant->SessionKey = compute_sessionkey( - remote_participant->Participant2ParticipantKeyMaterial.at(0).master_receiver_specific_key, - remote_participant->Participant2ParticipantKeyMaterial.at(0).master_salt, - remote_participant->session_id); + compute_sessionkey(remote_participant->SessionKey, true, + keyMat.master_receiver_specific_key, keyMat.master_salt, remote_participant->session_id, key_len); } //Obtain MAC using ReceiverSpecificKey and the same Initialization Vector as before int actual_size = 0, final_size = 0; EVP_CIPHER_CTX* e_ctx = EVP_CIPHER_CTX_new(); - if(local_participant->transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM} || - local_participant->transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}) + auto& trans_kind = remote_participant->Participant2ParticipantKeyMaterial.at(0).transformation_kind; + if(trans_kind == c_transfrom_kind_aes128_gcm || + trans_kind == c_transfrom_kind_aes128_gmac) { if(!EVP_EncryptInit(e_ctx, EVP_aes_128_gcm(), (const unsigned char*)(remote_participant->SessionKey.data()), initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptInit function returns an error"); - //TODO(Ricardo) Free context; + EVP_CIPHER_CTX_free(e_ctx); continue; } } - else if(local_participant->transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM} || - local_participant->transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}) + else if(trans_kind == c_transfrom_kind_aes256_gcm || + trans_kind == c_transfrom_kind_aes256_gmac) { if(!EVP_EncryptInit(e_ctx, EVP_aes_256_gcm(), (const unsigned char*)(remote_participant->SessionKey.data()), initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to encode the payload. EVP_EncryptInit function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } } if(!EVP_EncryptUpdate(e_ctx, NULL, &actual_size, tag.common_mac.data(), 16)) { logError(SECURITY_CRYPTO, "Unable to create authentication for the datawriter submessage. EVP_EncryptUpdate function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } if(!EVP_EncryptFinal(e_ctx, NULL, &final_size)) { logError(SECURITY_CRYPTO, "Unable to create authentication for the datawriter submessage. EVP_EncryptFinal function returns an error"); + EVP_CIPHER_CTX_free(e_ctx); continue; } serializer << remote_participant->Participant2ParticipantKeyMaterial.at(0).receiver_specific_key_id; @@ -1652,7 +1833,7 @@ bool AESGCMGMAC_Transform::serialize_SecureDataTag(eprosima::fastcdr::Cdr& seria eprosima::fastcdr::Cdr::state current_state = serializer.getState(); serializer.setState(length_state); - serializer << length; + serializer.serialize(length, eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); serializer.setState(current_state); return true; } @@ -1676,55 +1857,58 @@ bool AESGCMGMAC_Transform::deserialize_SecureDataBody(eprosima::fastcdr::Cdr& de eprosima::fastcdr::Cdr::state current_state = decoder.getState(); decoder.setState(body_state); + bool do_encryption = (transformation_kind == c_transfrom_kind_aes128_gcm || + transformation_kind == c_transfrom_kind_aes256_gcm); + bool use_256_bits = (transformation_kind == c_transfrom_kind_aes256_gcm || + transformation_kind == c_transfrom_kind_aes256_gmac); + EVP_CIPHER_CTX *d_ctx = EVP_CIPHER_CTX_new(); int cipher_block_size = 0, actual_size = 0, final_size = 0; - octet* output_buffer = nullptr; - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}) + if(!use_256_bits) { if(!EVP_DecryptInit(d_ctx, EVP_aes_128_gcm(), (const unsigned char *)session_key.data(), initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to decode the payload. EVP_DecryptInit function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } cipher_block_size = EVP_CIPHER_block_size(EVP_aes_128_gcm()); - - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) - { - output_buffer = plain_buffer; - } } - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}) + else { if(!EVP_DecryptInit(d_ctx, EVP_aes_256_gcm(), (const unsigned char *)session_key.data(), initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to decode the payload. EVP_DecryptInit function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } cipher_block_size = EVP_CIPHER_block_size(EVP_aes_256_gcm()); - - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM}) - { - output_buffer = plain_buffer; - } } - // Check plain_payload contains enough memory to cypher. - // - EVP_DecryptUpdate needs at maximum: body_length + cipher_block_size. - if(output_buffer != nullptr && (plain_buffer_len < (body_length + cipher_block_size))) + uint32_t protected_len = body_length; + if (do_encryption) { - logError(SECURITY_CRYPTO, "Not enough memory to decode payload"); - return false; + decoder.deserialize(protected_len, eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); + + // Check plain_payload contains enough memory to cypher. + // - EVP_DecryptUpdate needs at maximum: body_length + cipher_block_size. + if (plain_buffer_len < (protected_len + cipher_block_size)) + { + logError(SECURITY_CRYPTO, "Not enough memory to decode payload"); + EVP_CIPHER_CTX_free(d_ctx); + return false; + } } - if(!EVP_DecryptUpdate(d_ctx, output_buffer, &actual_size, - (unsigned char*)decoder.getCurrentPosition(), body_length)) + octet* output_buffer = do_encryption ? plain_buffer : nullptr; + unsigned char* input_buffer = (unsigned char*)decoder.getCurrentPosition(); + if(!EVP_DecryptUpdate(d_ctx, output_buffer, &actual_size, input_buffer, protected_len)) { logError(SECURITY_CRYPTO, "Unable to decode the payload. EVP_DecryptUpdate function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } @@ -1733,11 +1917,23 @@ bool AESGCMGMAC_Transform::deserialize_SecureDataBody(eprosima::fastcdr::Cdr& de if(!EVP_DecryptFinal(d_ctx, output_buffer, &final_size)) { logError(SECURITY_CRYPTO, "Unable to decode the payload. EVP_DecryptFinal function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } EVP_CIPHER_CTX_free(d_ctx); - plain_buffer_len = actual_size + final_size; + uint32_t cnt_len = do_encryption ? static_cast(actual_size + final_size) : body_length; + if (plain_buffer_len < cnt_len) + { + logError(SECURITY_CRYPTO, "Not enough memory to decode payload"); + return false; + } + + plain_buffer_len = cnt_len; + if (output_buffer == nullptr) + { + memcpy(plain_buffer, input_buffer, plain_buffer_len); + } decoder.setState(current_state); @@ -1760,12 +1956,6 @@ bool AESGCMGMAC_Transform::predeserialize_SecureDataBody(eprosima::fastcdr::Cdr& decoder >> secure_submsg_id; - if(secure_submsg_id != SecureBodySubmessage) - { - logError(SECURITY_CRYPTO, "Expected SecureDataBody submsg id"); - return false; - } - decoder >> flags; if(flags & BIT(0)) @@ -1784,7 +1974,7 @@ bool AESGCMGMAC_Transform::predeserialize_SecureDataBody(eprosima::fastcdr::Cdr& body_align = static_cast(decoder.alignment((decoder.getCurrentPosition() + body_length) - decoder.getBufferPointer(), sizeof(int32_t))); - return true; + return (secure_submsg_id == SecureBodySubmessage); } bool AESGCMGMAC_Transform::deserialize_SecureDataTag(eprosima::fastcdr::Cdr& decoder, SecureDataTag& tag, @@ -1796,7 +1986,7 @@ bool AESGCMGMAC_Transform::deserialize_SecureDataTag(eprosima::fastcdr::Cdr& dec decoder >> tag.common_mac; uint32_t sequence_length = 0; - decoder >> sequence_length; + decoder.deserialize(sequence_length, eprosima::fastcdr::Cdr::Endianness::BIG_ENDIANNESS); if(sequence_length > 0) { @@ -1830,23 +2020,24 @@ bool AESGCMGMAC_Transform::deserialize_SecureDataTag(eprosima::fastcdr::Cdr& dec int actual_size = 0, final_size = 0; //Get ReceiverSpecificSessionKey - std::array specific_session_key = compute_sessionkey(receiver_specific_key, - master_salt, session_id); + std::array specific_session_key; + compute_sessionkey(specific_session_key, true, receiver_specific_key, master_salt, session_id); //Verify specific MAC - if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GMAC}) + if(transformation_kind == c_transfrom_kind_aes128_gcm || + transformation_kind == c_transfrom_kind_aes128_gmac) { d_cipher = EVP_aes_128_gcm(); } - else if(transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GCM} || - transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES256_GMAC}) + else if(transformation_kind == c_transfrom_kind_aes256_gcm || + transformation_kind == c_transfrom_kind_aes256_gmac) { d_cipher = EVP_aes_256_gcm(); } else { logError(SECURITY_CRYPTO, "Invalid transformation kind)"); + EVP_CIPHER_CTX_free(d_ctx); return false; } @@ -1854,28 +2045,31 @@ bool AESGCMGMAC_Transform::deserialize_SecureDataTag(eprosima::fastcdr::Cdr& dec initialization_vector.data())) { logError(SECURITY_CRYPTO, "Unable to authenticate the message. EVP_DecryptInit function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } - if(!EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag.receiver_mac.data())) + if(!EVP_DecryptUpdate(d_ctx, NULL, &actual_size, tag.common_mac.data(), 16)) { - logError(SECURITY_CRYPTO, "Unable to authenticate the message. EVP_CIPHER_CTX_ctrl function returns an error"); + logError(SECURITY_CRYPTO, "Unable to authenticate the message. EVP_DecryptUpdate function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } - if(!EVP_DecryptUpdate(d_ctx, NULL, &actual_size, tag.common_mac.data(), 16)) + if (!EVP_CIPHER_CTX_ctrl(d_ctx, EVP_CTRL_GCM_SET_TAG, 16, tag.receiver_mac.data())) { - logError(SECURITY_CRYPTO, "Unable to authenticate the message. EVP_DecryptUpdate function returns an error"); + logError(SECURITY_CRYPTO, "Unable to authenticate the message. EVP_CIPHER_CTX_ctrl function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } if(!EVP_DecryptFinal_ex(d_ctx, NULL, &final_size)) { logError(SECURITY_CRYPTO, "Unable to authenticate the message. EVP_DecryptFinal_ex function returns an error"); + EVP_CIPHER_CTX_free(d_ctx); return false; } - // TODO(Ricardo) No freed in errors. EVP_CIPHER_CTX_free(d_ctx); } diff --git a/src/cpp/security/cryptography/AESGCMGMAC_Transform.h b/src/cpp/security/cryptography/AESGCMGMAC_Transform.h index 0651ab1fa8c..533910cfa97 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_Transform.h +++ b/src/cpp/security/cryptography/AESGCMGMAC_Transform.h @@ -104,9 +104,19 @@ class AESGCMGMAC_Transform : public CryptoTransform DatawriterCryptoHandle& sending_datawriter_crypto, SecurityException& exception) override; - //Aux function to compute session key from the master material - std::array compute_sessionkey(const std::array& master_sender_key, - const std::array& master_salt , const uint32_t session_id); + //Aux functions to compute session key from the master material + void compute_sessionkey( + std::array& session_key, + bool receiver_specific, + const std::array& master_key, + const std::array& master_salt, + const uint32_t session_id, + int key_len = 32); + + void compute_sessionkey( + std::array& session_key, + const KeyMaterial_AES_GCM_GMAC& key, + const uint32_t session_id); //Serialization and deserialization of message components void serialize_SecureDataHeader(eprosima::fastcdr::Cdr& serializer, @@ -117,13 +127,13 @@ class AESGCMGMAC_Transform : public CryptoTransform const std::array& transformation_kind, const std::array& session_key, const std::array& initialization_vector, eprosima::fastcdr::FastBuffer& output_buffer, octet* plain_buffer, uint32_t plain_buffer_len, - SecureDataTag& tag); + SecureDataTag& tag, bool submessage); bool serialize_SecureDataTag(eprosima::fastcdr::Cdr& serializer, const std::array& transformation_kind, const uint32_t session_id, const std::array& initialization_vector, std::vector& receiving_datareader_crypto_list, bool update_specific_keys, - SecureDataTag& tag); + SecureDataTag& tag, size_t sessionIndex); bool serialize_SecureDataTag(eprosima::fastcdr::Cdr& serializer, const AESGCMGMAC_ParticipantCryptoHandle& local_participant, @@ -133,7 +143,15 @@ class AESGCMGMAC_Transform : public CryptoTransform SecureDataHeader deserialize_SecureDataHeader(eprosima::fastcdr::Cdr& decoder); + /** + * Get information on the data between a Header and a Tag submessage. + * @param decoder Cdr decoding stream pointing to the first byte after the Header submessage + * @param body_length Outputs length of protected data + * @param body_align Outputs number of alignment bytes after protected data + * @return true when protected data is encrypted (i.e. it is a SEC_BODY submessage) + */ bool predeserialize_SecureDataBody(eprosima::fastcdr::Cdr& decoder, uint32_t& body_length, uint32_t& body_align); + bool deserialize_SecureDataBody(eprosima::fastcdr::Cdr& decoder, eprosima::fastcdr::Cdr::state& body_state, SecureDataTag& tag, uint32_t body_length, const std::array transformation_kind, diff --git a/src/cpp/security/cryptography/AESGCMGMAC_Types.h b/src/cpp/security/cryptography/AESGCMGMAC_Types.h index c924f2ae336..820dc4ea8df 100644 --- a/src/cpp/security/cryptography/AESGCMGMAC_Types.h +++ b/src/cpp/security/cryptography/AESGCMGMAC_Types.h @@ -23,6 +23,8 @@ #include #include #include +#include +#include #include #include @@ -52,6 +54,12 @@ namespace fastrtps { namespace rtps { namespace security { +const CryptoTransformKind c_transfrom_kind_none = CRYPTO_TRANSFORMATION_KIND_NONE; +const CryptoTransformKind c_transfrom_kind_aes128_gmac = CRYPTO_TRANSFORMATION_KIND_AES128_GMAC; +const CryptoTransformKind c_transfrom_kind_aes128_gcm = CRYPTO_TRANSFORMATION_KIND_AES128_GCM; +const CryptoTransformKind c_transfrom_kind_aes256_gmac = CRYPTO_TRANSFORMATION_KIND_AES256_GMAC; +const CryptoTransformKind c_transfrom_kind_aes256_gcm = CRYPTO_TRANSFORMATION_KIND_AES256_GCM; + /* Key Storage * ----------- * Contains common key and specific key @@ -73,6 +81,7 @@ struct KeyMaterial_AES_GCM_GMAC{ std::array master_receiver_specific_key; }; +typedef std::vector KeyMaterial_AES_GCM_GMAC_Seq; /* SecureSubMessageElements * ------------------------ */ @@ -99,6 +108,7 @@ struct SecureDataTag{ CryptoTransformKeyId receiver_mac_key_id; std::array receiver_mac; }; + /* Key Management * -------------- * Keys are stored and managed as Cryptohandles @@ -116,36 +126,45 @@ struct SecureDataTag{ * Note: the common key of the remote cryptohandle is stored along with the specific keys. KeyMaterial->master_sender_key */ +struct KeySessionData +{ + uint32_t session_id; + std::array SessionKey; + uint64_t session_block_counter; + + KeySessionData() : session_id(std::numeric_limits::max()), session_block_counter(0) {} +}; + class EntityKeyHandle { public: - EntityKeyHandle() : session_id(std::numeric_limits::max()), - session_block_counter(0), max_blocks_per_session(0){} + EntityKeyHandle() : max_blocks_per_session(0) + { + } ~EntityKeyHandle(){ } static const char* const class_id_; + //Plugin security options + PluginEndpointSecurityAttributesMask EndpointPluginAttributes; //Storage for the LocalCryptoHandle master_key, not used in RemoteCryptoHandles - KeyMaterial_AES_GCM_GMAC EntityKeyMaterial; + KeyMaterial_AES_GCM_GMAC_Seq EntityKeyMaterial; //KeyId of the master_key of the parent Participant and pointer to the relevant CryptoHandle CryptoTransformKeyId Participant_master_key_id; ParticipantCryptoHandle* Parent_participant; //(Direct) ReceiverSpecific Keys - Inherently hold the master_key of the writer - std::vector Entity2RemoteKeyMaterial; + KeyMaterial_AES_GCM_GMAC_Seq Entity2RemoteKeyMaterial; //(Reverse) ReceiverSpecific Keys - Inherently hold the master_key of the remote readers - std::vector Remote2EntityKeyMaterial; + KeyMaterial_AES_GCM_GMAC_Seq Remote2EntityKeyMaterial; //Copy of the Keymaterial used to Cypher CryptoTokens (inherited from the parent participant) - KeyMaterial_AES_GCM_GMAC Participant2ParticipantKxKeyMaterial; + // KeyMaterial_AES_GCM_GMAC Participant2ParticipantKxKeyMaterial; //Data used to store the current session keys and to determine when it has to be updated - uint32_t session_id; - std::array SessionKey; - uint64_t session_block_counter; + KeySessionData Sessions[2]; uint64_t max_blocks_per_session; - CryptoTransformKind transformation_kind; std::mutex mutex_; }; typedef HandleImpl AESGCMGMAC_WriterCryptoHandle; @@ -164,6 +183,8 @@ class ParticipantKeyHandle static const char* const class_id_; + //Plugin security options + PluginParticipantSecurityAttributesMask ParticipantPluginAttributes; //Storage for the LocalCryptoHandle master_key, not used in RemoteCryptoHandles KeyMaterial_AES_GCM_GMAC ParticipantKeyMaterial; //(Direct) ReceiverSpecific Keys - Inherently hold the master_key of the writer @@ -182,7 +203,6 @@ class ParticipantKeyHandle std::array SessionKey; uint64_t session_block_counter; uint64_t max_blocks_per_session; - CryptoTransformKind transformation_kind; std::mutex mutex_; }; diff --git a/src/cpp/subscriber/SubscriberHistory.cpp b/src/cpp/subscriber/SubscriberHistory.cpp index 960104d4b3c..a65aa5efbcf 100644 --- a/src/cpp/subscriber/SubscriberHistory.cpp +++ b/src/cpp/subscriber/SubscriberHistory.cpp @@ -151,7 +151,11 @@ bool SubscriberHistory::received_change(CacheChange_t* a_change, size_t unknown_ { logInfo(RTPS_HISTORY, "Getting Key of change with no Key transmitted") mp_subImpl->getType()->deserialize(&a_change->serializedPayload, mp_getKeyObject); - if (!mp_subImpl->getType()->getKey(mp_getKeyObject, &a_change->instanceHandle)) + bool is_key_protected = false; +#if HAVE_SECURITY + is_key_protected = mp_reader->getAttributes().security_attributes().is_key_protected; +#endif + if(!mp_subImpl->getType()->getKey(mp_getKeyObject, &a_change->instanceHandle, is_key_protected)) return false; } @@ -385,7 +389,11 @@ bool SubscriberHistory::readNextData(void* data, SampleInfo_t* info) if (this->mp_subImpl->getAttributes().topic.topicKind == WITH_KEY && change->instanceHandle == c_InstanceHandle_Unknown && change->kind == ALIVE) { - this->mp_subImpl->getType()->getKey(data, &change->instanceHandle); + bool is_key_protected = false; +#if HAVE_SECURITY + is_key_protected = mp_reader->getAttributes().security_attributes().is_key_protected; +#endif + this->mp_subImpl->getType()->getKey(data, &change->instanceHandle, is_key_protected); } info->iHandle = change->instanceHandle; info->related_sample_identity = change->write_params.sample_identity(); @@ -433,7 +441,11 @@ bool SubscriberHistory::takeNextData(void* data, SampleInfo_t* info) if (this->mp_subImpl->getAttributes().topic.topicKind == WITH_KEY && change->instanceHandle == c_InstanceHandle_Unknown && change->kind == ALIVE) { - this->mp_subImpl->getType()->getKey(data, &change->instanceHandle); + bool is_key_protected = false; +#if HAVE_SECURITY + is_key_protected = mp_reader->getAttributes().security_attributes().is_key_protected; +#endif + this->mp_subImpl->getType()->getKey(data, &change->instanceHandle, is_key_protected); } info->iHandle = change->instanceHandle; info->related_sample_identity = change->write_params.sample_identity(); diff --git a/src/cpp/types/DynamicPubSubType.cpp b/src/cpp/types/DynamicPubSubType.cpp index b3fe8fc9d33..85614f08bd7 100644 --- a/src/cpp/types/DynamicPubSubType.cpp +++ b/src/cpp/types/DynamicPubSubType.cpp @@ -115,7 +115,7 @@ bool DynamicPubSubType::deserialize(eprosima::fastrtps::rtps::SerializedPayload_ return true; } -bool DynamicPubSubType::getKey(void* data, eprosima::fastrtps::rtps::InstanceHandle_t* handle) +bool DynamicPubSubType::getKey(void* data, eprosima::fastrtps::rtps::InstanceHandle_t* handle, bool force_md5) { if (mDynamicType == nullptr || !m_isGetKeyDefined) { @@ -133,7 +133,7 @@ bool DynamicPubSubType::getKey(void* data, eprosima::fastrtps::rtps::InstanceHan eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer, keyBufferSize); eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. pDynamicData->serializeKey(ser); - if (keyBufferSize > 16) + if (force_md5 || keyBufferSize > 16) { m_md5.init(); m_md5.update(m_keyBuffer, (unsigned int)ser.getSerializedDataLength()); diff --git a/test/blackbox/types/Data1mbType.cpp b/test/blackbox/types/Data1mbType.cpp index 484827b203b..12460349d02 100644 --- a/test/blackbox/types/Data1mbType.cpp +++ b/test/blackbox/types/Data1mbType.cpp @@ -79,14 +79,14 @@ std::function Data1mbType::getSerializedSizeProvider(void *data) }; } -bool Data1mbType::getKey(void *data, InstanceHandle_t* handle) { +bool Data1mbType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; Data1mb* p_type = (Data1mb*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,Data1mb::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(Data1mb::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || Data1mb::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/test/blackbox/types/Data1mbType.h b/test/blackbox/types/Data1mbType.h index 53c1e95076a..b4c3d3bc8e0 100644 --- a/test/blackbox/types/Data1mbType.h +++ b/test/blackbox/types/Data1mbType.h @@ -43,7 +43,7 @@ class Data1mbType : public eprosima::fastrtps::TopicDataType virtual ~Data1mbType(); bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); std::function getSerializedSizeProvider(void *data); void* createData(); void deleteData(void * data); diff --git a/test/blackbox/types/Data64kbType.cpp b/test/blackbox/types/Data64kbType.cpp index 4082d32b71d..91d1bb89f9b 100644 --- a/test/blackbox/types/Data64kbType.cpp +++ b/test/blackbox/types/Data64kbType.cpp @@ -79,14 +79,14 @@ void Data64kbType::deleteData(void* data) { delete((Data64kb*)data); } -bool Data64kbType::getKey(void *data, InstanceHandle_t* handle) { +bool Data64kbType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; Data64kb* p_type = (Data64kb*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,Data64kb::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(Data64kb::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || Data64kb::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/test/blackbox/types/Data64kbType.h b/test/blackbox/types/Data64kbType.h index 9559f956621..47019bd5b6c 100644 --- a/test/blackbox/types/Data64kbType.h +++ b/test/blackbox/types/Data64kbType.h @@ -41,7 +41,7 @@ class Data64kbType : public eprosima::fastrtps::TopicDataType { virtual ~Data64kbType(); bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); std::function getSerializedSizeProvider(void *data); void deleteData(void * data); diff --git a/test/blackbox/types/HelloWorldType.cpp b/test/blackbox/types/HelloWorldType.cpp index 7b03e86c735..d16af6418a8 100644 --- a/test/blackbox/types/HelloWorldType.cpp +++ b/test/blackbox/types/HelloWorldType.cpp @@ -84,7 +84,7 @@ void HelloWorldType::deleteData(void* data) delete((HelloWorld*)data); } -bool HelloWorldType::getKey(void* /*data*/, InstanceHandle_t* /*ihandle*/) +bool HelloWorldType::getKey(void* /*data*/, InstanceHandle_t* /*ihandle*/, bool /*force_md5*/) { return false; } diff --git a/test/blackbox/types/HelloWorldType.h b/test/blackbox/types/HelloWorldType.h index 91733de63b8..266026b0585 100644 --- a/test/blackbox/types/HelloWorldType.h +++ b/test/blackbox/types/HelloWorldType.h @@ -35,7 +35,7 @@ class HelloWorldType:public eprosima::fastrtps::TopicDataType { bool serialize(void*data, eprosima::fastrtps::rtps::SerializedPayload_t* payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t* payload,void * data); std::function getSerializedSizeProvider(void *data); - bool getKey(void*data, eprosima::fastrtps::rtps::InstanceHandle_t* ihandle); + bool getKey(void*data, eprosima::fastrtps::rtps::InstanceHandle_t* ihandle, bool force_md5); void* createData(); void deleteData(void* data); }; diff --git a/test/blackbox/types/StringType.cpp b/test/blackbox/types/StringType.cpp index 3d45ad0b1ae..1cae9cdb7e7 100644 --- a/test/blackbox/types/StringType.cpp +++ b/test/blackbox/types/StringType.cpp @@ -37,7 +37,7 @@ StringType::~StringType() { bool StringType::serialize(void* data, SerializedPayload_t* payload) { - String* hw = (String*) data; + String* hw = (String*) data; // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer((char*)payload->data, payload->max_size); // Object that serializes the data. @@ -84,7 +84,7 @@ void StringType::deleteData(void* data) delete((String*)data); } -bool StringType::getKey(void* /*data*/, InstanceHandle_t* /*ihandle*/) +bool StringType::getKey(void* /*data*/, InstanceHandle_t* /*ihandle*/, bool /*force_md5*/) { return false; } diff --git a/test/blackbox/types/StringType.h b/test/blackbox/types/StringType.h index af843f218de..a6f14d079f0 100644 --- a/test/blackbox/types/StringType.h +++ b/test/blackbox/types/StringType.h @@ -35,7 +35,7 @@ class StringType:public eprosima::fastrtps::TopicDataType { bool serialize(void*data, eprosima::fastrtps::rtps::SerializedPayload_t* payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t* payload,void * data); std::function getSerializedSizeProvider(void *data); - bool getKey(void*data, eprosima::fastrtps::rtps::InstanceHandle_t* ihandle); + bool getKey(void*data, eprosima::fastrtps::rtps::InstanceHandle_t* ihandle, bool force_md5); void* createData(); void deleteData(void* data); }; diff --git a/test/mock/rtps/ParticipantProxyData/fastrtps/rtps/builtin/data/ParticipantProxyData.h b/test/mock/rtps/ParticipantProxyData/fastrtps/rtps/builtin/data/ParticipantProxyData.h index a961b8e7c9c..4da384e6331 100644 --- a/test/mock/rtps/ParticipantProxyData/fastrtps/rtps/builtin/data/ParticipantProxyData.h +++ b/test/mock/rtps/ParticipantProxyData/fastrtps/rtps/builtin/data/ParticipantProxyData.h @@ -23,6 +23,10 @@ #include #include +#if HAVE_SECURITY +#include +#endif + namespace eprosima { namespace fastrtps { namespace rtps { @@ -44,9 +48,13 @@ class ParticipantProxyData uint32_t m_availableBuiltinEndpoints; LocatorList_t m_metatrafficUnicastLocatorList; LocatorList_t m_metatrafficMulticastLocatorList; - IdentityToken identity_token_; VendorId_t m_VendorId; +#if HAVE_SECURITY + IdentityToken identity_token_; PermissionsToken permissions_token_; + security::ParticipantSecurityAttributesMask security_attributes_ = 0UL; + security::PluginParticipantSecurityAttributesMask plugin_security_attributes_ = 0UL; +#endif }; } // namespace rtps diff --git a/test/mock/rtps/RTPSParticipantImpl/rtps/participant/RTPSParticipantImpl.h b/test/mock/rtps/RTPSParticipantImpl/rtps/participant/RTPSParticipantImpl.h index b93e094d91b..468aff0cb70 100644 --- a/test/mock/rtps/RTPSParticipantImpl/rtps/participant/RTPSParticipantImpl.h +++ b/test/mock/rtps/RTPSParticipantImpl/rtps/participant/RTPSParticipantImpl.h @@ -27,6 +27,10 @@ #include #include +#if HAVE_SECURITY +#include +#endif + #include namespace eprosima { @@ -63,6 +67,10 @@ class RTPSParticipantImpl MOCK_CONST_METHOD0(getGuid, const GUID_t&()); +#if HAVE_SECURITY + MOCK_CONST_METHOD0(security_attributes, const security::ParticipantSecurityAttributes&()); +#endif + MOCK_METHOD1(setGuid, void(GUID_t&)); MOCK_METHOD6(createWriter_mock, bool (RTPSWriter** writer, WriterAttributes& param, WriterHistory* hist,WriterListener* listen, diff --git a/test/mock/rtps/ReaderProxyData/fastrtps/rtps/builtin/data/ReaderProxyData.h b/test/mock/rtps/ReaderProxyData/fastrtps/rtps/builtin/data/ReaderProxyData.h index 1421b6f5a50..9a6e20cb059 100644 --- a/test/mock/rtps/ReaderProxyData/fastrtps/rtps/builtin/data/ReaderProxyData.h +++ b/test/mock/rtps/ReaderProxyData/fastrtps/rtps/builtin/data/ReaderProxyData.h @@ -21,6 +21,10 @@ #include +#if HAVE_SECURITY +#include +#endif + namespace eprosima { namespace fastrtps { namespace rtps { @@ -31,6 +35,11 @@ class ReaderProxyData GUID_t guid() { return m_guid; } +#if HAVE_SECURITY + security::EndpointSecurityAttributesMask security_attributes_ = 0UL; + security::PluginEndpointSecurityAttributesMask plugin_security_attributes_ = 0UL; +#endif + private: GUID_t m_guid; diff --git a/test/mock/rtps/SecurityPluginFactory/rtps/security/MockCryptoKeyFactory.h b/test/mock/rtps/SecurityPluginFactory/rtps/security/MockCryptoKeyFactory.h index 1b355edb756..a4a3997747b 100644 --- a/test/mock/rtps/SecurityPluginFactory/rtps/security/MockCryptoKeyFactory.h +++ b/test/mock/rtps/SecurityPluginFactory/rtps/security/MockCryptoKeyFactory.h @@ -36,10 +36,11 @@ class MockCryptoKeyFactory : public CryptoKeyFactory virtual ~MockCryptoKeyFactory(){} - MOCK_METHOD4(register_local_participant, ParticipantCryptoHandle* ( + MOCK_METHOD5(register_local_participant, ParticipantCryptoHandle* ( const IdentityHandle&, const PermissionsHandle&, const PropertySeq&, + const ParticipantSecurityAttributes&, SecurityException&)); MOCK_METHOD5(register_matched_remote_participant, ParticipantCryptoHandle* ( @@ -49,9 +50,10 @@ class MockCryptoKeyFactory : public CryptoKeyFactory const SharedSecretHandle&, SecurityException&)); - MOCK_METHOD3(register_local_datawriter, DatawriterCryptoHandle* ( + MOCK_METHOD4(register_local_datawriter, DatawriterCryptoHandle* ( ParticipantCryptoHandle&, const PropertySeq&, + const EndpointSecurityAttributes&, SecurityException&)); MOCK_METHOD5(register_matched_remote_datareader, DatareaderCryptoHandle* ( @@ -61,9 +63,10 @@ class MockCryptoKeyFactory : public CryptoKeyFactory const bool, SecurityException&)); - MOCK_METHOD3(register_local_datareader, DatareaderCryptoHandle* ( + MOCK_METHOD4(register_local_datareader, DatareaderCryptoHandle* ( ParticipantCryptoHandle&, const PropertySeq&, + const EndpointSecurityAttributes&, SecurityException&)); MOCK_METHOD4(register_matched_remote_datawriter, DatawriterCryptoHandle* ( diff --git a/test/mock/rtps/WriterProxyData/fastrtps/rtps/builtin/data/WriterProxyData.h b/test/mock/rtps/WriterProxyData/fastrtps/rtps/builtin/data/WriterProxyData.h index 226363cf080..5fc2e943630 100644 --- a/test/mock/rtps/WriterProxyData/fastrtps/rtps/builtin/data/WriterProxyData.h +++ b/test/mock/rtps/WriterProxyData/fastrtps/rtps/builtin/data/WriterProxyData.h @@ -21,6 +21,10 @@ #include +#if HAVE_SECURITY +#include +#endif + namespace eprosima { namespace fastrtps { namespace rtps { @@ -31,6 +35,11 @@ class WriterProxyData GUID_t guid() { return m_guid; } +#if HAVE_SECURITY + security::EndpointSecurityAttributesMask security_attributes_ = 0UL; + security::PluginEndpointSecurityAttributesMask plugin_security_attributes_ = 0UL; +#endif + private: GUID_t m_guid; diff --git a/test/profiling/allocations/AllocTestTypePubSubTypes.cxx b/test/profiling/allocations/AllocTestTypePubSubTypes.cxx index c7868671dd5..9df17c13bb8 100644 --- a/test/profiling/allocations/AllocTestTypePubSubTypes.cxx +++ b/test/profiling/allocations/AllocTestTypePubSubTypes.cxx @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file AllocTestTypePubSubTypes.cpp * This header file contains the implementation of the serialization functions. * @@ -98,14 +98,14 @@ void AllocTestTypePubSubType::deleteData(void* data) { delete((AllocTestType*)data); } -bool AllocTestTypePubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool AllocTestTypePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; AllocTestType* p_type = (AllocTestType*) data; eprosima::fastcdr::FastBuffer fastbuffer((char*)m_keyBuffer,AllocTestType::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(AllocTestType::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || AllocTestType::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); m_md5.finalize(); diff --git a/test/profiling/allocations/AllocTestTypePubSubTypes.h b/test/profiling/allocations/AllocTestTypePubSubTypes.h index dab726206f4..b6bcb60903e 100644 --- a/test/profiling/allocations/AllocTestTypePubSubTypes.h +++ b/test/profiling/allocations/AllocTestTypePubSubTypes.h @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -/*! +/*! * @file AllocTestTypePubSubTypes.h * This header file contains the declaration of the serialization functions. * @@ -40,7 +40,7 @@ class AllocTestTypePubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/test/unittest/dynamic_types/idl/BasicPubSubTypes.cxx b/test/unittest/dynamic_types/idl/BasicPubSubTypes.cxx index 1262930dccb..49cd1785429 100644 --- a/test/unittest/dynamic_types/idl/BasicPubSubTypes.cxx +++ b/test/unittest/dynamic_types/idl/BasicPubSubTypes.cxx @@ -110,14 +110,14 @@ void EnumStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool EnumStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool EnumStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; EnumStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),EnumStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(EnumStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || EnumStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -212,14 +212,14 @@ void AliasStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool AliasStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool AliasStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; AliasStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),AliasStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(AliasStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || AliasStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -314,14 +314,14 @@ void AliasAliasStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool AliasAliasStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool AliasAliasStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; AliasAliasStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),AliasAliasStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(AliasAliasStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || AliasAliasStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -416,14 +416,14 @@ void BoolStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool BoolStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool BoolStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; BoolStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),BoolStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(BoolStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || BoolStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -518,14 +518,14 @@ void OctetStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool OctetStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool OctetStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; OctetStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),OctetStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(OctetStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || OctetStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -620,14 +620,14 @@ void ShortStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool ShortStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ShortStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ShortStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),ShortStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ShortStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ShortStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -722,14 +722,14 @@ void LongStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool LongStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool LongStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; LongStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),LongStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(LongStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || LongStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -824,14 +824,14 @@ void LongLongStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool LongLongStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool LongLongStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; LongLongStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),LongLongStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(LongLongStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || LongLongStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -926,14 +926,14 @@ void UShortStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool UShortStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool UShortStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; UShortStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),UShortStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(UShortStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || UShortStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1028,14 +1028,14 @@ void ULongStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool ULongStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ULongStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ULongStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),ULongStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ULongStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ULongStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1130,14 +1130,14 @@ void ULongLongStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool ULongLongStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ULongLongStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ULongLongStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),ULongLongStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ULongLongStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ULongLongStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1232,14 +1232,14 @@ void FloatStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool FloatStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool FloatStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; FloatStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),FloatStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(FloatStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || FloatStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1334,14 +1334,14 @@ void DoubleStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool DoubleStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool DoubleStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; DoubleStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),DoubleStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(DoubleStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || DoubleStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1436,14 +1436,14 @@ void LongDoubleStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool LongDoubleStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool LongDoubleStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; LongDoubleStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),LongDoubleStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(LongDoubleStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || LongDoubleStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1538,14 +1538,14 @@ void CharStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool CharStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool CharStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; CharStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),CharStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(CharStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || CharStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1640,14 +1640,14 @@ void WCharStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool WCharStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool WCharStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; WCharStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),WCharStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(WCharStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || WCharStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1742,14 +1742,14 @@ void StringStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool StringStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool StringStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; StringStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),StringStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(StringStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || StringStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1844,14 +1844,14 @@ void WStringStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool WStringStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool WStringStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; WStringStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),WStringStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(WStringStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || WStringStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -1946,14 +1946,14 @@ void LargeStringStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool LargeStringStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool LargeStringStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; LargeStringStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),LargeStringStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(LargeStringStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || LargeStringStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2048,14 +2048,14 @@ void LargeWStringStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool LargeWStringStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool LargeWStringStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; LargeWStringStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),LargeWStringStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(LargeWStringStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || LargeWStringStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2150,14 +2150,14 @@ void ArraytStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool ArraytStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ArraytStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ArraytStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),ArraytStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ArraytStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ArraytStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2253,14 +2253,14 @@ void ArrayArrayStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool ArrayArrayStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ArrayArrayStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ArrayArrayStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),ArrayArrayStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ArrayArrayStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ArrayArrayStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2355,14 +2355,14 @@ void SequenceStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool SequenceStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool SequenceStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; SequenceStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),SequenceStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(SequenceStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || SequenceStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2457,14 +2457,14 @@ void SequenceSequenceStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool SequenceSequenceStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool SequenceSequenceStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; SequenceSequenceStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),SequenceSequenceStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(SequenceSequenceStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || SequenceSequenceStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2559,14 +2559,14 @@ void MapStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool MapStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool MapStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; MapStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),MapStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(MapStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || MapStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2661,14 +2661,14 @@ void MapMapStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool MapMapStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool MapMapStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; MapMapStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),MapMapStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(MapMapStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || MapMapStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2763,14 +2763,14 @@ void StructStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool StructStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool StructStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; StructStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),StructStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(StructStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || StructStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2865,14 +2865,14 @@ void StructStructStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool StructStructStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool StructStructStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; StructStructStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),StructStructStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(StructStructStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || StructStructStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -2970,14 +2970,14 @@ void SimpleUnionStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool SimpleUnionStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool SimpleUnionStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; SimpleUnionStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),SimpleUnionStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(SimpleUnionStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || SimpleUnionStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -3072,14 +3072,14 @@ void UnionUnionUnionStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool UnionUnionUnionStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool UnionUnionUnionStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; UnionUnionUnionStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),UnionUnionUnionStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(UnionUnionUnionStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || UnionUnionUnionStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -3174,14 +3174,14 @@ void WCharUnionStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool WCharUnionStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool WCharUnionStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; WCharUnionStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),WCharUnionStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(WCharUnionStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || WCharUnionStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); diff --git a/test/unittest/dynamic_types/idl/BasicPubSubTypes.h b/test/unittest/dynamic_types/idl/BasicPubSubTypes.h index 6e2d60c4d57..316565d8e4e 100644 --- a/test/unittest/dynamic_types/idl/BasicPubSubTypes.h +++ b/test/unittest/dynamic_types/idl/BasicPubSubTypes.h @@ -43,7 +43,7 @@ class EnumStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -62,7 +62,7 @@ class AliasStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -81,7 +81,7 @@ class AliasAliasStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -100,7 +100,7 @@ class BoolStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -119,7 +119,7 @@ class OctetStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -138,7 +138,7 @@ class ShortStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -157,7 +157,7 @@ class LongStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -176,7 +176,7 @@ class LongLongStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -195,7 +195,7 @@ class UShortStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -214,7 +214,7 @@ class ULongStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -233,7 +233,7 @@ class ULongLongStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -252,7 +252,7 @@ class FloatStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -271,7 +271,7 @@ class DoubleStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -290,7 +290,7 @@ class LongDoubleStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -309,7 +309,7 @@ class CharStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -328,7 +328,7 @@ class WCharStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -347,7 +347,7 @@ class StringStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -366,7 +366,7 @@ class WStringStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -385,7 +385,7 @@ class LargeStringStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -404,7 +404,7 @@ class LargeWStringStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -423,7 +423,7 @@ class ArraytStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -443,7 +443,7 @@ class ArrayArrayStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -462,7 +462,7 @@ class SequenceStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -481,7 +481,7 @@ class SequenceSequenceStructPubSubType : public eprosima::fastrtps::TopicDataTyp bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -500,7 +500,7 @@ class MapStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -519,7 +519,7 @@ class MapMapStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -538,7 +538,7 @@ class StructStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -557,7 +557,7 @@ class StructStructStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -579,7 +579,7 @@ class SimpleUnionStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -598,7 +598,7 @@ class UnionUnionUnionStructPubSubType : public eprosima::fastrtps::TopicDataType bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -617,7 +617,7 @@ class WCharUnionStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/test/unittest/dynamic_types/idl/TestPubSubTypes.cxx b/test/unittest/dynamic_types/idl/TestPubSubTypes.cxx index 396e3e0a22d..c44886a0e42 100644 --- a/test/unittest/dynamic_types/idl/TestPubSubTypes.cxx +++ b/test/unittest/dynamic_types/idl/TestPubSubTypes.cxx @@ -111,14 +111,14 @@ void BasicStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool BasicStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool BasicStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; BasicStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),BasicStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(BasicStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || BasicStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -218,14 +218,14 @@ void ComplexStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool ComplexStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool ComplexStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; ComplexStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),ComplexStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(ComplexStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || ComplexStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -322,14 +322,14 @@ void CompleteStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool CompleteStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool CompleteStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; CompleteStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),CompleteStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(CompleteStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || CompleteStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); @@ -424,14 +424,14 @@ void KeyedStructPubSubType::deleteData(void* data) delete(reinterpret_cast(data)); } -bool KeyedStructPubSubType::getKey(void *data, InstanceHandle_t* handle) { +bool KeyedStructPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; KeyedStruct* p_type = static_cast(data); eprosima::fastcdr::FastBuffer fastbuffer(reinterpret_cast(m_keyBuffer),KeyedStruct::getKeyMaxCdrSerializedSize()); // Object that manages the raw buffer. eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); // Object that serializes the data. p_type->serializeKey(ser); - if(KeyedStruct::getKeyMaxCdrSerializedSize()>16) { + if(force_md5 || KeyedStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer, static_cast(ser.getSerializedDataLength())); m_md5.finalize(); diff --git a/test/unittest/dynamic_types/idl/TestPubSubTypes.h b/test/unittest/dynamic_types/idl/TestPubSubTypes.h index 7dcc7e411f0..afff346a837 100644 --- a/test/unittest/dynamic_types/idl/TestPubSubTypes.h +++ b/test/unittest/dynamic_types/idl/TestPubSubTypes.h @@ -44,7 +44,7 @@ class BasicStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -68,7 +68,7 @@ class ComplexStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -89,7 +89,7 @@ class CompleteStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; @@ -108,7 +108,7 @@ class KeyedStructPubSubType : public eprosima::fastrtps::TopicDataType { bool serialize(void *data, eprosima::fastrtps::rtps::SerializedPayload_t *payload); bool deserialize(eprosima::fastrtps::rtps::SerializedPayload_t *payload, void *data); std::function getSerializedSizeProvider(void* data); - bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle); + bool getKey(void *data, eprosima::fastrtps::rtps::InstanceHandle_t *ihandle, bool force_md5 = false); void* createData(); void deleteData(void * data); MD5 m_md5; diff --git a/test/unittest/rtps/security/SecurityHandshakeProcessTests.cpp b/test/unittest/rtps/security/SecurityHandshakeProcessTests.cpp index 78929f83116..ea4599dc58e 100644 --- a/test/unittest/rtps/security/SecurityHandshakeProcessTests.cpp +++ b/test/unittest/rtps/security/SecurityHandshakeProcessTests.cpp @@ -80,11 +80,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_not_remote_participa #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -125,11 +125,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_bad_message_class_id #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -184,11 +184,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_not_expecting_reques #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -236,11 +236,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_fail_begin_handshake #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -296,11 +296,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_ok_begin_handshake_r #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -377,11 +377,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_new_change_fail) #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -441,11 +441,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_add_change_fail) #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -543,11 +543,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_pending_handshake_re #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -627,11 +627,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_fail_process_handsha #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -685,11 +685,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_ok_process_handshake #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -760,11 +760,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_process_handshake_re #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -818,11 +818,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_process_handshake_re #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -898,11 +898,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_process_handshake_re #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -948,11 +948,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_bad_related_guid) #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -997,11 +997,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_bad_related_sequence #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -1046,11 +1046,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_fail_process_handsha #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -1104,11 +1104,11 @@ TEST_F(SecurityTest, discovered_participant_process_message_ok_process_handshake #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); diff --git a/test/unittest/rtps/security/SecurityInitializationTests.cpp b/test/unittest/rtps/security/SecurityInitializationTests.cpp index 37cff010ab4..41ff0f7d928 100644 --- a/test/unittest/rtps/security/SecurityInitializationTests.cpp +++ b/test/unittest/rtps/security/SecurityInitializationTests.cpp @@ -43,10 +43,11 @@ TEST_F(SecurityTest, initialization_register_local_participant_error) { DefaultValue::Set(pattr); DefaultValue::Set(guid); + DefaultValue::Set(security_attributes_); EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(1). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(nullptr)); ASSERT_FALSE(manager_.init(security_attributes_, participant_properties_)); @@ -56,11 +57,12 @@ TEST_F(SecurityTest, initialization_fail_participant_stateless_message_writer) { DefaultValue::Set(pattr); DefaultValue::Set(guid); + DefaultValue::Set(security_attributes_); MockParticipantCryptoHandle local_participant_crypto_handle; EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(1). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(&local_participant_crypto_handle)); EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, unregister_participant(&local_participant_crypto_handle,_)).Times(1). WillOnce(Return(true)); @@ -74,12 +76,13 @@ TEST_F(SecurityTest, initialization_fail_participant_stateless_message_reader) { DefaultValue::Set(pattr); DefaultValue::Set(guid); + DefaultValue::Set(security_attributes_); MockParticipantCryptoHandle local_participant_crypto_handle; NiceMock* stateless_writer = new NiceMock(&participant_); EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(1). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(&local_participant_crypto_handle)); EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, unregister_participant(&local_participant_crypto_handle,_)).Times(1). WillOnce(Return(true)); @@ -95,13 +98,14 @@ TEST_F(SecurityTest, initialization_fail_participant_volatile_message_writer) { DefaultValue::Set(pattr); DefaultValue::Set(guid); + DefaultValue::Set(security_attributes_); MockParticipantCryptoHandle local_participant_crypto_handle; NiceMock* stateless_writer = new NiceMock(&participant_); NiceMock* stateless_reader = new NiceMock(); EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(1). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(&local_participant_crypto_handle)); EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, unregister_participant(&local_participant_crypto_handle,_)).Times(1). WillOnce(Return(true)); @@ -118,6 +122,7 @@ TEST_F(SecurityTest, initialization_fail_participant_volatile_message_reader) { DefaultValue::Set(pattr); DefaultValue::Set(guid); + DefaultValue::Set(security_attributes_); MockParticipantCryptoHandle local_participant_crypto_handle; NiceMock* stateless_writer = new NiceMock(&participant_); NiceMock* stateless_reader = new NiceMock(); @@ -125,7 +130,7 @@ TEST_F(SecurityTest, initialization_fail_participant_volatile_message_reader) EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(1). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(&local_participant_crypto_handle)); EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, unregister_participant(&local_participant_crypto_handle,_)).Times(1). WillOnce(Return(true)); @@ -143,6 +148,7 @@ TEST_F(SecurityTest, initialization_auth_retry) { DefaultValue::Set(pattr); DefaultValue::Set(guid); + DefaultValue::Set(security_attributes_); MockParticipantCryptoHandle local_participant_crypto_handle; NiceMock* stateless_writer = new NiceMock(&participant_); NiceMock* stateless_reader = new NiceMock(); @@ -152,7 +158,7 @@ TEST_F(SecurityTest, initialization_auth_retry) EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(2). WillOnce(Return(ValidationResult_t::VALIDATION_PENDING_RETRY)). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(&local_participant_crypto_handle)); EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, unregister_participant(&local_participant_crypto_handle,_)).Times(1). WillOnce(Return(true)); @@ -175,5 +181,6 @@ TEST_F(SecurityTest, initialization_ok) WillOnce(Return(true)); initialization_ok(); + } diff --git a/test/unittest/rtps/security/SecurityTests.hpp b/test/unittest/rtps/security/SecurityTests.hpp index ae9223986d2..cdd4130627a 100644 --- a/test/unittest/rtps/security/SecurityTests.hpp +++ b/test/unittest/rtps/security/SecurityTests.hpp @@ -15,17 +15,17 @@ #ifndef __TEST_UNITTEST_RTPS_SECURITY_SECURITYTESTS_HPP__ #define __TEST_UNITTEST_RTPS_SECURITY_SECURITYTESTS_HPP__ +#include #include #include #include #include #include +#include #include #include -#include #include #include -#include #include #include #include @@ -33,7 +33,7 @@ #include using namespace eprosima::fastrtps::rtps; -using namespace security; +using namespace eprosima::fastrtps::rtps::security; using namespace ::testing; class MockIdentity @@ -111,6 +111,7 @@ class SecurityTest : public ::testing::Test ::testing::DefaultValue::Set(pattr); ::testing::DefaultValue::Set(guid); ::testing::DefaultValue::Set(default_cdr_message); + ::testing::DefaultValue::Set(security_attributes_); stateless_writer_ = new ::testing::NiceMock(&participant_); stateless_reader_ = new ::testing::NiceMock(); volatile_writer_ = new ::testing::NiceMock(&participant_); @@ -118,7 +119,7 @@ class SecurityTest : public ::testing::Test EXPECT_CALL(*auth_plugin_, validate_local_identity(_,_,_,_,_,_)).Times(1). WillOnce(DoAll(SetArgPointee<0>(&local_identity_handle_), Return(ValidationResult_t::VALIDATION_OK))); - EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_)).Times(1). + EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, register_local_participant(Ref(local_identity_handle_),_,_,_,_)).Times(1). WillOnce(Return(&local_participant_crypto_handle_)); EXPECT_CALL(crypto_plugin_->cryptokeyfactory_, unregister_participant(&local_participant_crypto_handle_,_)).Times(1). WillOnce(Return(true)); @@ -209,11 +210,11 @@ class SecurityTest : public ::testing::Test #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); @@ -273,11 +274,11 @@ class SecurityTest : public ::testing::Test #if __BIG_ENDIAN__ aux_msg.msg_endian = BIGEND; change->serializedPayload.encapsulation = PL_CDR_BE; - CDRMessage::addOctet(&aux_msg, PL_CDR_BE); + CDRMessage::addOctet(&aux_msg, CDR_BE); #else aux_msg.msg_endian = LITTLEEND; change->serializedPayload.encapsulation = PL_CDR_LE; - CDRMessage::addOctet(&aux_msg, PL_CDR_LE); + CDRMessage::addOctet(&aux_msg, CDR_LE); #endif CDRMessage::addUInt16(&aux_msg, 0); diff --git a/test/unittest/security/authentication/AuthenticationPluginTests.hpp b/test/unittest/security/authentication/AuthenticationPluginTests.hpp index 22eb69c6a4b..7ab309068c3 100644 --- a/test/unittest/security/authentication/AuthenticationPluginTests.hpp +++ b/test/unittest/security/authentication/AuthenticationPluginTests.hpp @@ -197,7 +197,7 @@ TEST_F(AuthenticationPluginTest, handshake_process_ok) eprosima::fastrtps::ParameterList_t parameter_list1 = participant_data1.AllQostoParameterList(); eprosima::fastrtps::rtps::CDRMessage_t auxMsg; auxMsg.msg_endian = eprosima::fastrtps::rtps::BIGEND; - ASSERT_TRUE(eprosima::fastrtps::ParameterList::writeParameterListToCDRMsg(&auxMsg, ¶meter_list1, true)); + ASSERT_TRUE(eprosima::fastrtps::ParameterList::writeParameterListToCDRMsg(&auxMsg, ¶meter_list1, false)); result = plugin.begin_handshake_request(&handshake_handle, &handshake_message, @@ -220,7 +220,7 @@ TEST_F(AuthenticationPluginTest, handshake_process_ok) auxMsg.length = 0; auxMsg.pos = 0; - ASSERT_TRUE(eprosima::fastrtps::ParameterList::writeParameterListToCDRMsg(&auxMsg, ¶meter_list2, true)); + ASSERT_TRUE(eprosima::fastrtps::ParameterList::writeParameterListToCDRMsg(&auxMsg, ¶meter_list2, false)); result = plugin.begin_handshake_reply(&handshake_handle_reply, &handshake_message_reply, diff --git a/test/unittest/security/authentication/BuiltinPKIDHTests.cpp b/test/unittest/security/authentication/BuiltinPKIDHTests.cpp index 3b2ece46ed3..2498d3e9a85 100644 --- a/test/unittest/security/authentication/BuiltinPKIDHTests.cpp +++ b/test/unittest/security/authentication/BuiltinPKIDHTests.cpp @@ -68,6 +68,7 @@ IdentityToken AuthenticationPluginTest::generate_remote_identity_token_ok(const { IdentityToken token; const PKIIdentityHandle& h = PKIIdentityHandle::narrow(local_identity_handle); + token.class_id("DDS:Auth:PKI-DH:1.0"); Property property; @@ -148,7 +149,7 @@ void AuthenticationPluginTest::check_handshake_request_message(const HandshakeHa // TODO(Ricardo) Have to add +3 because current serialization add alignment bytes at the end. CDRMessage_t cdrmessage(static_cast(BinaryPropertyHelper::serialized_size(message.binary_properties())+ 3)); cdrmessage.msg_endian = BIGEND; - CDRMessage::addBinaryPropertySeq(&cdrmessage, message.binary_properties(), "hash_c1"); + CDRMessage::addBinaryPropertySeq(&cdrmessage, message.binary_properties(), "c.",false); unsigned char md[SHA256_DIGEST_LENGTH]; ASSERT_TRUE(EVP_Digest(cdrmessage.buffer, cdrmessage.length, md, NULL, EVP_sha256(), NULL)); ASSERT_TRUE(memcmp(md, hash_c1->data(), SHA256_DIGEST_LENGTH) == 0); @@ -158,19 +159,7 @@ void AuthenticationPluginTest::check_handshake_request_message(const HandshakeHa DH* dh = EVP_PKEY_get1_DH(handshake_handle->dhkeys_); ASSERT_TRUE(dh != nullptr); const unsigned char* pointer = dh1->data(); - uint32_t length = 0; -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - pointer += 4; + uint32_t length = dh1->size(); BIGNUM* bn = BN_new(); ASSERT_TRUE(BN_bin2bn(pointer, length, bn) != nullptr); @@ -184,38 +173,6 @@ void AuthenticationPluginTest::check_handshake_request_message(const HandshakeHa const BIGNUM* g = dh->g; #endif - ASSERT_TRUE(BN_cmp(p, bn) == 0); - pointer += length; - pointer += alignment(pointer - dh1->data(), 4); -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - pointer += 4; - ASSERT_TRUE(BN_bin2bn(pointer, length, bn) != nullptr); - ASSERT_TRUE(BN_cmp(g, bn) == 0); - pointer += length; - pointer += alignment(pointer - dh1->data(), 4); -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - pointer += 4; - ASSERT_TRUE(BN_bin2bn(pointer, length, bn) != nullptr); int check_result; ASSERT_TRUE(DH_check_pub_key(dh, bn, &check_result)); ASSERT_TRUE(!check_result); @@ -261,7 +218,7 @@ void AuthenticationPluginTest::check_handshake_reply_message(const HandshakeHand // TODO(Ricardo) Have to add +3 because current serialization add alignment bytes at the end. CDRMessage_t cdrmessage(static_cast(BinaryPropertyHelper::serialized_size(message.binary_properties())+ 3)); cdrmessage.msg_endian = BIGEND; - CDRMessage::addBinaryPropertySeq(&cdrmessage, message.binary_properties(), "hash_c2"); + CDRMessage::addBinaryPropertySeq(&cdrmessage, message.binary_properties(), "c.",false); unsigned char md[SHA256_DIGEST_LENGTH]; ASSERT_TRUE(EVP_Digest(cdrmessage.buffer, cdrmessage.length, md, NULL, EVP_sha256(), NULL)); ASSERT_TRUE(memcmp(md, hash_c2->data(), SHA256_DIGEST_LENGTH) == 0); @@ -271,19 +228,7 @@ void AuthenticationPluginTest::check_handshake_reply_message(const HandshakeHand DH* dh = EVP_PKEY_get1_DH(handshake_handle->dhkeys_); ASSERT_TRUE(dh != nullptr); const unsigned char* pointer = dh2->data(); - uint32_t length = 0; -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - pointer += 4; + uint32_t length = dh2->size(); BIGNUM* bn = BN_new(); ASSERT_TRUE(BN_bin2bn(pointer, length, bn) != nullptr); @@ -297,38 +242,6 @@ void AuthenticationPluginTest::check_handshake_reply_message(const HandshakeHand const BIGNUM* g = dh->g; #endif - ASSERT_TRUE(BN_cmp(p, bn) == 0); - pointer += length; - pointer += alignment(pointer - dh2->data(), 4); -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - pointer += 4; - ASSERT_TRUE(BN_bin2bn(pointer, length, bn) != nullptr); - ASSERT_TRUE(BN_cmp(g, bn) == 0); - pointer += length; - pointer += alignment(pointer - dh2->data(), 4); -#if __BIG_ENDIAN__ - ((char*)&length)[0] = pointer[0]; - ((char*)&length)[1] = pointer[1]; - ((char*)&length)[2] = pointer[2]; - ((char*)&length)[3] = pointer[3]; -#else - ((char*)&length)[0] = pointer[3]; - ((char*)&length)[1] = pointer[2]; - ((char*)&length)[2] = pointer[1]; - ((char*)&length)[3] = pointer[0]; -#endif - pointer += 4; - ASSERT_TRUE(BN_bin2bn(pointer, length, bn) != nullptr); int check_result; ASSERT_TRUE(DH_check_pub_key(dh, bn, &check_result)); ASSERT_TRUE(!check_result); @@ -374,7 +287,7 @@ void AuthenticationPluginTest::check_handshake_reply_message(const HandshakeHand //add dh1 CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property(message, "dh1")); //add hash_c1 - CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property(message, "hash_c1")); + CDRMessage::addBinaryProperty(&cdrmessage2, *DataHolderHelper::find_binary_property(message, "hash_c1"), false); EVP_MD_CTX* ctx = #if IS_OPENSSL_1_1 EVP_MD_CTX_new(); @@ -455,7 +368,7 @@ void AuthenticationPluginTest::check_handshake_final_message(const HandshakeHand //add dh2 CDRMessage::addBinaryProperty(&cdrmessage, *DataHolderHelper::find_binary_property(message, "dh2")); //add hash_c2 - CDRMessage::addBinaryProperty(&cdrmessage, *DataHolderHelper::find_binary_property(message, "hash_c2")); + CDRMessage::addBinaryProperty(&cdrmessage, *DataHolderHelper::find_binary_property(message, "hash_c2"), false); EVP_MD_CTX* ctx = #if IS_OPENSSL_1_1 EVP_MD_CTX_new(); diff --git a/test/unittest/security/cryptography/CryptographyPluginTests.hpp b/test/unittest/security/cryptography/CryptographyPluginTests.hpp index 94b36506045..8c099db4f32 100644 --- a/test/unittest/security/cryptography/CryptographyPluginTests.hpp +++ b/test/unittest/security/cryptography/CryptographyPluginTests.hpp @@ -54,10 +54,15 @@ TEST_F(CryptographyPluginTest, factory_CreateLocalParticipantHandle) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *target = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *target = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); ASSERT_TRUE(target != nullptr); eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle& local_participant = eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle::narrow(*target); @@ -66,9 +71,9 @@ TEST_F(CryptographyPluginTest, factory_CreateLocalParticipantHandle) ASSERT_GT(local_participant->Participant2ParticipantKeyMaterial.size(), 0ul); ASSERT_GT(local_participant->Participant2ParticipantKxKeyMaterial.size(), 0ul); - ASSERT_TRUE( (local_participant->ParticipantKeyMaterial.transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) ); - ASSERT_TRUE( (local_participant->Participant2ParticipantKeyMaterial.at(0).transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) ); - ASSERT_TRUE( (local_participant->Participant2ParticipantKxKeyMaterial.at(0).transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) ); + ASSERT_TRUE( (local_participant->ParticipantKeyMaterial.transformation_kind == eprosima::fastrtps::rtps::security::c_transfrom_kind_aes256_gcm) ); + ASSERT_TRUE( (local_participant->Participant2ParticipantKeyMaterial.at(0).transformation_kind == eprosima::fastrtps::rtps::security::c_transfrom_kind_aes256_gcm) ); + ASSERT_TRUE( (local_participant->Participant2ParticipantKxKeyMaterial.at(0).transformation_kind == eprosima::fastrtps::rtps::security::c_transfrom_kind_aes256_gcm) ); ASSERT_FALSE( std::all_of(local_participant->ParticipantKeyMaterial.master_salt.begin(),local_participant->ParticipantKeyMaterial.master_salt.end(), [](uint8_t i){return i==0;}) ); ASSERT_FALSE( std::all_of(local_participant->Participant2ParticipantKeyMaterial.at(0).master_salt.begin(),local_participant->Participant2ParticipantKeyMaterial.at(0).master_salt.end(), [](uint8_t i){return i==0;}) ); @@ -97,11 +102,16 @@ TEST_F(CryptographyPluginTest, factory_RegisterRemoteParticipant) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *local = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *local = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); ASSERT_TRUE(local != nullptr); @@ -110,8 +120,8 @@ TEST_F(CryptographyPluginTest, factory_RegisterRemoteParticipant) //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -123,7 +133,7 @@ TEST_F(CryptographyPluginTest, factory_RegisterRemoteParticipant) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -144,7 +154,7 @@ TEST_F(CryptographyPluginTest, factory_RegisterRemoteParticipant) ASSERT_TRUE(remote_participant_A->Participant2ParticipantKxKeyMaterial.size() == 1); ASSERT_TRUE(remote_participant_B->Participant2ParticipantKxKeyMaterial.size() == 1); //Check that both remoteKeysMaterials have unique IDS (keys are the same since they use the same source material - ASSERT_TRUE(remote_participant_A->Participant2ParticipantKeyMaterial.at(0).sender_key_id != remote_participant_B->Participant2ParticipantKeyMaterial.at(0).sender_key_id); + ASSERT_TRUE(remote_participant_A->Participant2ParticipantKeyMaterial.at(0).sender_key_id == remote_participant_B->Participant2ParticipantKeyMaterial.at(0).sender_key_id); //KxKeys should be the same since they derive from the same Shared Secret although Keys should not ASSERT_TRUE(remote_participant_A->Participant2ParticipantKeyMaterial.at(0).master_receiver_specific_key != remote_participant_B->Participant2ParticipantKeyMaterial.at(0).master_receiver_specific_key); ASSERT_TRUE(remote_participant_A->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key == remote_participant_B->Participant2ParticipantKxKeyMaterial.at(0).master_sender_key); @@ -163,16 +173,22 @@ TEST_F(CryptographyPluginTest, exchange_CDRSerializenDeserialize){ eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle& Participant_A = eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle::narrow(*ParticipantA); eprosima::fastrtps::rtps::security::KeyMaterial_AES_GCM_GMAC base = Participant_A->ParticipantKeyMaterial; std::vector serialized = CryptoPlugin->keyexchange()->KeyMaterialCDRSerialize(base); - eprosima::fastrtps::rtps::security::KeyMaterial_AES_GCM_GMAC result = CryptoPlugin->keyexchange()->KeyMaterialCDRDeserialize(&serialized); + eprosima::fastrtps::rtps::security::KeyMaterial_AES_GCM_GMAC result; + CryptoPlugin->keyexchange()->KeyMaterialCDRDeserialize(result, &serialized); ASSERT_TRUE( (base.transformation_kind == result.transformation_kind) & (base.master_salt == result.master_salt) & @@ -195,15 +211,20 @@ TEST_F(CryptographyPluginTest, exchange_ParticipantCryptoTokens) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -215,15 +236,15 @@ TEST_F(CryptographyPluginTest, exchange_ParticipantCryptoTokens) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); (*shared_secret)->data_.push_back(binary_data); //Create ParticipantA and ParticipantB - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantB = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantB = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); ASSERT_TRUE( (ParticipantA != nullptr) & (ParticipantB != nullptr) ); @@ -275,15 +296,20 @@ TEST_F(CryptographyPluginTest, transform_RTPSMessage) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -295,15 +321,15 @@ TEST_F(CryptographyPluginTest, transform_RTPSMessage) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); (*shared_secret)->data_.push_back(binary_data); //Create ParticipantA and ParticipantB - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantB = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *ParticipantB = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); ASSERT_TRUE( (ParticipantA != nullptr) & (ParticipantB != nullptr) ); @@ -368,16 +394,16 @@ TEST_F(CryptographyPluginTest, transform_RTPSMessage) //Now lets do the same with 256GCM //Fill prop_handle with info about the new mode we want eprosima::fastrtps::rtps::Property prop1; - prop1.name("dds.sec.crypto.cryptotransformkind"); - prop1.value("AES256_GMAC"); + prop1.name("dds.sec.crypto.keysize"); + prop1.value("256"); prop_handle.push_back(prop1); eprosima::fastrtps::rtps::Property prop2; prop2.name("dds.sec.crypto.maxblockspersession"); prop2.value("16"); prop_handle.push_back(prop2); //Create ParticipantA and ParticipantB - ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); - ParticipantB = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,exception); + ParticipantA = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); + ParticipantB = CryptoPlugin->keyfactory()->register_local_participant(*i_handle,*perm_handle,prop_handle,part_sec_attr,exception); //Register a remote for both Participants ParticipantA_remote =CryptoPlugin->keyfactory()->register_matched_remote_participant(*ParticipantA,*i_handle,*perm_handle,*shared_secret, exception); @@ -423,27 +449,39 @@ TEST_F(CryptographyPluginTest, factory_CreateLocalWriterHandle) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatawriterCryptoHandle *target = CryptoPlugin->keyfactory()->register_local_datawriter(*participant, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::DatawriterCryptoHandle *target = CryptoPlugin->keyfactory()->register_local_datawriter(*participant, prop_handle, sec_attrs, exception); ASSERT_TRUE(target != nullptr); eprosima::fastrtps::rtps::security::AESGCMGMAC_WriterCryptoHandle& local_writer = eprosima::fastrtps::rtps::security::AESGCMGMAC_WriterCryptoHandle::narrow(*target); ASSERT_TRUE(!local_writer.nil()); ASSERT_TRUE(local_writer->Entity2RemoteKeyMaterial.empty()); - ASSERT_TRUE( (local_writer->EntityKeyMaterial.transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) ); + ASSERT_TRUE( (local_writer->EntityKeyMaterial.at(0).transformation_kind == eprosima::fastrtps::rtps::security::c_transfrom_kind_aes128_gcm) ); - ASSERT_FALSE( std::all_of(local_writer->EntityKeyMaterial.master_salt.begin(),local_writer->EntityKeyMaterial.master_salt.end(), [](uint8_t i){return i==0;}) ); + ASSERT_FALSE( std::all_of(local_writer->EntityKeyMaterial.at(0).master_salt.begin(),local_writer->EntityKeyMaterial.at(0).master_salt.end(), [](uint8_t i){return i==0;}) ); - ASSERT_FALSE( std::all_of(local_writer->EntityKeyMaterial.master_sender_key.begin(),local_writer->EntityKeyMaterial.master_sender_key.end(), [](uint8_t i){return i==0;}) ); + ASSERT_FALSE( std::all_of(local_writer->EntityKeyMaterial.at(0).master_sender_key.begin(),local_writer->EntityKeyMaterial.at(0).master_sender_key.end(), [](uint8_t i){return i==0;}) ); - ASSERT_FALSE( std::any_of(local_writer->EntityKeyMaterial.receiver_specific_key_id.begin(),local_writer->EntityKeyMaterial.receiver_specific_key_id.end(), [](uint8_t i){return i!=0;}) ); + ASSERT_FALSE( std::any_of(local_writer->EntityKeyMaterial.at(0).receiver_specific_key_id.begin(),local_writer->EntityKeyMaterial.at(0).receiver_specific_key_id.end(), [](uint8_t i){return i!=0;}) ); - ASSERT_FALSE( std::any_of(local_writer->EntityKeyMaterial.master_receiver_specific_key.begin(),local_writer->EntityKeyMaterial.master_receiver_specific_key.end(), [](uint8_t i){return i!=0;}) ); + ASSERT_FALSE( std::any_of(local_writer->EntityKeyMaterial.at(0).master_receiver_specific_key.begin(),local_writer->EntityKeyMaterial.at(0).master_receiver_specific_key.end(), [](uint8_t i){return i!=0;}) ); delete i_handle; delete perm_handle; @@ -460,27 +498,39 @@ TEST_F(CryptographyPluginTest, factory_CreateLocalReaderHandle) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *target = CryptoPlugin->keyfactory()->register_local_datareader(*participant, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *target = CryptoPlugin->keyfactory()->register_local_datareader(*participant, prop_handle, sec_attrs, exception); ASSERT_TRUE(target != nullptr); eprosima::fastrtps::rtps::security::AESGCMGMAC_ReaderCryptoHandle& local_reader = eprosima::fastrtps::rtps::security::AESGCMGMAC_ReaderCryptoHandle::narrow(*target); ASSERT_TRUE(!local_reader.nil()); ASSERT_TRUE(local_reader->Entity2RemoteKeyMaterial.empty()); - ASSERT_TRUE( (local_reader->EntityKeyMaterial.transformation_kind == std::array{CRYPTO_TRANSFORMATION_KIND_AES128_GCM}) ); + ASSERT_TRUE( (local_reader->EntityKeyMaterial.at(0).transformation_kind == eprosima::fastrtps::rtps::security::c_transfrom_kind_aes128_gcm) ); - ASSERT_FALSE( std::all_of(local_reader->EntityKeyMaterial.master_salt.begin(),local_reader->EntityKeyMaterial.master_salt.end(), [](uint8_t i){return i==0;}) ); + ASSERT_FALSE( std::all_of(local_reader->EntityKeyMaterial.at(0).master_salt.begin(),local_reader->EntityKeyMaterial.at(0).master_salt.end(), [](uint8_t i){return i==0;}) ); - ASSERT_FALSE( std::all_of(local_reader->EntityKeyMaterial.master_sender_key.begin(),local_reader->EntityKeyMaterial.master_sender_key.end(), [](uint8_t i){return i==0;}) ); + ASSERT_FALSE( std::all_of(local_reader->EntityKeyMaterial.at(0).master_sender_key.begin(),local_reader->EntityKeyMaterial.at(0).master_sender_key.end(), [](uint8_t i){return i==0;}) ); - ASSERT_FALSE( std::any_of(local_reader->EntityKeyMaterial.receiver_specific_key_id.begin(),local_reader->EntityKeyMaterial.receiver_specific_key_id.end(), [](uint8_t i){return i!=0;}) ); + ASSERT_FALSE( std::any_of(local_reader->EntityKeyMaterial.at(0).receiver_specific_key_id.begin(),local_reader->EntityKeyMaterial.at(0).receiver_specific_key_id.end(), [](uint8_t i){return i!=0;}) ); - ASSERT_FALSE( std::any_of(local_reader->EntityKeyMaterial.master_receiver_specific_key.begin(),local_reader->EntityKeyMaterial.master_receiver_specific_key.end(), [](uint8_t i){return i!=0;}) ); + ASSERT_FALSE( std::any_of(local_reader->EntityKeyMaterial.at(0).master_receiver_specific_key.begin(),local_reader->EntityKeyMaterial.at(0).master_receiver_specific_key.end(), [](uint8_t i){return i!=0;}) ); delete i_handle; delete perm_handle; @@ -497,21 +547,33 @@ TEST_F(CryptographyPluginTest, factory_RegisterRemoteReaderWriter) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -523,7 +585,7 @@ TEST_F(CryptographyPluginTest, factory_RegisterRemoteReaderWriter) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -571,21 +633,33 @@ TEST_F(CryptographyPluginTest, exchange_ReaderWriterCryptoTokens) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -597,7 +671,7 @@ TEST_F(CryptographyPluginTest, exchange_ReaderWriterCryptoTokens) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -677,21 +751,34 @@ TEST_F(CryptographyPluginTest, transform_SerializedPayload) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = true; + sec_attrs.is_key_protected = true; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_PAYLOAD_ENCRYPTED; - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -703,7 +790,7 @@ TEST_F(CryptographyPluginTest, transform_SerializedPayload) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -767,19 +854,19 @@ TEST_F(CryptographyPluginTest, transform_SerializedPayload) //Lets do it with the 256 version eprosima::fastrtps::rtps::Property prop1; - prop1.name("dds.sec.crypto.cryptotransformkind"); - prop1.value("AES256_GCM"); + prop1.name("dds.sec.crypto.keysize"); + prop1.value("256"); prop_handle.push_back(prop1); eprosima::fastrtps::rtps::Property prop2; prop2.name("dds.sec.crypto.maxblockspersession"); prop2.value("16"); prop_handle.push_back(prop2); - participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); - reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Register a remote for both Participants ParticipantA_remote =CryptoPlugin->keyfactory()->register_matched_remote_participant(*participant_A,*i_handle,*perm_handle,*shared_secret, exception); @@ -836,21 +923,33 @@ TEST_F(CryptographyPluginTest, transform_Writer_Submesage) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -862,7 +961,7 @@ TEST_F(CryptographyPluginTest, transform_Writer_Submesage) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -932,19 +1031,19 @@ TEST_F(CryptographyPluginTest, transform_Writer_Submesage) //Test the GCM256 version eprosima::fastrtps::rtps::Property prop1; - prop1.name("dds.sec.crypto.cryptotransformkind"); - prop1.value("AES256_GCM"); + prop1.name("dds.sec.crypto.keysize"); + prop1.value("256"); prop_handle.push_back(prop1); eprosima::fastrtps::rtps::Property prop2; prop2.name("dds.sec.crypto.maxblockspersession"); prop2.value("16"); prop_handle.push_back(prop2); - participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); - reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Register a remote for both Participants ParticipantA_remote =CryptoPlugin->keyfactory()->register_matched_remote_participant(*participant_A,*i_handle,*perm_handle,*shared_secret, exception); @@ -1008,21 +1107,33 @@ TEST_F(CryptographyPluginTest, transform_Reader_Submessage) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -1034,7 +1145,7 @@ TEST_F(CryptographyPluginTest, transform_Reader_Submessage) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -1103,19 +1214,19 @@ TEST_F(CryptographyPluginTest, transform_Reader_Submessage) //Test the GCM256 version eprosima::fastrtps::rtps::Property prop1; - prop1.name("dds.sec.crypto.cryptotransformkind"); - prop1.value("AES256_GCM"); + prop1.name("dds.sec.crypto.keysize"); + prop1.value("256"); prop_handle.push_back(prop1); eprosima::fastrtps::rtps::Property prop2; prop2.name("dds.sec.crypto.maxblockspersession"); prop2.value("16"); prop_handle.push_back(prop2); - participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); - reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, exception); - writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, exception); + reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_A, prop_handle, sec_attrs, exception); + writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_B, prop_handle, sec_attrs, exception); //Register a remote for both Participants ParticipantA_remote =CryptoPlugin->keyfactory()->register_matched_remote_participant(*participant_A,*i_handle,*perm_handle,*shared_secret, exception); @@ -1179,21 +1290,33 @@ TEST_F(CryptographyPluginTest, transform_preprocess_secure_submessage) eprosima::fastrtps::rtps::security::PKIIdentityHandle* i_handle = new eprosima::fastrtps::rtps::security::PKIIdentityHandle(); eprosima::fastrtps::rtps::security::AccessPermissionsHandle* perm_handle = new eprosima::fastrtps::rtps::security::AccessPermissionsHandle(); eprosima::fastrtps::rtps::PropertySeq prop_handle; + eprosima::fastrtps::rtps::security::ParticipantSecurityAttributes part_sec_attr; + eprosima::fastrtps::rtps::security::EndpointSecurityAttributes sec_attrs; eprosima::fastrtps::rtps::security::SharedSecretHandle* shared_secret = new eprosima::fastrtps::rtps::security::SharedSecretHandle(); eprosima::fastrtps::rtps::security::SecurityException exception; - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); - eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, exception); + part_sec_attr.is_rtps_protected = true; + part_sec_attr.plugin_participant_attributes = PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ENCRYPTED | + PLUGIN_PARTICIPANT_SECURITY_ATTRIBUTES_FLAG_IS_RTPS_ORIGIN_AUTHENTICATED; + + sec_attrs.is_submessage_protected = true; + sec_attrs.is_payload_protected = false; + sec_attrs.is_key_protected = false; + sec_attrs.plugin_endpoint_attributes = PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ENCRYPTED | + PLUGIN_ENDPOINT_SECURITY_ATTRIBUTES_FLAG_IS_SUBMESSAGE_ORIGIN_AUTHENTICATED; + + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_A = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); + eprosima::fastrtps::rtps::security::ParticipantCryptoHandle *participant_B = CryptoPlugin->keyfactory()->register_local_participant(*i_handle, *perm_handle, prop_handle, part_sec_attr, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_B, prop_handle, exception); - eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_A, prop_handle, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *reader = CryptoPlugin->keyfactory()->register_local_datareader(*participant_B, prop_handle, sec_attrs, exception); + eprosima::fastrtps::rtps::security::DatareaderCryptoHandle *writer = CryptoPlugin->keyfactory()->register_local_datawriter(*participant_A, prop_handle, sec_attrs, exception); //Fill shared secret with dummy values std::vector dummy_data, challenge_1, challenge_2; eprosima::fastrtps::rtps::security::SharedSecret::BinaryData binary_data; - challenge_1.reserve(8); - challenge_2.reserve(8); + challenge_1.resize(8); + challenge_2.resize(8); RAND_bytes(challenge_1.data(),8); binary_data.name("Challenge1"); @@ -1205,7 +1328,7 @@ TEST_F(CryptographyPluginTest, transform_preprocess_secure_submessage) binary_data.value(challenge_2); (*shared_secret)->data_.push_back(binary_data); - dummy_data.reserve(32); + dummy_data.resize(32); RAND_bytes(dummy_data.data(),32); binary_data.name("SharedSecret"); binary_data.value(dummy_data); @@ -1245,10 +1368,10 @@ TEST_F(CryptographyPluginTest, transform_preprocess_secure_submessage) eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle& P_B = eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle::narrow(*ParticipantB_remote); //Owner of a Reader eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle& P_A = eprosima::fastrtps::rtps::security::AESGCMGMAC_ParticipantCryptoHandle::narrow(*ParticipantA_remote); //Owner of a Writer - ASSERT_TRUE( P_A->Readers.size() == 1); - ASSERT_TRUE( P_A->Writers.size() == 0); - ASSERT_TRUE( P_B->Writers.size() == 1); - ASSERT_TRUE( P_B->Readers.size() == 0); + ASSERT_TRUE( P_A->Readers.size() == 2); + ASSERT_TRUE( P_A->Writers.size() == 1); + ASSERT_TRUE( P_B->Writers.size() == 2); + ASSERT_TRUE( P_B->Readers.size() == 1); //Perform sample message exchange eprosima::fastrtps::rtps::CDRMessage_t plain_payload; diff --git a/utils/metaTest/types/MetaTestTypesPubSubType.cpp b/utils/metaTest/types/MetaTestTypesPubSubType.cpp index f2ed3a508fe..60fd7e1c474 100644 --- a/utils/metaTest/types/MetaTestTypesPubSubType.cpp +++ b/utils/metaTest/types/MetaTestTypesPubSubType.cpp @@ -25,7 +25,7 @@ #include "MetaTestTypesPubSubType.h" -MetaTestTypesPubSubType::MetaTestTypesPubSubType() +MetaTestTypesPubSubType::MetaTestTypesPubSubType() { setName("MetaTestType"); m_typeSize = (uint32_t)MetaTestType::getMaxCdrSerializedSize(); @@ -33,27 +33,27 @@ MetaTestTypesPubSubType::MetaTestTypesPubSubType() m_keyBuffer = (unsigned char*)malloc(MetaTestType::getKeyMaxCdrSerializedSize()>16 ? MetaTestType::getKeyMaxCdrSerializedSize() : 16); } -MetaTestTypesPubSubType::~MetaTestTypesPubSubType() +MetaTestTypesPubSubType::~MetaTestTypesPubSubType() { if(m_keyBuffer!=nullptr) delete(m_keyBuffer); } -bool MetaTestTypesPubSubType::serialize(void *data, SerializedPayload_t *payload) +bool MetaTestTypesPubSubType::serialize(void *data, SerializedPayload_t *payload) { MetaTestType *p_type = (MetaTestType*) data; - + // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer((char*) payload->data, payload->max_size); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer,eprosima::fastcdr::Cdr::LITTLE_ENDIANNESS); //Select the correct endianess - payload->encapsulation = CDR_LE; + payload->encapsulation = CDR_LE; // Serialize the object: p_type->serialize(ser); //Get the serialized length payload->length = (uint16_t)ser.getSerializedDataLength(); - + return true; } @@ -83,7 +83,7 @@ void MetaTestTypesPubSubType::deleteData(void* data) delete((MetaTestType*)data); } -bool MetaTestTypesPubSubType::getKey(void *data, InstanceHandle_t* handle) +bool MetaTestTypesPubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; @@ -96,7 +96,7 @@ bool MetaTestTypesPubSubType::getKey(void *data, InstanceHandle_t* handle) eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); p_type->serializeKey(ser); - if(MetaTestType::getKeyMaxCdrSerializedSize()>16) + if(force_md5 || MetaTestType::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); @@ -113,6 +113,6 @@ bool MetaTestTypesPubSubType::getKey(void *data, InstanceHandle_t* handle) handle->value[i] = m_keyBuffer[i]; } } - + return true; } diff --git a/utils/outdatedTests/SimplePublisherSubscriber/SimplePubSubType.cxx b/utils/outdatedTests/SimplePublisherSubscriber/SimplePubSubType.cxx index aa0402dd2d0..98281294af7 100644 --- a/utils/outdatedTests/SimplePublisherSubscriber/SimplePubSubType.cxx +++ b/utils/outdatedTests/SimplePublisherSubscriber/SimplePubSubType.cxx @@ -25,7 +25,7 @@ #include "SimplePubSubType.h" -SimplePubSubType::SimplePubSubType() +SimplePubSubType::SimplePubSubType() { m_topicDataTypeName = std::string("SimpleStructPubSubType"); m_typeSize = (uint32_t)SimpleStruct::getMaxCdrSerializedSize(); @@ -33,27 +33,27 @@ SimplePubSubType::SimplePubSubType() m_keyBuffer = (unsigned char*)malloc(SimpleStruct::getKeyMaxCdrSerializedSize()>16 ? SimpleStruct::getKeyMaxCdrSerializedSize() : 16); } -SimplePubSubType::~SimplePubSubType() +SimplePubSubType::~SimplePubSubType() { if(m_keyBuffer!=NULL) delete(m_keyBuffer); } -bool SimplePubSubType::serialize(void *data, SerializedPayload_t *payload) +bool SimplePubSubType::serialize(void *data, SerializedPayload_t *payload) { SimpleStruct *p_type = (SimpleStruct*) data; - + // Object that manages the raw buffer. eprosima::fastcdr::FastBuffer fastbuffer((char*) payload->data, payload->max_size); // Object that serializes the data. eprosima::fastcdr::Cdr ser(fastbuffer,eprosima::fastcdr::Cdr::LITTLE_ENDIANNESS); //Select the correct endianess - payload->encapsulation = CDR_LE; + payload->encapsulation = CDR_LE; // Serialize the object: p_type->serialize(ser); //Get the serialized length payload->length = (uint16_t)ser.getSerializedDataLength(); - + return true; } @@ -73,7 +73,7 @@ bool SimplePubSubType::deserialize(SerializedPayload_t* payload, void* data) return true; } -bool SimplePubSubType::getKey(void *data, InstanceHandle_t* handle) +bool SimplePubSubType::getKey(void *data, InstanceHandle_t* handle, bool force_md5) { if(!m_isGetKeyDefined) return false; @@ -86,7 +86,7 @@ bool SimplePubSubType::getKey(void *data, InstanceHandle_t* handle) eprosima::fastcdr::Cdr ser(fastbuffer, eprosima::fastcdr::Cdr::BIG_ENDIANNESS); p_type->serializeKey(ser); - if(SimpleStruct::getKeyMaxCdrSerializedSize()>16) + if(force_md5 || SimpleStruct::getKeyMaxCdrSerializedSize()>16) { m_md5.init(); m_md5.update(m_keyBuffer,(unsigned int)ser.getSerializedDataLength()); @@ -103,6 +103,6 @@ bool SimplePubSubType::getKey(void *data, InstanceHandle_t* handle) handle->value[i] = m_keyBuffer[i]; } } - + return true; }