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
512 NS_LOG_FUNCTION (
this <<
"QKDApp014 Connection from KMS requested on socket " << socket);
525 NS_LOG_FUNCTION (
this <<
"QKDApp014 Connection from KMS accepted on socket " << socket);
537 NS_LOG_FUNCTION (
this <<
"QKDApp014 Connection from APP accepted on socket " << s);
549 NS_LOG_FUNCTION (
this <<
"QKDApp014 Signaling Connection from APP accepted on socket " << s);
556 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014 Connection to KMS succeeded via socket " << socket);
562 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014, Connection to KMS Failed via socket " << socket);
568 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014 Connection to APP succeeded via socket " << socket);
574 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014, Connection to APP Failed via socket " << socket);
580 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014 Signaling Connection to APP succeeded via socket " << socket);
586 NS_LOG_FUNCTION (
this << socket <<
"QKDApp014, Connection to APP Failed via socket " << socket);
631 while ((packet = socket->
RecvFrom (from)))
639 << packet <<
"PACKETID: " << packet->
GetUid()
640 <<
" of size: " << packet->
GetSize()
646 <<
"s packet from KMS received "
647 << packet->
GetSize () <<
" bytes from "
664 while ((packet = socket->
RecvFrom (from)))
672 <<
"PACKETID: " << packet->
GetUid()
673 <<
" of size: " << packet->
GetSize()
679 <<
"s packet from APP pair received "
680 << packet->
GetSize () <<
" bytes from "
696 while ((packet = socket->
RecvFrom (from)))
704 <<
"PACKETID: " << packet->
GetUid()
705 <<
" of size: " << packet->
GetSize()
711 <<
"s signaling packet from APP pair received "
712 << packet->
GetSize () <<
" bytes from "
724 NS_LOG_FUNCTION (
this <<
"QKDApp014 Data to KMS Sent via socket " << socket);
750 NS_LOG_FUNCTION(
this <<
"Keys removed from temporary key store" << keyIds );
751 std::map<std::string, QKDApp014::QKDApp014Key>::iterator it;
752 for (uint i = 0; i < keyIds.size(); i++) {
756 NS_LOG_DEBUG(
this <<
"Key with ID" << keyIds[i] <<
"does not exist in temporary key store!" );
765 NS_LOG_FUNCTION(
this <<
"Key with ID" << key.keyId <<
"is added to inbound key store!" );
772 NS_LOG_FUNCTION(
this <<
"Key with ID" << key.keyId <<
"is added to encription key store!" );
779 NS_LOG_FUNCTION(
this <<
"Key with ID" << key.keyId <<
"is added to authentication key store!" );
788 NS_LOG_FUNCTION(
this <<
"KeyId" << it->first << it->second.keyId <<
"\n" );
804 NS_LOG_FUNCTION(
this <<
"Primary QKDApp checks internal enc/auth buffer states ...");
819 NS_LOG_FUNCTION(
this <<
"Checking the conditions to change the application state ...");
820 bool encryptionReady {
true}, authenticationReady {
true};
822 encryptionReady =
false;
824 authenticationReady =
false;
828 else if(
m_appState ==
READY && !(encryptionReady && authenticationReady))
837 NS_LOG_FUNCTION(
this <<
"Obtaining encryption key from application key buffer!" );
843 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from application key buffer!" );
851 }
else if(keyType == 1){
852 NS_LOG_FUNCTION(
this <<
"Obtaining authentication key from application key buffer!" );
856 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from applicaiton key buffer!" );
863 <<
"Allowed values are 0-Encryption key type, and 1-Authentication key type" );
874 std::map<std::string, QKDApp014::QKDApp014Key>::iterator it;
878 if (keyType ==
"enc"){
884 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from inbound key buffer!" );
889 }
else if(keyType ==
"auth"){
890 NS_LOG_FUNCTION(
this <<
"Key " << key.keyId <<
" removed from inbound key buffer!" );
895 NS_FATAL_ERROR(
this <<
"Key" << keyId <<
" is missing from inbound key store" );
959 if(m_encryptionTypeInt < 0 || m_encryptionTypeInt > 2){
963 if(m_authenticationTypeInt < 0 || m_authenticationTypeInt > 3){
986 <<
" for StartApplication().");
1016 NS_LOG_FUNCTION(
this <<
"Open sockets are closed and application is stopped" );
1040 encKey.
keyId = std::string(32,
'0');
1042 authKey.
keyId = std::string(32,
'0');
1050 std::string encKeyDecoded =
m_encryptor->Base64Decode(encKey.
key);
1051 std::string authKeyDecoded =
m_encryptor->Base64Decode(authKey.
key);
1055 NS_LOG_FUNCTION(
this <<
"Confidential message" << confidentialMsg.size() << confidentialMsg );
1057 std::string encryptedMsg;
1058 std::string authTag;
1062 encryptedMsg =
m_encryptor->EncryptMsg(confidentialMsg, encKeyDecoded);
1064 <<
"Encrypted message (Base64 print)" <<
m_encryptor->Base64Encode(encryptedMsg));
1065 authTag =
m_encryptor->Authenticate (encryptedMsg, authKeyDecoded);
1067 <<
"Authentication tag" << authTag );
1071 encryptedMsg = confidentialMsg;
1079 std::string msg = encryptedMsg;
1080 Ptr<Packet> packet = Create<Packet> ( (uint8_t*) msg.c_str(), msg.length() );
1132 itBuffer =
m_buffer_QKDApp014.insert (std::make_pair (from, Create<Packet> (0))).first;
1135 buffer = itBuffer->second;
1177 uint8_t *buffer =
new uint8_t[packet->
GetSize ()];
1179 std::string payload = std::string((
char*)buffer, packet->
GetSize ());
1182 NS_LOG_FUNCTION(
this <<
"Replica QKDApp014 received data packet from peer QKDApp014" <<
m_encryptor->Base64Encode(payload) );
1186 std::string decryptedMsg;
1187 bool authSuccessful =
false;
1199 std::string decodedKey =
m_encryptor->Base64Decode(key.key);
1202 authSuccessful =
true;
1206 NS_LOG_FUNCTION(
this <<
"FAILED authentication of received packet" );
1210 authSuccessful =
true;
1219 authSuccessful =
true;
1223 NS_LOG_FUNCTION(
this <<
"FAILED authentication of received packet" );
1226 authSuccessful =
true;
1230 authSuccessful =
true;
1241 std::string decodedKey =
m_encryptor->Base64Decode(key.key);
1246 decryptedMsg =
m_encryptor->DecryptMsg (payload, decodedKey);
1266 NS_FATAL_ERROR(
this <<
"Only Replica QKDApp014 should receive protected packet" );
1293 std::ostringstream lkmsAddressTemp;
1294 lkmsAddress.
Print(lkmsAddressTemp);
1295 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1306 std::string hMessage = httpMessage.
ToString();
1308 (uint8_t*) (hMessage).c_str(),
1314 <<
" of size: " << packet->
GetSize()
1335 if (numberOfKeys <= 0)
1336 NS_FATAL_ERROR(
this <<
"Invalid application parameter - m_numberOfKeysKMS" << numberOfKeys );
1344 std::vector<std::string> additional_slave_SAE_IDs {};
1345 bool useGet =
false;
1348 if (additional_slave_SAE_IDs.empty() && useGet)
1355 std::ostringstream lkmsAddressTemp;
1356 lkmsAddress.
Print(lkmsAddressTemp);
1357 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1361 std::string requestBody;
1374 jkeyrequest[
"number"] = numberOfKeys;
1375 jkeyrequest[
"size"] = sizeOfKeys;
1376 if (!additional_slave_SAE_IDs.empty()){
1377 jkeyrequest[
"additional_slave_SAE_IDs"] = additional_slave_SAE_IDs;
1379 requestBody = jkeyrequest.dump();
1384 std::string hMessage = httpMessage.
ToString();
1386 (uint8_t*) (hMessage).c_str(),
1393 <<
" of size: " << packet->
GetSize()
1402 }
else if (keyType == 1)
1406 NS_LOG_FUNCTION(
this <<
"Size of authentication keys" << sizeOfKeys );
1408 std::vector<std::string> additional_slave_SAE_IDs {};
1409 bool useGet =
false;
1412 if (additional_slave_SAE_IDs.empty() && useGet)
1419 std::ostringstream lkmsAddressTemp;
1420 lkmsAddress.
Print(lkmsAddressTemp);
1421 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1425 std::string requestBody;
1437 jkeyrequest[
"number"] = numberOfKeys;
1438 jkeyrequest[
"size"] = sizeOfKeys;
1439 if (!additional_slave_SAE_IDs.empty()){
1440 jkeyrequest[
"additional_slave_SAE_IDs"] = additional_slave_SAE_IDs;
1443 requestBody = jkeyrequest.dump();
1449 std::string hMessage = httpMessage.
ToString();
1451 (uint8_t*) (hMessage).c_str(),
1457 <<
" of size: " << packet->
GetSize()
1466 NS_FATAL_ERROR(
this <<
"Invalid key type" << keyType <<
"Available values are 0-Encryption key type, and 1-Authentication key type" );
1488 std::ostringstream lkmsAddressTemp;
1489 lkmsAddress.
Print(lkmsAddressTemp);
1490 std::string headerUri =
"http://" + lkmsAddressTemp.str ();
1493 headerUri +=
"/api/v1/keys/"+ksid+
"/dec_keys";
1500 std::string hMessage = httpMessage.
ToString();
1502 (uint8_t*) (hMessage).c_str(),
1508 <<
" of size: " << packet->
GetSize()
1521 std::string receivedStatus = p->
ToString();
1525 if (receivedStatus.find(
"Fragment") != std::string::npos) {
1529 std::make_pair (from, Create<Packet> (0))
1532 buffer = itBuffer->second;
1543 uint8_t *b1 =
new uint8_t[buffer->
GetSize ()];
1545 std::string requestString = std::string((
char*)b1);
1549 parser.
Parse(&request, requestString);
1562 uint8_t *b2 =
new uint8_t[completePacket->
GetSize ()];
1564 std::string s2 = std::string((
char*)b2);
1567 parser.
Parse(&request2, s2);
1594 jresponse = nlohmann::json::parse(payload);
1596 if (methodType == 0) {
1600 }
else if (methodType == 1){
1604 }
else if (methodType == 2) {
1623 responseStatus == HTTPMessage::HttpStatus::BadRequest ||
1624 responseStatus == HTTPMessage::HttpStatus::Unauthorized ||
1625 responseStatus == HTTPMessage::HttpStatus::ServiceUnavailable
1628 NS_FATAL_ERROR(
this <<
"QKDApp014 received ERROR status information from local KMS" << jstatusResponse.dump() );
1630 }
else if (responseStatus == HTTPMessage::HttpStatus::Ok){
1632 NS_LOG_FUNCTION(
this <<
"QKDApp014 received status information from local KMS" );
1637 NS_FATAL_ERROR(
this <<
"Unsupported error status code" << responseStatus <<
"of response.");
1649 if(jGetKeyResponse.empty())
1653 if (jGetKeyResponse.contains(
"ksid"))
1654 ksid = jGetKeyResponse[
"ksid"];
1658 responseStatus == HTTPMessage::HttpStatus::BadRequest ||
1659 responseStatus == HTTPMessage::HttpStatus::Unauthorized ||
1660 responseStatus == HTTPMessage::HttpStatus::ServiceUnavailable
1663 if (jGetKeyResponse.contains(
"message"))
1665 if (jGetKeyResponse[
"message"] == std::string {
"requested parameters do not adhere to KMS rules"})
1667 else if (jGetKeyResponse[
"message"] == std::string {
"insufficient amount of key material"})
1669 else if (jGetKeyResponse[
"message"] == std::string {
"keys are being transformed"})
1677 }
else if (responseStatus == HTTPMessage::HttpStatus::Ok){
1679 NS_LOG_FUNCTION(
this <<
"Primary QKDApp014 received requested number of keys" << jGetKeyResponse.dump() );
1684 std::vector<std::string> keysToNegotiate;
1685 for (nlohmann::json::iterator it = jGetKeyResponse[
"keys"].begin(); it != jGetKeyResponse[
"keys"].end(); ++it) {
1686 key.key = (it.value())[
"key"];
1687 key.keyId = (it.value())[
"key_ID"];
1688 key.keyType = keyType;
1694 keysToNegotiate.push_back(key.keyId);
1703 NS_FATAL_ERROR(
this <<
"Unsupported error status code" << responseStatus <<
"of response.");
1717 if (jGetKeyWithKeyIDsResponse.contains(
"ksid"))
1718 ksid = jGetKeyWithKeyIDsResponse[
"ksid"];
1722 responseStatus == HTTPMessage::HttpStatus::BadRequest ||
1723 responseStatus == HTTPMessage::HttpStatus::Unauthorized ||
1724 responseStatus == HTTPMessage::HttpStatus::ServiceUnavailable
1727 NS_FATAL_ERROR(
this <<
"Replica QKDApp014 received ERROR response on key request" << jGetKeyWithKeyIDsResponse.dump() );
1731 }
else if (responseStatus == HTTPMessage::HttpStatus::Ok) {
1733 NS_LOG_FUNCTION(
this <<
"Replica QKDApp014 received requested keys" << jGetKeyWithKeyIDsResponse.dump() );
1737 for (nlohmann::json::iterator it = jGetKeyWithKeyIDsResponse[
"keys"].begin(); it != jGetKeyWithKeyIDsResponse[
"keys"].end(); ++it) {
1739 key.key = (it.value())[
"key"];
1740 key.keyId = (it.value())[
"key_ID"];
1750 NS_FATAL_ERROR(
this <<
"Unsupported HTTP status code" << responseStatus <<
"of response");
1760 std::string receivedStatus = p->
ToString();
1764 if (receivedStatus.find(
"Fragment") != std::string::npos) {
1768 std::make_pair (from, Create<Packet> (0))
1771 buffer = itBuffer->second;
1782 uint8_t *b1 =
new uint8_t[buffer->
GetSize ()];
1784 std::string requestString = std::string((
char*)b1);
1788 parser.
Parse(&request, requestString);
1803 uint8_t *b2 =
new uint8_t[completePacket->
GetSize ()];
1805 std::string s2 = std::string((
char*)b2);
1808 parser.
Parse(&request2, s2);
1829 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Primary QKDApp014 received response from Replica QKDApp014. Packet ID" << packet->
GetUid());
1832 if (header.
GetStatus() == HTTPMessage::HttpStatus::Ok) {
1836 for (uint i = 0; i < keyIds.size(); i++) {
1839 std::map<std::string, QKDApp014::QKDApp014Key>::iterator it;
1844 NS_LOG_DEBUG(
this <<
"Key " << keyIds[i] <<
" was not found in the temporary key store!" );
1847 if ((it->second).keyType == 0)
1862 NS_LOG_DEBUG (
this <<
"The attempt to negotiate keys failed.");
1865 NS_LOG_FUNCTION(
this <<
"Application is submitting a new GET_KEY request ...");
1873 NS_LOG_DEBUG(
this <<
"Key" << keyID <<
"was not found in the temporary key store!");
1889 jKeyIDs = nlohmann::json::parse(payload);
1891 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Replica QKDApp014 received proposal from Primary QKDApp014. Packet ID" << packet->
GetUid() << jKeyIDs);
1915 key_IDs[
"ksid"] = ksid;
1916 for (uint i = 0; i < keyIds.size(); i++) {
1917 key_IDs[
"key_IDs"].push_back({ {
"key_ID", keyIds[i] } });
1920 std::string msg = key_IDs.dump();
1925 std::string hMessage = httpMessage.
ToString();
1927 (uint8_t*) (hMessage).c_str(),
1937 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Primary QKDApp014 sends proposal to Replica QKDApp014. Packet ID" << packet->
GetUid() << packet->
GetSize());
1944 std::string hMessage = httpMessage.
ToString();
1946 (uint8_t*) (hMessage).c_str(),
1955 NS_LOG_FUNCTION(
this <<
"APP-SIGNALING: Replica QKDApp014 sends respond to Primary QKDApp014. Packet ID" << packet->
GetUid() );
1999 "for AppTransitionTree()!");
2008 "for AppTransitionTree()!");
2027 return "NOT_STARTED";
2030 return "INITIALIZED";
2042 return "DECRYPT_DATA";
2049 return "FATAL_ERROR";
2070 for (std::multimap<std::string, std::string>::iterator iter =
2074 if(iter->first == oldState && iter->second == newState){
2076 NS_LOG_DEBUG (
this <<
" QKDApp014 " << oldState <<
" --> " << newState <<
".");
2082 if(found ==
false) {
2083 NS_FATAL_ERROR (
"Unsupported transition from " << oldState <<
" to " << newState);
2099 uint32_t encryptionType,
2100 uint32_t authenticationType,
2101 uint32_t authenticationTagLengthInBits
2104 NS_LOG_FUNCTION (
this << encryptionType << authenticationType << authenticationTagLengthInBits);
2106 switch (encryptionType){
2118 switch (authenticationType){
2137 authenticationTagLengthInBits
2143 authenticationTagLengthInBits
2158 std::string confidentialMessage;
2159 static const char alphanum[] =
2161 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2162 "abcdefghijklmnopqrstuvwxyz";
2164 uint32_t randVal = 0;
2165 for (uint32_t i = 0; i < msgLength; ++i){
2167 confidentialMessage += alphanum[ randVal ];
2170 return confidentialMessage;
2177 keyId.erase(std::remove(keyId.begin(), keyId.end(),
'-'), keyId.end());
2185 keyId.insert(8,
"-");
2186 keyId.insert(13,
"-");
2187 keyId.insert(18,
"-");
2188 keyId.insert(23,
"-");
2208 return CryptoPP::AES::MAX_KEYLENGTH * 8;
2225 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(void) 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.
void Parse(HTTPMessage *httpMessage, const std::string &buffer)
Parse a std::string to a HTTP message.
uint16_t GetPort(void) const
Ipv4Address GetIpv4(void) const
static bool IsMatchingType(const Address &address)
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(void)
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 CopyData(uint8_t *buffer, uint32_t size) const
Copy the packet contents to a byte buffer.
std::string ToString(void) const
Return a string representation of the packet.
void RemoveAtStart(uint32_t size)
Remove size bytes from the start of the current packet.
uint64_t GetUid(void) const
Returns the packet's Uid.
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.
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
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 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 EventId Schedule(Time const &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
static Time Now(void)
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 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.
void SetAcceptCallback(Callback< bool, Ptr< Socket >, const Address & > connectionRequest, Callback< void, Ptr< Socket >, const Address & > newConnectionCreated)
Accept connection requests from remote hosts.
virtual int ShutdownRecv(void)=0
virtual int Listen(void)=0
Listen for incoming connections.
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(void)=0
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual int Close(void)=0
Close a socket.
void SetCloseCallbacks(Callback< void, Ptr< Socket > > normalClose, Callback< void, Ptr< Socket > > errorClose)
Detect socket recv() events such as graceful shutdown or error.
void SetRecvCallback(Callback< void, Ptr< Socket > > receivedData)
Notify application when new data is available to be read.
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 Bind(const Address &address)=0
Allocate a local endpoint for this socket.
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(void)
Get the type ID.
Simulation virtual time values and global simulation resolution.
AttributeValue implementation for Time.
a unique identifier for an interface.
TypeId SetParent(TypeId tid)
Set the parent TypeId.
AttributeValue implementation for 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(void)
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,...
Ptr< const AttributeAccessor > MakeTimeAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Ptr< const AttributeAccessor > MakeTypeIdAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Ptr< const AttributeChecker > MakeTypeIdChecker(void)
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method.
Callback< R, Ts... > MakeNullCallback(void)
#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.
basic_json<> json
default JSON class
NLOHMANN_BASIC_JSON_TPL_DECLARATION std::string to_string(const NLOHMANN_BASIC_JSON_TPL &j)
user-defined to_string function for JSON values
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeChecker > MakeTimeChecker(const Time min, const Time max)
Helper to make a Time checker with bounded range.
Callback< R, Ts... > MakeCallback(R(T::*memPtr)(Ts...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
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