22 #include "ns3/address.h"
23 #include "ns3/address-utils.h"
25 #include "ns3/inet-socket-address.h"
26 #include "ns3/inet6-socket-address.h"
28 #include "ns3/socket.h"
29 #include "ns3/udp-socket-factory.h"
30 #include "ns3/tcp-socket-factory.h"
31 #include "ns3/simulator.h"
32 #include "ns3/socket-factory.h"
33 #include "ns3/packet.h"
34 #include "ns3/trace-source-accessor.h"
48 .SetGroupName(
"Applications")
50 .AddAttribute (
"Protocol",
"The type of protocol to use.",
54 .AddAttribute (
"NumberOfKeyToFetchFromKMS",
55 "The total number of keys per request to LKMS (ESTI QKD 014)",
58 MakeUintegerChecker<uint32_t> ())
59 .AddAttribute (
"LengthOfAuthenticationTag",
60 "The default length of the authentication tag",
63 MakeUintegerChecker<uint32_t> ())
64 .AddAttribute (
"EncryptionType",
65 "The type of encryption to be used (0-unencrypted, 1-OTP, 2-AES)",
68 MakeUintegerChecker<uint32_t> ())
69 .AddAttribute (
"AuthenticationType",
70 "The type of authentication to be used (0-unauthenticated, 1-VMAC, 2-MD5, 3-SHA1)",
73 MakeUintegerChecker<uint32_t> ())
74 .AddAttribute (
"AESLifetime",
75 "Lifetime of AES key expressed in bytes",
78 MakeUintegerChecker<uint64_t> ())
79 .AddAttribute (
"UseCrypto",
80 "Should crypto functions be performed (0-No, 1-Yes)",
83 MakeUintegerChecker<uint32_t> ())
84 .AddAttribute (
"WaitInsufficient",
"Penalty time (in seconds) when there is insufficient amount of key",
88 .AddAttribute (
"WaitTransform",
"Penalty time (in seconds) when keys are being transformed",
93 .AddTraceSource (
"Tx",
"A new packet is created and is sent",
95 "ns3::Packet::TracedCallback")
96 .AddTraceSource (
"TxSig",
"A new signaling packet is created and is sent",
98 "ns3::Packet::TracedCallback")
99 .AddTraceSource (
"TxKMS",
"A new packet is created and is sent to local KMS",
101 "ns3::Packet::TracedCallback")
102 .AddTraceSource (
"Rx",
"A new packet is received",
104 "ns3::Packet::TracedCallback")
105 .AddTraceSource (
"RxSig",
"A new signaling packet is received",
107 "ns3::Packet::TracedCallback")
108 .AddTraceSource (
"RxKMS",
"A new packet is received from local KMS",
110 "ns3::Packet::TracedCallback")
111 .AddTraceSource (
"StateTransition",
112 "Trace fired upon every QKDApp014 state transition.",
114 "ns3::Application::StateTransitionCallback")
115 .AddTraceSource (
"PacketEncrypted",
116 "The change trance for currenly ecrypted packet",
118 "ns3::QKDCrypto::PacketEncrypted")
119 .AddTraceSource (
"PacketDecrypted",
120 "The change trance for currenly decrypted packet",
122 "ns3::QKDCrypto::PacketDecrypted")
123 .AddTraceSource (
"PacketAuthenticated",
124 "The change trance for currenly authenticated packet",
126 "ns3::QKDCrypto::PacketAuthenticated")
127 .AddTraceSource (
"PacketDeAuthenticated",
128 "The change trance for currenly deauthenticated packet",
130 "ns3::QKDCrypto::PacketDeAuthenticated")
131 .AddTraceSource (
"Mx",
"Missed send packet call",
133 "ns3::Packet::TracedCallback")
134 .AddTraceSource (
"KeyObtained",
"Trace amount of obtained key material",
136 "ns3::QKDApp014::KeyObtained")
154 : m_sendSignalingSocketApp (0),
155 m_sinkSignalingSocketApp (0),
156 m_sendDataSocketApp (0),
157 m_sinkDataSocketApp (0),
158 m_sendSocketToKMS (0),
159 m_sinkSocketFromKMS (0),
167 m_appState (NOT_STARTED)
171 m_random = CreateObject<UniformRandomVariable> ();
174 {
"NOT_STARTED",
"INITIALIZED"},
175 {
"INITIALIZED",
"WAIT"},
176 {
"INITIALIZED",
"READY"},
179 {
"READY",
"SEND_DATA"},
180 {
"SEND_DATA",
"READY"},
181 {
"READY",
"DECRYPT_DATA"},
182 {
"DECRYPT_DATA",
"READY"},
183 {
"DECRYPT_DATA",
"STOPPED"},
184 {
"SEND_DATA",
"STOPPED"},
185 {
"READY",
"STOPPED"},
205 std::string socketType,
227 std::string socketType,
233 uint32_t nPacketsSize,
299 uint32_t scheduleID {0};
301 if(
action ==
"CheckAppBufferState"){
305 scheduleID =
event.GetUid();
322 std::map<uint32_t, EventId >::iterator eventEntry =
m_scheduledEvents.find ( eventId );
369 <<
" and port " << 82
516 NS_LOG_FUNCTION (
this <<
"QKDApp014 Connection from KMS requested on socket " << socket);
529 NS_LOG_FUNCTION (
this <<
"QKDApp014 Connection from KMS accepted on socket " << socket);
541 NS_LOG_FUNCTION (
this <<
"QKDApp014 Connection from APP accepted on socket " << s);
553 NS_LOG_FUNCTION (
this <<
"QKDApp014 Signaling Connection from APP accepted on socket " << s);
560 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014 Connection to KMS succeeded via socket " << socket);
566 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014, Connection to KMS Failed via socket " << socket);
572 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014 Connection to APP succeeded via socket " << socket);
578 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014, Connection to APP Failed via socket " << socket);
584 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014 Signaling Connection to APP succeeded via socket " << socket);
590 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014, Connection to APP Failed via socket " << socket);
635 while ((packet = socket->
RecvFrom (from)))
643 << packet <<
"PACKETID: " << packet->
GetUid()
644 <<
" of size: " << packet->
GetSize()
650 <<
"s packet from KMS received "
651 << packet->
GetSize () <<
" bytes from "
668 while ((packet = socket->
RecvFrom (from)))
676 <<
"PACKETID: " << packet->
GetUid()
677 <<
" of size: " << packet->
GetSize()
683 <<
"s packet from APP pair received "
684 << packet->
GetSize () <<
" bytes from "
700 while ((packet = socket->
RecvFrom (from)))
708 <<
"PACKETID: " << packet->
GetUid()
709 <<
" of size: " << packet->
GetSize()
715 <<
"s signaling packet from APP pair received "
716 << packet->
GetSize () <<
" bytes from "
728 NS_LOG_FUNCTION (
this <<
"QKDApp014 Data to KMS Sent via socket " << socket);
754 NS_LOG_FUNCTION(
this <<
"Keys removed from temporary key store" << keyIds );
755 std::map<std::string, QKDApp014::QKDApp014Key>::iterator it;
756 for (uint i = 0; i < keyIds.size(); i++) {
760 NS_LOG_DEBUG(
this <<
"Key with ID" << keyIds[i] <<
"does not exist in temporary key store!" );
769 NS_LOG_FUNCTION(
this <<
"Key with ID" << key.keyId <<
"is added to inbound key store!" );
776 NS_LOG_FUNCTION(
this <<
"Key with ID" << key.keyId <<
"is added to encription key store!" );
783 NS_LOG_FUNCTION(
this <<
"Key with ID" << key.keyId <<
"is added to authentication key store!" );
792 NS_LOG_FUNCTION(
this <<
"KeyId" << it->first << it->second.keyId <<
"\n" );
808 NS_LOG_FUNCTION(
this <<
"Primary QKDApp checks internal enc/auth buffer states ...");
823 NS_LOG_FUNCTION(
this <<
"Checking the conditions to change the application state ...");
824 bool encryptionReady {
true}, authenticationReady {
true};
826 encryptionReady =
false;
828 authenticationReady =
false;
832 else if(
m_appState ==
READY && !(encryptionReady && authenticationReady))
841 NS_LOG_FUNCTION(
this <<
"Obtaining encryption key from application key buffer!" );
847 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from application key buffer!" );
855 }
else if(keyType == 1){
856 NS_LOG_FUNCTION(
this <<
"Obtaining authentication key from application key buffer!" );
860 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from applicaiton key buffer!" );
867 <<
"Allowed values are 0-Encryption key type, and 1-Authentication key type" );
878 std::map<std::string, QKDApp014::QKDApp014Key>::iterator it;
882 if (keyType ==
"enc"){
888 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from inbound key buffer!" );
893 }
else if(keyType ==
"auth"){
894 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from inbound key buffer!" );
899 NS_FATAL_ERROR(
this <<
"Key" << keyId <<
" is missing from inbound key store" );
963 if(m_encryptionTypeInt < 0 || m_encryptionTypeInt > 2){
967 if(m_authenticationTypeInt < 0 || m_authenticationTypeInt > 3){
990 <<
" for StartApplication().");
1020 NS_LOG_FUNCTION(
this <<
"Open sockets are closed and application is stopped" );
1044 encKey.
keyId = std::string(32,
'0');
1046 authKey.
keyId = std::string(32,
'0');
1054 std::string encKeyDecoded =
m_encryptor->Base64Decode(encKey.
key);
1055 std::string authKeyDecoded =
m_encryptor->Base64Decode(authKey.
key);
1059 NS_LOG_FUNCTION(
this <<
"Confidential message" << confidentialMsg.size() << confidentialMsg );
1061 std::string encryptedMsg;
1062 std::string authTag;
1066 encryptedMsg =
m_encryptor->EncryptMsg(confidentialMsg, encKeyDecoded);
1068 <<
"Encrypted message (Base64 print)" <<
m_encryptor->Base64Encode(encryptedMsg));
1069 authTag =
m_encryptor->Authenticate (encryptedMsg, authKeyDecoded);
1071 <<
"Authentication tag" << authTag );
1075 encryptedMsg = confidentialMsg;
1083 std::string msg = encryptedMsg;
1084 Ptr<Packet> packet = Create<Packet> ( (uint8_t*) msg.c_str(), msg.length() );
1136 itBuffer =
m_buffer_QKDApp014.insert (std::make_pair (from, Create<Packet> (0))).first;
1139 buffer = itBuffer->second;
1181 uint8_t *buffer =
new uint8_t[packet->
GetSize ()];
1183 std::string payload = std::string((
char*)buffer, packet->
GetSize ());
1186 NS_LOG_FUNCTION(
this <<
"Replica QKDApp014 received data packet from peer QKDApp014" <<
m_encryptor->Base64Encode(payload) );
1190 std::string decryptedMsg;
1191 bool authSuccessful =
false;
1203 std::string decodedKey =
m_encryptor->Base64Decode(key.key);
1206 authSuccessful =
true;
1210 NS_LOG_FUNCTION(
this <<
"FAILED authentication of received packet" );
1214 authSuccessful =
true;
1223 authSuccessful =
true;
1227 NS_LOG_FUNCTION(
this <<
"FAILED authentication of received packet" );
1230 authSuccessful =
true;
1234 authSuccessful =
true;
1245 std::string decodedKey =
m_encryptor->Base64Decode(key.key);
1250 decryptedMsg =
m_encryptor->DecryptMsg (payload, decodedKey);
1270 NS_FATAL_ERROR(
this <<
"Only Replica QKDApp014 should receive protected packet" );
1297 std::ostringstream lkmsAddressTemp;
1298 lkmsAddress.
Print(lkmsAddressTemp);
1299 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1310 std::string hMessage = httpMessage.
ToString();
1312 (uint8_t*) (hMessage).c_str(),
1318 <<
" of size: " << packet->
GetSize()
1339 if (numberOfKeys <= 0)
1340 NS_FATAL_ERROR(
this <<
"Invalid application parameter - m_numberOfKeysKMS" << numberOfKeys );
1348 std::vector<std::string> additional_slave_SAE_IDs {};
1349 bool useGet =
false;
1352 if (additional_slave_SAE_IDs.empty() && useGet)
1359 std::ostringstream lkmsAddressTemp;
1360 lkmsAddress.
Print(lkmsAddressTemp);
1361 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1365 std::string requestBody;
1378 jkeyrequest[
"number"] = numberOfKeys;
1379 jkeyrequest[
"size"] = sizeOfKeys;
1380 if (!additional_slave_SAE_IDs.empty()){
1381 jkeyrequest[
"additional_slave_SAE_IDs"] = additional_slave_SAE_IDs;
1383 requestBody = jkeyrequest.dump();
1388 std::string hMessage = httpMessage.
ToString();
1390 (uint8_t*) (hMessage).c_str(),
1397 <<
" of size: " << packet->
GetSize()
1406 }
else if (keyType == 1)
1410 NS_LOG_FUNCTION(
this <<
"Size of authentication keys" << sizeOfKeys );
1412 std::vector<std::string> additional_slave_SAE_IDs {};
1413 bool useGet =
false;
1416 if (additional_slave_SAE_IDs.empty() && useGet)
1423 std::ostringstream lkmsAddressTemp;
1424 lkmsAddress.
Print(lkmsAddressTemp);
1425 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1429 std::string requestBody;
1441 jkeyrequest[
"number"] = numberOfKeys;
1442 jkeyrequest[
"size"] = sizeOfKeys;
1443 if (!additional_slave_SAE_IDs.empty()){
1444 jkeyrequest[
"additional_slave_SAE_IDs"] = additional_slave_SAE_IDs;
1447 requestBody = jkeyrequest.dump();
1453 std::string hMessage = httpMessage.
ToString();
1455 (uint8_t*) (hMessage).c_str(),
1461 <<
" of size: " << packet->
GetSize()
1470 NS_FATAL_ERROR(
this <<
"Invalid key type" << keyType <<
"Available values are 0-Encryption key type, and 1-Authentication key type" );
1492 std::ostringstream lkmsAddressTemp;
1493 lkmsAddress.
Print(lkmsAddressTemp);
1494 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1497 headerUri +=
"/api/v1/keys/"+ksid+
"/dec_keys";
1504 std::string hMessage = httpMessage.
ToString();
1506 (uint8_t*) (hMessage).c_str(),
1512 <<
" of size: " << packet->
GetSize()
1525 std::string receivedStatus = p->
ToString();
1529 if (receivedStatus.find(
"Fragment") != std::string::npos) {
1533 std::make_pair (from, Create<Packet> (0))
1536 buffer = itBuffer->second;
1547 uint8_t *b1 =
new uint8_t[buffer->
GetSize ()];
1549 std::string requestString = std::string((
char*)b1);
1553 parser.Parse(&request, requestString);
1566 uint8_t *b2 =
new uint8_t[completePacket->
GetSize ()];
1568 std::string s2 = std::string((
char*)b2);
1571 parser.Parse(&request2, s2);
1598 jresponse = nlohmann::json::parse(payload);
1600 if (methodType == 0) {
1604 }
else if (methodType == 1){
1608 }
else if (methodType == 2) {
1627 responseStatus == HTTPMessage::HttpStatus::BadRequest ||
1628 responseStatus == HTTPMessage::HttpStatus::Unauthorized ||
1629 responseStatus == HTTPMessage::HttpStatus::ServiceUnavailable
1632 NS_FATAL_ERROR(
this <<
"QKDApp014 received ERROR status information from local KMS" << jstatusResponse.dump() );
1634 }
else if (responseStatus == HTTPMessage::HttpStatus::Ok){
1636 NS_LOG_FUNCTION(
this <<
"QKDApp014 received status information from local KMS" );
1641 NS_FATAL_ERROR(
this <<
"Unsupported error status code" << responseStatus <<
"of response.");
1653 if(jGetKeyResponse.empty())
1657 if (jGetKeyResponse.contains(
"ksid"))
1658 ksid = jGetKeyResponse[
"ksid"];
1662 responseStatus == HTTPMessage::HttpStatus::BadRequest ||
1663 responseStatus == HTTPMessage::HttpStatus::Unauthorized ||
1664 responseStatus == HTTPMessage::HttpStatus::ServiceUnavailable
1667 if (jGetKeyResponse.contains(
"message"))
1669 if (jGetKeyResponse[
"message"] == std::string {
"requested parameters do not adhere to KMS rules"})
1671 else if (jGetKeyResponse[
"message"] == std::string {
"insufficient amount of key material"})
1673 else if (jGetKeyResponse[
"message"] == std::string {
"keys are being transformed"})
1681 }
else if (responseStatus == HTTPMessage::HttpStatus::Ok){
1683 NS_LOG_FUNCTION(
this <<
"Primary QKDApp014 received requested number of keys" << jGetKeyResponse.dump() );
1688 std::vector<std::string> keysToNegotiate;
1689 for (nlohmann::json::iterator it = jGetKeyResponse[
"keys"].begin(); it != jGetKeyResponse[
"keys"].end(); ++it) {
1690 key.key = (it.value())[
"key"];
1691 key.keyId = (it.value())[
"key_ID"];
1692 key.keyType = keyType;
1698 keysToNegotiate.push_back(key.keyId);
1707 NS_FATAL_ERROR(
this <<
"Unsupported error status code" << responseStatus <<
"of response.");
1721 if (jGetKeyWithKeyIDsResponse.contains(
"ksid"))
1722 ksid = jGetKeyWithKeyIDsResponse[
"ksid"];
1726 responseStatus == HTTPMessage::HttpStatus::BadRequest ||
1727 responseStatus == HTTPMessage::HttpStatus::Unauthorized ||
1728 responseStatus == HTTPMessage::HttpStatus::ServiceUnavailable
1731 NS_FATAL_ERROR(
this <<
"Replica QKDApp014 received ERROR response on key request" << jGetKeyWithKeyIDsResponse.dump() );
1735 }
else if (responseStatus == HTTPMessage::HttpStatus::Ok) {
1737 NS_LOG_FUNCTION(
this <<
"Replica QKDApp014 received requested keys" << jGetKeyWithKeyIDsResponse.dump() );
1741 for (nlohmann::json::iterator it = jGetKeyWithKeyIDsResponse[
"keys"].begin(); it != jGetKeyWithKeyIDsResponse[
"keys"].end(); ++it) {
1743 key.key = (it.value())[
"key"];
1744 key.keyId = (it.value())[
"key_ID"];
1754 NS_FATAL_ERROR(
this <<
"Unsupported HTTP status code" << responseStatus <<
"of response");
1764 std::string receivedStatus = p->
ToString();
1768 if (receivedStatus.find(
"Fragment") != std::string::npos) {
1772 std::make_pair (from, Create<Packet> (0))
1775 buffer = itBuffer->second;
1786 uint8_t *b1 =
new uint8_t[buffer->
GetSize ()];
1788 std::string requestString = std::string((
char*)b1);
1792 parser.Parse(&request, requestString);
1807 uint8_t *b2 =
new uint8_t[completePacket->
GetSize ()];
1809 std::string s2 = std::string((
char*)b2);
1812 parser.Parse(&request2, s2);
1833 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Primary QKDApp014 received response from Replica QKDApp014. Packet ID" << packet->
GetUid());
1836 if (header.
GetStatus() == HTTPMessage::HttpStatus::Ok) {
1840 for (uint i = 0; i < keyIds.size(); i++) {
1843 std::map<std::string, QKDApp014::QKDApp014Key>::iterator it;
1848 NS_LOG_DEBUG(
this <<
"Key " << keyIds[i] <<
" was not found in the temporary key store!" );
1851 if ((it->second).keyType == 0)
1866 NS_LOG_DEBUG (
this <<
"The attempt to negotiate keys failed.");
1869 NS_LOG_FUNCTION(
this <<
"Application is submitting a new GET_KEY request ...");
1877 NS_LOG_DEBUG(
this <<
"Key" << keyID <<
"was not found in the temporary key store!");
1893 jKeyIDs = nlohmann::json::parse(payload);
1895 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Replica QKDApp014 received proposal from Primary QKDApp014. Packet ID" << packet->
GetUid() << jKeyIDs);
1919 key_IDs[
"ksid"] = ksid;
1920 for (uint i = 0; i < keyIds.size(); i++) {
1921 key_IDs[
"key_IDs"].push_back({ {
"key_ID", keyIds[i] } });
1924 std::string msg = key_IDs.dump();
1929 std::string hMessage = httpMessage.
ToString();
1931 (uint8_t*) (hMessage).c_str(),
1941 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Primary QKDApp014 sends proposal to Replica QKDApp014. Packet ID" << packet->
GetUid() << packet->
GetSize());
1948 std::string hMessage = httpMessage.
ToString();
1950 (uint8_t*) (hMessage).c_str(),
1959 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Replica QKDApp014 sends respond to Primary QKDApp014. Packet ID" << packet->
GetUid() );
2003 "for AppTransitionTree()!");
2012 "for AppTransitionTree()!");
2031 return "NOT_STARTED";
2034 return "INITIALIZED";
2046 return "DECRYPT_DATA";
2053 return "FATAL_ERROR";
2074 for (std::multimap<std::string, std::string>::iterator iter =
2078 if(iter->first == oldState && iter->second == newState){
2080 NS_LOG_DEBUG (
this <<
" QKDApp014 " << oldState <<
" --> " << newState <<
".");
2086 if(found ==
false) {
2087 NS_FATAL_ERROR (
"Unsupported transition from " << oldState <<
" to " << newState);
2103 uint32_t encryptionType,
2104 uint32_t authenticationType,
2105 uint32_t authenticationTagLengthInBits
2108 NS_LOG_FUNCTION (
this << encryptionType << authenticationType << authenticationTagLengthInBits);
2110 switch (encryptionType){
2122 switch (authenticationType){
2141 authenticationTagLengthInBits
2147 authenticationTagLengthInBits
2162 std::string confidentialMessage;
2163 static const char alphanum[] =
2165 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2166 "abcdefghijklmnopqrstuvwxyz";
2168 uint32_t randVal = 0;
2169 for (uint32_t i = 0; i < msgLength; ++i){
2171 confidentialMessage += alphanum[ randVal ];
2174 return confidentialMessage;
2181 keyId.erase(std::remove(keyId.begin(), keyId.end(),
'-'), keyId.end());
2189 keyId.insert(8,
"-");
2190 keyId.insert(13,
"-");
2191 keyId.insert(18,
"-");
2192 keyId.insert(23,
"-");
2212 return CryptoPP::AES::MAX_KEYLENGTH * 8;
2229 return CryptoPP::AES::BLOCKSIZE * 8;
a polymophic address class
The base class for all ns3 applications.
Ptr< Node > GetNode() const
Class for representing data rates.
uint64_t GetBitRate() const
Get the underlying bitrate.
An identifier for simulation events.
bool IsRunning() const
This method is syntactic sugar for !IsExpired().
The basic class to represent both HTTP requests and responses.
std::string ToString()
Takes the headers added to the message along with the body and outputs it to a std::string for use in...
void CreateRequest(const std::string &url, const std::string &method)
std::string GetMessageBodyString()
void CreateResponse(const HttpStatus status)
HTTPMessage::HttpStatus GetStatus()
To be returned with a status code in a response is a status text describing the status code by text r...
std::string GetStatusMessage() const
Get the current status message for this message.
A basic class to parse a HTTP message, both request and response.
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
Ipv4 addresses are stored in host order in this class.
void Print(std::ostream &os) const
Print this address to the given output stream.
static Ipv4Address GetAny()
uint32_t RemoveHeader(Header &header)
Deserialize and remove the header from the internal buffer.
void AddAtEnd(Ptr< const Packet > packet)
Concatenate the input packet at the end of the current packet.
void AddHeader(const Header &header)
Add header to this packet.
uint32_t GetSize() const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
uint32_t CopyData(uint8_t *buffer, uint32_t size) const
Copy the packet contents to a byte buffer.
void RemoveAtStart(uint32_t size)
Remove size bytes from the start of the current packet.
uint32_t PeekHeader(Header &header) const
Deserialize but does not remove the header from the internal buffer.
Ptr< Packet > CreateFragment(uint32_t start, uint32_t length) const
Create a new packet which contains a fragment of the original packet.
uint64_t GetUid() const
Returns the packet's Uid.
std::string ToString() const
Return a string representation of the packet.
Establish secure communication on application lavel to use the key and test LKSM.
uint32_t m_master
Is a master (sender/primary) application?
void HandleAcceptFromKMS(Ptr< Socket > s, const Address &from)
Handle an incoming connection from the KMS.
void GetKeyWithKeyIDs()
Requests keys with given identifiers from the KMS (ETSI QKD 014 - Get key with key IDs method).
void PrepareSendSocketToKMS()
Prepare the send socket to communicate with the KMS Application.
uint32_t GetKeyType(void)
Map the HTTP response and obtain the key type.
void SwitchAppState(QKDApp014State state)
Change the state of the application.
void HandleReadFromKMS(Ptr< Socket > socket)
Handle a packet received from the KMS application.
Ptr< QKDEncryptor > m_encryptor
The QKD encryptor.
void ConnectionSignalingToAppSucceeded(Ptr< Socket > socket)
Callback function after the signaling connection to the APP is complete.
TracedCallback< const uint32_t & > m_obtainedKeyMaterialTrace
A trace callback for the obtained key material.
std::string CreateKeyIdField(std::string keyId)
Adjust the encryption key identifier for the QKDApp header.
void HandlePeerCloseSignalingFromApp(Ptr< Socket > socket)
Handle a signaling connection close from the peer QKD application.
TracedCallback< Ptr< const Packet >, std::string > m_txTrace
A trace for transmitted data packets.
void ConnectionSignalingToAppFailed(Ptr< Socket > socket)
Callback function after the signaling connection to the APP has failed.
void AddAuthKeyInKeyStore(QKDApp014::QKDApp014Key &key)
Add a new key to the authentication key store.
void ProcessStatusResponse(HTTPMessage &header, nlohmann::json jstatusResponse)
Process the status response from the KMS.
QKDApp014State
The application states.
std::string GetPacketContent(uint32_t msgLength=0)
Generate a random packet (message) of a given size.
void HandlePeerErrorFromKMS(Ptr< Socket > socket)
Handle a connection error from the KMS.
std::unordered_map< Address, Ptr< Packet >, AddressHash > m_buffer_kms
The buffer for the received packets from the KMS (fragmentation).
QKDApp014State GetAppState() const
Get the current state of the application.
TypeId m_tid
The type identifier.
UUID m_ksid_auth
The authentication key stream identifier.
static TypeId GetTypeId(void)
Get the type ID.
void GetKeysFromKMS(uint32_t keyType)
Request keys from the KMS (ETSI QKD 014 - Get key method).
Time m_waitInsufficient
The amount of time spent waiting before issuing a new GET_KEY request when the previous one resulted ...
void SendPacket(void)
Send the application packet (includes the generation of a random message and optional encryption or/a...
void ConnectionToKMSSucceeded(Ptr< Socket > socket)
Callback function after the connection to the KMS is complete.
void ProcessDataPacketFromApp(QKDAppHeader header, Ptr< Packet > packet, Ptr< Socket > socket)
Process the data packets from the peer QKD application.
std::vector< std::vector< std::string > > m_httpRequestsApp
A vector of HTTP requests sent to the peer application.
std::map< uint32_t, EventId > m_scheduledEvents
The map of scheduled events.
void MemoriesRequestKMS(uint32_t methodType, uint32_t keyType=0)
Memories the HTTP request made to the local KMS.
TracedCallback< Ptr< const Packet >, std::string > m_mxTrace
A trace for the missed time slots to send data packets.
UUID m_dstSaeId
The peer application identifier.
uint32_t ScheduleAction(Time t, std::string action)
Schedule the action.
DataRate m_dataRate
The application data rate.
UUID m_ksid_enc
The encryption key stream identifier.
void AddEncKeyInKeyStore(QKDApp014::QKDApp014Key &key)
Add a new key to the encryption key store.
void PacketReceivedFromKMS(const Ptr< Packet > &p, const Address &from, Ptr< Socket > socket)
Check for the TCP segmentation of the packets received from the KMS.
uint32_t GetETSIMethod(void)
Map the HTTP response and obtrain the request method.
void HandleAcceptSignalingFromApp(Ptr< Socket > s, const Address &from)
Handle a signaling incoming connection from the peer QKD application.
uint32_t GetAuthenticationKeySize()
Get required key size for the choosen authentication algorithm.
TracedCallback< Ptr< const Packet > > m_txKmsTrace
A trace for transmitted packets to the KMS.
void HandlePeerCloseFromKMS(Ptr< Socket > socket)
Handle a connection close from the KMS.
QKDApp014State m_appState
The application state.
uint32_t GetEncryptionKeySize()
Get required key size for the choosen encryption algorithm.
void MemoriesRequestApp(std::vector< std::string > keyIds)
Memories the HTTP request made to the peer QKD application.
Ptr< Socket > m_sendSocketToKMS
The sending socket to the KMS.
void ProcessResponseFromKMS(HTTPMessage &header, Ptr< Packet > packet, Ptr< Socket > socket)
Process the response from the KMS application.
uint32_t m_encryptionTypeInt
The encryption algorithm.
void ProcessGetKeyResponse(HTTPMessage &header, nlohmann::json jGetKeyResponse)
Process the GET_KEY response from the KMS.
void HandleAcceptFromApp(Ptr< Socket > s, const Address &from)
Handle an incoming connection from the peer QKD application.
void ConnectionToAppFailed(Ptr< Socket > socket)
Callback function after the connection to the APP has failed.
std::string GetAppStateString() const
Get the current state of the application in the string format.
Address m_kms
The local KMS address.
uint32_t m_authenticationTagLengthInBits
The size of the authentication tag in bits (32 by default).
TracedCallback< Ptr< const Packet > > m_rxSigTrace
A trace for received signaling packets.
void ExchangeInfoMessages(std::string ksid, std::vector< std::string > keyIds, HTTPMessage::HttpStatus statusCode=HTTPMessage::Ok)
Exchange key identifiers between sending and receiving application.
ns3::TracedCallback< const std::string &, const std::string & > m_stateTransitionTrace
The posible application state transitions.
TracedCallback< Ptr< Packet >, std::string > m_authenticationTrace
A trace callback for the authentication event.
void SignalingPacketReceivedFromApp(const Ptr< Packet > &p, const Address &from, Ptr< Socket > socket)
Check for the TCP segmentation of the signaling packets received from the peer QKD application.
uint32_t m_numberOfKeysKMS
The number of keys to fetch per request.
std::string ReadKeyIdField(std::string keyId)
Rebuild the key identifier for the QKDApp header.
bool ConnectionRequestedFromKMS(Ptr< Socket > socket, const Address &address)
Callback function after the connection response from the KMS has been received.
void RequestProcessedKMS(void)
Remove the request from the HTTP requests store (once the response from the KMS has been processed).
virtual void StartApplication(void)
void CheckAppBufferState()
Check the state of the application key buffer.
std::string m_socketType
The sockets type.
QKDApp014KeyBuffer m_appKeyBuffer
The application key buffer.
UUID GetId(void)
Get the application identifier.
Address m_localSignaling
The local address for the signaling data transmission.
TracedCallback< Ptr< Packet > > m_encryptionTrace
A trace callback for the encryption event.
std::vector< std::pair< uint32_t, uint32_t > > m_httpRequestsKMS
A vector of HTTP requests set to the KMS.
EventId m_sendEvent
The data transmission event.
void PrintAppBufferStatusInformation()
Print the status information on the application key buffer.
uint32_t m_authenticationTypeInt
The authentication algorithm.
void ProcessGetKeyWithKeyIDsResponse(HTTPMessage &header, nlohmann::json jGetKeyWithKeyIDsResponse)
Process the Get Key with Key IDs response from the KMS.
void InitializeAppKeyBuffer()
Initialize the application key buffer.
uint32_t m_packetSize
The data packet size.
void HandleReadFromApp(Ptr< Socket > socket)
Handle a packet received from the peer QKD application.
TracedCallback< Ptr< const Packet > > m_txSigTrace
A trace for transmitted signaling packets.
Ptr< Socket > m_sendDataSocketApp
The sending socket for the data.
TracedCallback< Ptr< const Packet > > m_rxKmsTrace
A trace for received packets from the KMS.
virtual void StopApplication(void)
Application specific shutdown code.
void HandlePeerErrorFromApp(Ptr< Socket > socket)
Handle a connection error from the peer QKD application.
void ConnectionToAppSucceeded(Ptr< Socket > socket)
Callback function after the connection to the APP is complete.
void ProcessSignalingPacketFromApp(HTTPMessage &header, Ptr< Packet > packet, Ptr< Socket > socket)
Process the signaling packets received from the peer QKD application.
uint32_t m_packetsSent
The number of sent data packets.
uint64_t m_aesLifetime
The AES key lifetime.
void DataPacketReceivedFromApp(const Ptr< Packet > &p, const Address &from, Ptr< Socket > socket)
Check for the TCP segmentation of the data packets received from the peer QKD application.
void DataToKMSSend(Ptr< Socket >, uint32_t)
Callback function to notify that data to KMS has been sent.
void ConnectionToKMSFailed(Ptr< Socket > socket)
Callback function after the connection to the KMS has failed.
Ptr< Socket > m_sinkDataSocketApp
The receiving socket for the data.
TracedCallback< Ptr< const Packet >, std::string > m_rxTrace
A trace for received data packets.
std::unordered_map< Address, Ptr< Packet >, AddressHash > m_buffer_QKDApp014
The buffer for received data packets (fragmentation).
void SetEncryptionAndAuthenticationSettings(uint32_t encryptionType, uint32_t authenticationType, uint32_t authenticationTagLengthInBits)
Set the encryption and the authentication algorithms.
void CancelScheduledAction(uint32_t eventId)
Cancel the scheduled event/action.
Ptr< Socket > m_sinkSocketFromKMS
The receiving socket from the KMS.
QKDApp014::QKDApp014Key GetKeyFromAppKeyBuffer(uint32_t keyType)
Get the key from the application key buffer.
void RemoveKeysFromTemporaryKeyStore(std::vector< std::string > keyIds)
Remove keys from the temporary key store.
Address m_local
The local address for the data transmission.
void HandlePeerErrorSignalingFromApp(Ptr< Socket > socket)
Handle a signaling connection error from the peer QKD application.
static uint32_t m_applicationCounts
The number of running applications.
nlohmann::json m_keyIDs
The latest received key identifiers from the sender application.
bool m_internalAppWait
The indicator for the longer wait (used after the GetKey error!).
void AppTransitionTree(void)
Transition through a tree of the application states and trigger actions.
void CheckAppState()
Check the conditions to change the application state.
uint32_t m_useCrypto
Execute actual cryptographic algorithms?
std::multimap< std::string, std::string > m_transitionMatrix
The map of the possible state transitions.
void RequestProcessedApp(void)
Remove request from the HTTP requests store (once the response from the peer application has been pro...
virtual ~QKDApp014()
Destructor.
Ptr< UniformRandomVariable > m_random
The uniform random variable.
TracedCallback< Ptr< Packet >, std::string > m_deauthenticationTrace
A trace callback for the authentication check event.
void PrintTemporaryKeyStoreContent()
Print the content of the temporary key store.
void PrepareSendSocketToApp()
Prepare the send socket to communicate with the peer QKD Application.
void Setup(std::string socketType, Address src, Address dst, Address kms, UUID dstSaeId, std::string type)
Configure the application.
UUID m_id
The application identifier.
void HandleReadSignalingFromApp(Ptr< Socket > socket)
Handle a signaling packet received from the peer QKD application.
void GetStatusFromKMS(uint32_t keyType)
Request status information from the KMS (ETSI QKD 014 - Get status method).
Time m_waitTransform
The amount of time spent waiting before issuing a new GET_KEY request when the previous one resulted ...
TracedCallback< Ptr< Packet > > m_decryptionTrace
A trace callback for the decryption event.
Ptr< Socket > m_sendSignalingSocketApp
The sending socket for the signaling messages.
void ScheduleTx(void)
Schedule the time slot to send the data packets.
Address m_peer
The address of the peer for the data transmission.
QKDEncryptor::AuthenticationType m_authenticationType
The authentication algorithm.
Address m_peerSignaling
The address of the peer for the signaling data transmission.
void HandlePeerCloseFromApp(Ptr< Socket > socket)
Handle a connection close from the peer QKD application.
uint32_t m_dataSent
The amount of the sent data.
void AddKeyInInboundKeyStore(QKDApp014::QKDApp014Key &key)
Add a new key to the inbound key store.
Ptr< Socket > m_sinkSignalingSocketApp
The receiving socket for the signaling messages.
void PrepareSinkSocketFromApp()
Prepare the sink socket to listen from the peer QKD Application.
QKDEncryptor::EncryptionType m_encryptionType
The encryption algorithm.
void PrepareSinkSocketFromKMS()
Prepare the sink socket to listen from the KMS Application.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
static void Cancel(const EventId &id)
Set the cancel bit on this event: the event's associated function will not be invoked when it expires...
static Time Now()
Return the current simulation virtual time.
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
void SetCloseCallbacks(Callback< void, Ptr< Socket >> normalClose, Callback< void, Ptr< Socket >> errorClose)
Detect socket recv() events such as graceful shutdown or error.
void SetAcceptCallback(Callback< bool, Ptr< Socket >, const Address & > connectionRequest, Callback< void, Ptr< Socket >, const Address & > newConnectionCreated)
Accept connection requests from remote hosts.
void SetRecvCallback(Callback< void, Ptr< Socket >> receivedData)
Notify application when new data is available to be read.
virtual int ShutdownRecv()=0
void SetDataSentCallback(Callback< void, Ptr< Socket >, uint32_t > dataSent)
Notify application when a packet has been sent from transport protocol (non-standard socket call)
virtual int ShutdownSend()=0
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
static Ptr< Socket > CreateSocket(Ptr< Node > node, TypeId tid)
This method wraps the creation of sockets that is performed on a given node by a SocketFactory specif...
virtual int Close()=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
virtual int Listen()=0
Listen for incoming connections.
void SetConnectCallback(Callback< void, Ptr< Socket >> connectionSucceeded, Callback< void, Ptr< Socket >> connectionFailed)
Specify callbacks to allow the caller to determine if the connection succeeds of fails.
virtual Ptr< Packet > RecvFrom(uint32_t maxSize, uint32_t flags, Address &fromAddress)=0
Read a single packet from the socket and retrieve the sender address.
static TypeId GetTypeId()
Get the type ID.
Simulation virtual time values and global simulation resolution.
a unique identifier for an interface.
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Universally unique identifier (UUID)
static UUID Random()
Generate random UUID4 (randomly or pseudo-randomly generated version)
std::string string() const
Get string from the current UUID in format "00000000-0000-0000-0000-000000000000".
static TypeId GetTypeId()
Get the type ID.
Hold an unsigned integer type.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Callback< R, Args... > MakeNullCallback()
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Time Seconds(double value)
Construct a Time in the indicated unit.
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
NLOHMANN_BASIC_JSON_TPL_DECLARATION std::string to_string(const NLOHMANN_BASIC_JSON_TPL &j)
user-defined to_string function for JSON values
basic_json<> json
default JSON class
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Ptr< const AttributeChecker > MakeTypeIdChecker()
Ptr< const AttributeChecker > MakeTimeChecker(const Time min, const Time max)
Helper to make a Time checker with bounded range.
Ptr< const AttributeAccessor > MakeTypeIdAccessor(T1 a1)
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
std::map< std::string, QKDApp014Key > outboundEncKeyStore
std::map< std::string, QKDApp014Key > outboundAuthKeyStore
std::map< std::string, QKDApp014Key > inboundKeyStore
std::map< std::string, QKDApp014Key > temporaryKeyStoreMaster
The cryptographic key at the application layer.
static const uint32_t packetSize
Packet size generated at the AP.