Zero Trust IoT library
Loading...
Searching...
No Matches
mitm-mitigation.cc
Go to the documentation of this file.
1
6#include "ns3/core-module.h"
7#include "ns3/network-module.h"
8#include "ns3/internet-module.h"
9#include "ns3/point-to-point-module.h"
10#include "ns3/applications-module.h"
11#include "ns3/zt-certificate.h"
12#include "ns3/zt-policy-engine.h"
13#include "ns3/zt-encryption-utils.h"
14#include "ns3/zt-logger.h"
15#include "ns3/zt-tls-handshake.h"
16
17using namespace ns3;
18
19// ==== Globals ====
20
22Ptr<ZtTlsHandshake> handshake;
23
25Ptr<ZtPolicyEngine> policyEngine;
26
29
31uint16_t port = 9000;
32
37void ReceiveAtGateway(Ptr<Socket> socket)
38{
39 Ptr<Packet> packet = socket->Recv();
40 uint32_t size = packet->GetSize();
41 std::vector<uint8_t> buffer(size);
42 packet->CopyData(buffer.data(), size);
43 std::string encrypted(buffer.begin(), buffer.end());
44
45 uint32_t selfId = 1;
46 if (!handshake->HasSession(selfId)) {
47 ZtLogger::Log("GATEWAY", "Rejected packet: no valid session with sender.");
48 return;
49 }
50
51 std::string sessionKeyHex = handshake->GetSessionKey(selfId);
52 std::string decrypted;
53 try {
54 decrypted = ns3::DecryptPayload(encrypted, ns3::HexDecodeKey(sessionKeyHex).BytePtr());
55 } catch (...) {
56 ZtLogger::Log("GATEWAY", "Decryption failed: corrupted or spoofed packet.");
57 return;
58 }
59
60 if (decrypted.find("temperature") != std::string::npos) {
61 ZtLogger::Log("GATEWAY", "Valid encrypted payload received from Sensor.");
62 ZtLogger::Log("GATEWAY", "Valid encrypted payload received from Sensor: " + decrypted);
63 } else {
64 ZtLogger::Log("GATEWAY", "Rejected packet: payload failed validation.");
65 }
66}
67
74void SendFromSensor(Ptr<Socket> socket, Address gatewayAddr, uint32_t nodeId)
75{
76 std::string cert = ca.SignIdentity(nodeId, "IoTDevice", std::time(nullptr) + 300);
77 ZtLogger::LogCertIssued(nodeId, "IoTDevice", std::time(nullptr) + 300);
78
79 if (!policyEngine->AuthorizeWithCert(nodeId, "IoTDevice", cert)) {
80 ZtLogger::LogCertRejected("Sensor not authorized");
81 return;
82 }
83
84 handshake->StartHandshake(socket->GetNode(), NodeList::GetNode(1), nodeId, 1);
85
86 if (!handshake->HasSession(1)) {
87 ZtLogger::Log("TLS", "Handshake failed with gateway");
88 return;
89 }
90
91 std::string sessionKeyHex = handshake->GetSessionKey(1);
92 std::string ivOut;
93 std::string payload = "temperature=26.3";
94 std::string encrypted = ns3::EncryptPayload(payload, ns3::HexDecodeKey(sessionKeyHex).BytePtr(), ivOut);
95
96 ZtLogger::LogEncryption("[payload hidden]", ivOut);
97
98 socket->Connect(InetSocketAddress(InetSocketAddress::ConvertFrom(gatewayAddr).GetIpv4(), port));
99 socket->Send(reinterpret_cast<const uint8_t *>(encrypted.c_str()), encrypted.size(), 0);
100}
101
107void AttackerSpoof(Ptr<Socket> socket, Address gatewayAddr)
108{
109 std::string fakeData = "temperature=99.9";
110 socket->Connect(InetSocketAddress(InetSocketAddress::ConvertFrom(gatewayAddr).GetIpv4(), port));
111 socket->Send(reinterpret_cast<const uint8_t *>(fakeData.c_str()), fakeData.size(), 0);
112
113 ZtLogger::Log("ATTACKER", "Sent spoofed plaintext");
114}
115
122int main(int argc, char *argv[])
123{
124 NodeContainer nodes;
125 nodes.Create(3);
126 Names::Add("sensor", nodes.Get(0));
127 Names::Add("gateway", nodes.Get(1));
128 Names::Add("attacker", nodes.Get(2));
129
130 InternetStackHelper stack;
131 stack.Install(nodes);
132
133 PointToPointHelper p2p;
134 p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
135 p2p.SetChannelAttribute("Delay", StringValue("2ms"));
136 p2p.Install(nodes.Get(0), nodes.Get(1));
137 p2p.Install(nodes.Get(2), nodes.Get(1));
138
139 Ipv4AddressHelper ip;
140 ip.SetBase("10.1.1.0", "255.255.255.0");
141 Ipv4InterfaceContainer interfaces1 = ip.Assign(p2p.Install(nodes.Get(0), nodes.Get(1)));
142
143 ip.SetBase("10.1.2.0", "255.255.255.0");
144 Ipv4InterfaceContainer interfaces2 = ip.Assign(p2p.Install(nodes.Get(2), nodes.Get(1)));
145
146 Ipv4GlobalRoutingHelper::PopulateRoutingTables();
147
148 // Setup Zero Trust components
149 policyEngine = CreateObject<ZtPolicyEngine>();
150 policyEngine->AddAuthorized(0, "client");
151 policyEngine->AddAuthorized(1, "server");
152 policyEngine->SetCaPublicKey(ca.GetPublicKey());
153
154 handshake = CreateObject<ZtTlsHandshake>();
155 handshake->SetPolicyValidator([](uint32_t nodeId, std::string role) {
156 return policyEngine->Authorize(nodeId, role);
157 });
158
160
161 // Gateway listener
162 Ptr<Socket> recvSocket = Socket::CreateSocket(nodes.Get(1), TypeId::LookupByName("ns3::UdpSocketFactory"));
163 recvSocket->Bind(InetSocketAddress(Ipv4Address::GetAny(), port));
164 recvSocket->SetRecvCallback(MakeCallback(&ReceiveAtGateway));
165
166 // Legitimate sensor send
167 Ptr<Socket> sensorSock = Socket::CreateSocket(nodes.Get(0), TypeId::LookupByName("ns3::UdpSocketFactory"));
168 Simulator::Schedule(Seconds(1.0), &SendFromSensor, sensorSock, InetSocketAddress(interfaces1.GetAddress(1), port), 0);
169
170 // Attacker spoof
171 Ptr<Socket> attackerSock = Socket::CreateSocket(nodes.Get(2), TypeId::LookupByName("ns3::UdpSocketFactory"));
172 Simulator::Schedule(Seconds(1.5), &AttackerSpoof, attackerSock, InetSocketAddress(interfaces2.GetAddress(1), port));
173
174 Simulator::Run();
175 Simulator::Destroy();
176 return 0;
177}
178
Issues and signs certificates for Zero Trust identity validation.
CryptoPP::RSA::PublicKey GetPublicKey() const
Retrieves the public RSA key of the CA.
std::string SignIdentity(uint32_t nodeId, const std::string &role, time_t expiry)
Signs an identity certificate with node ID, role, and expiry.
static void LogCertRejected(const std::string &reason)
Logs a rejected certificate attempt with a reason.
Definition zt-logger.cc:75
static void LogCertIssued(uint32_t nodeId, const std::string &role, time_t expiry)
Logs a certificate issuance event.
Definition zt-logger.cc:46
static void EnableTimestamps(bool enable)
Enables or disables timestamp logging.
Definition zt-logger.cc:16
static void Log(const std::string &tag, const std::string &message)
Logs a general message with a specified tag.
Definition zt-logger.cc:25
static void LogEncryption(const std::string &payload, const std::string &ivHex)
Logs an encryption event with payload and IV.
Definition zt-logger.cc:86
void SendFromSensor(Ptr< Socket > socket, Address gatewayAddr, uint32_t nodeId)
Simulates a sensor device sending an encrypted payload to the gateway after policy and handshake vali...
void AttackerSpoof(Ptr< Socket > socket, Address gatewayAddr)
Simulates an attacker sending a spoofed plaintext message to the gateway without encryption.
int main(int argc, char *argv[])
Main entry point for the simulation. Sets up network topology, installs security components,...
CertificateAuthority ca
Certificate authority for signing identity certificates.
Ptr< ZtPolicyEngine > policyEngine
Policy engine for authorization based on identity and roles.
void ReceiveAtGateway(Ptr< Socket > socket)
Receives an encrypted packet at the gateway and performs decryption and validation.
uint16_t port
UDP communication port used by gateway.
Ptr< ZtTlsHandshake > handshake
TLS handshake manager for establishing secure sessions.
std::string EncryptPayload(const std::string &data, const byte *key, std::string &ivOut)
Encrypts a plaintext string using AES-CBC mode with a randomly generated IV.
std::string DecryptPayload(const std::string &cipher, const byte *key)
Decrypts a ciphertext string encrypted with EncryptPayload.
SecByteBlock HexDecodeKey(const std::string &hex)
Decodes a hex-encoded AES key string into a raw key byte block.