-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIDSRuleEngine.cpp
More file actions
445 lines (380 loc) · 14.8 KB
/
Copy pathIDSRuleEngine.cpp
File metadata and controls
445 lines (380 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// ============================================================
// Project 5: Intrusion Detection Rule Engine (Snort-like)
// OOP: Rule, Event, Engine, RuleSet classes
// DSA: Pattern matching, Hash Maps, Priority Queue, vectors
// Domain: Cybersecurity
// ============================================================
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <ctime>
using namespace std;
// ---------- Severity Levels ----------
enum class Severity { LOW = 1, MEDIUM = 2, HIGH = 3, CRITICAL = 4 };
string severityStr(Severity s) {
switch(s) {
case Severity::LOW: return "LOW";
case Severity::MEDIUM: return "MEDIUM";
case Severity::HIGH: return "HIGH";
case Severity::CRITICAL: return "CRITICAL";
}
return "";
}
string severityColor(Severity s) {
switch(s) {
case Severity::LOW: return "[LOW] ";
case Severity::MEDIUM: return "[MEDIUM] ";
case Severity::HIGH: return "[HIGH] ";
case Severity::CRITICAL: return "[CRITICAL]";
}
return "";
}
// ---------- Network Event ----------
struct NetworkEvent {
int id;
string srcIP;
string dstIP;
int srcPort;
int dstPort;
string protocol;
string payload;
int packetSize;
int ttl;
string timestamp;
string httpMethod;
string httpPath;
int responseCode;
NetworkEvent(int id, string src, string dst, int sp, int dp,
string proto, string pl, int sz = 500, int ttl = 64)
: id(id), srcIP(src), dstIP(dst), srcPort(sp), dstPort(dp),
protocol(proto), payload(pl), packetSize(sz), ttl(ttl),
responseCode(0) {
time_t t = time(nullptr);
char buf[20];
strftime(buf, sizeof(buf), "%H:%M:%S", localtime(&t));
timestamp = buf;
}
void print() const {
cout << " Event #" << id << ": " << srcIP << ":" << srcPort
<< " -> " << dstIP << ":" << dstPort
<< " [" << protocol << "] "
<< "payload=" << (payload.length() > 30 ? payload.substr(0,30)+"..." : payload)
<< "\n";
}
};
// ---------- Detection Alert ----------
struct Alert {
int severity;
string ruleName;
string category;
string message;
int eventId;
string srcIP;
bool operator<(const Alert& other) const {
return severity < other.severity;
}
};
// ---------- Base Rule ----------
class Rule {
protected:
string name;
string category;
Severity severity;
string description;
int matchCount = 0;
public:
Rule(string n, string cat, Severity sev, string desc)
: name(n), category(cat), severity(sev), description(desc) {}
virtual bool matches(const NetworkEvent& e) const = 0;
virtual ~Rule() {}
string getName() const { return name; }
string getCategory() const { return category; }
Severity getSeverity() const { return severity; }
string getDescription() const { return description; }
int getMatchCount() const { return matchCount; }
void incrementMatch() { matchCount++; }
};
// ---------- Signature-Based Rules ----------
// Keyword match in payload
class PayloadRule : public Rule {
vector<string> keywords;
public:
PayloadRule(string n, string cat, Severity sev, string desc, vector<string> kw)
: Rule(n, cat, sev, desc), keywords(kw) {}
bool matches(const NetworkEvent& e) const override {
string pl = e.payload;
transform(pl.begin(), pl.end(), pl.begin(), ::tolower);
for (auto& kw : keywords) {
string k = kw;
transform(k.begin(), k.end(), k.begin(), ::tolower);
if (pl.find(k) != string::npos) return true;
}
return false;
}
};
// Specific port monitoring
class PortRule : public Rule {
vector<int> ports;
bool srcOrDst; // true=dst, false=src
public:
PortRule(string n, string cat, Severity sev, string desc, vector<int> p, bool dst=true)
: Rule(n, cat, sev, desc), ports(p), srcOrDst(dst) {}
bool matches(const NetworkEvent& e) const override {
int port = srcOrDst ? e.dstPort : e.srcPort;
return find(ports.begin(), ports.end(), port) != ports.end();
}
};
// IP Blacklist
class BlacklistRule : public Rule {
vector<string> blacklist;
public:
BlacklistRule(string n, string desc, vector<string> ips)
: Rule(n, "BLACKLIST", Severity::CRITICAL, desc), blacklist(ips) {}
bool matches(const NetworkEvent& e) const override {
return find(blacklist.begin(), blacklist.end(), e.srcIP) != blacklist.end();
}
};
// Packet size anomaly
class PacketSizeRule : public Rule {
int minSize, maxSize;
public:
PacketSizeRule(string n, string desc, int mn, int mx)
: Rule(n, "ANOMALY", Severity::MEDIUM, desc), minSize(mn), maxSize(mx) {}
bool matches(const NetworkEvent& e) const override {
return e.packetSize < minSize || e.packetSize > maxSize;
}
};
// Protocol anomaly
class ProtocolRule : public Rule {
string expectedProto;
int monitoredPort;
public:
ProtocolRule(string n, string desc, string proto, int port)
: Rule(n, "ANOMALY", Severity::HIGH, desc),
expectedProto(proto), monitoredPort(port) {}
bool matches(const NetworkEvent& e) const override {
return e.dstPort == monitoredPort && e.protocol != expectedProto;
}
};
// ---------- Rate-Based Rule (stateful) ----------
class RateRule : public Rule {
unordered_map<string, int>& counter;
int threshold;
public:
RateRule(string n, string cat, Severity sev, string desc,
unordered_map<string, int>& cnt, int thresh)
: Rule(n, cat, sev, desc), counter(cnt), threshold(thresh) {}
bool matches(const NetworkEvent& e) const override {
return counter[e.srcIP] > threshold;
}
};
// ---------- Rule Engine ----------
class IDSEngine {
private:
vector<Rule*> rules;
priority_queue<Alert> alertQueue;
unordered_map<string, int> connectionCount;
unordered_map<string, int> portScanCount;
map<string, int> alertsByCategory;
int totalEvents = 0;
int flaggedEvents = 0;
string getTimestamp() {
time_t t = time(nullptr);
char buf[20];
strftime(buf, sizeof(buf), "%H:%M:%S", localtime(&t));
return buf;
}
public:
IDSEngine() {
// SQL Injection detection
rules.push_back(new PayloadRule(
"SQL_INJECTION", "WEB_ATTACK", Severity::CRITICAL,
"SQL Injection attempt detected",
{"' OR '1'='1", "UNION SELECT", "DROP TABLE", "'; --", "1=1", "xp_cmdshell", "EXEC("}
));
// XSS detection
rules.push_back(new PayloadRule(
"XSS_ATTACK", "WEB_ATTACK", Severity::HIGH,
"Cross-Site Scripting (XSS) attempt",
{"<script>", "javascript:", "onerror=", "onload=", "alert(", "document.cookie"}
));
// Command injection
rules.push_back(new PayloadRule(
"CMD_INJECTION", "WEB_ATTACK", Severity::CRITICAL,
"Command injection attempt",
{"; rm -rf", "| cat /etc/passwd", "&& wget", "$(curl", "`whoami`", "../../../etc"}
));
// Malware signatures
rules.push_back(new PayloadRule(
"MALWARE_SIG", "MALWARE", Severity::CRITICAL,
"Known malware signature detected",
{"X5O!P%@AP[4\\PZX54(P^)7CC)7}", "EICAR", "eval(base64_decode", "powershell -enc"}
));
// Suspicious admin ports
rules.push_back(new PortRule(
"ADMIN_PORT_ACCESS", "POLICY", Severity::MEDIUM,
"Access to privileged admin port",
{22, 23, 3389, 5900, 5985}, true
));
// Database ports
rules.push_back(new PortRule(
"DB_PORT_EXPOSED", "POLICY", Severity::HIGH,
"Direct database port access from external",
{3306, 5432, 1433, 27017, 6379}, true
));
// Known malicious IPs
rules.push_back(new BlacklistRule(
"BLACKLISTED_IP", "Known malicious IP address",
{"45.33.32.156", "198.51.100.99", "203.0.113.42", "10.0.99.99"}
));
// Packet size anomaly
rules.push_back(new PacketSizeRule(
"OVERSIZED_PACKET", "Packet size exceeds normal bounds", 0, 1500
));
// Wrong protocol on port (e.g. UDP on port 80)
rules.push_back(new ProtocolRule(
"PROTO_ANOMALY_HTTP", "Non-TCP traffic on HTTP port", "TCP", 80
));
// Brute force (rate-based)
rules.push_back(new RateRule(
"BRUTE_FORCE", "AUTH_ATTACK", Severity::HIGH,
"Possible brute force attack (high connection rate)",
connectionCount, 5
));
}
~IDSEngine() {
for (auto r : rules) delete r;
}
void processEvent(NetworkEvent& e) {
totalEvents++;
connectionCount[e.srcIP]++;
bool wasFlagged = false;
for (auto* rule : rules) {
if (rule->matches(e)) {
rule->incrementMatch();
alertsByCategory[rule->getCategory()]++;
int sev = (int)rule->getSeverity();
alertQueue.push({sev, rule->getName(), rule->getCategory(),
rule->getDescription(), e.id, e.srcIP});
if (!wasFlagged) {
flaggedEvents++;
wasFlagged = true;
}
cout << " " << severityColor(rule->getSeverity())
<< " " << setw(20) << rule->getName()
<< " | " << e.srcIP << ":" << e.srcPort
<< " -> " << e.dstIP << ":" << e.dstPort << "\n";
}
}
if (!wasFlagged) {
cout << " [CLEAN] " << " "
<< " | " << e.srcIP << " -> " << e.dstIP
<< ":" << e.dstPort << "\n";
}
}
void printAlerts() {
cout << "\n========================================\n";
cout << " ALERT QUEUE (by severity)\n";
cout << "========================================\n";
priority_queue<Alert> copy = alertQueue;
while (!copy.empty()) {
Alert a = copy.top(); copy.pop();
Severity s = (Severity)a.severity;
cout << " " << severityColor(s)
<< " " << setw(20) << a.ruleName
<< " | Event #" << a.eventId
<< " | " << a.srcIP
<< "\n >> " << a.message << "\n";
}
}
void printStats() {
cout << "\n========================================\n";
cout << " ENGINE STATISTICS\n";
cout << "========================================\n";
cout << " Total Events Processed : " << totalEvents << "\n";
cout << " Flagged Events : " << flaggedEvents << "\n";
cout << " Alert Rate : "
<< fixed << setprecision(1)
<< (totalEvents ? (double)flaggedEvents/totalEvents*100 : 0.0) << "%\n";
cout << "\n Alerts by Category:\n";
for (auto& p : alertsByCategory)
cout << " " << setw(15) << p.first << " : " << p.second << " alerts\n";
cout << "\n Top Offending IPs:\n";
vector<pair<string,int>> sorted(connectionCount.begin(), connectionCount.end());
sort(sorted.begin(), sorted.end(), [](auto& a, auto& b){ return a.second > b.second; });
for (int i = 0; i < min(5, (int)sorted.size()); i++)
cout << " " << setw(16) << sorted[i].first << " : " << sorted[i].second << " events\n";
cout << "\n Rule Hit Counts:\n";
for (auto* r : rules)
if (r->getMatchCount() > 0)
cout << " " << setw(25) << r->getName()
<< " : " << r->getMatchCount() << " matches\n";
}
};
// ---------- Main ----------
int main() {
cout << "========================================\n";
cout << " Intrusion Detection Rule Engine\n";
cout << "========================================\n\n";
IDSEngine engine;
cout << "[*] Processing network events...\n\n";
cout << string(75, '-') << "\n";
cout << " Status " << " Rule "
<< " | Connection Details\n";
cout << string(75, '-') << "\n";
// Normal traffic
NetworkEvent e1(1, "192.168.1.10", "192.168.1.1", 54321, 80, "TCP",
"GET /index.html HTTP/1.1 Host: example.com");
engine.processEvent(e1);
// SQL Injection attempt
NetworkEvent e2(2, "203.0.113.7", "192.168.1.50", 9876, 80, "TCP",
"GET /login?user=admin' OR '1'='1&pass=x HTTP/1.1");
engine.processEvent(e2);
// XSS attempt
NetworkEvent e3(3, "172.16.0.99", "192.168.1.50", 43210, 80, "TCP",
"POST /comment body=<script>alert(document.cookie)</script>");
engine.processEvent(e3);
// Command injection
NetworkEvent e4(4, "198.51.100.99", "192.168.1.50", 11111, 80, "TCP",
"GET /ping?host=127.0.0.1; rm -rf / --no-preserve-root");
engine.processEvent(e4);
// Blacklisted IP
NetworkEvent e5(5, "45.33.32.156", "192.168.1.1", 54322, 443, "TCP",
"GET /admin HTTP/1.1");
engine.processEvent(e5);
// SSH brute force
for (int i = 6; i <= 12; i++) {
NetworkEvent e(i, "10.0.99.99", "192.168.1.1", 50000+i, 22, "TCP",
"SSH auth attempt " + to_string(i));
engine.processEvent(e);
}
// Malware signature
NetworkEvent e13(13, "192.168.1.77", "10.10.10.10", 6666, 4444, "TCP",
"X5O!P%@AP[4\\PZX54(P^)7CC)7} EICAR test");
engine.processEvent(e13);
// DB port access
NetworkEvent e14(14, "203.0.113.10", "192.168.1.20", 9000, 3306, "TCP",
"mysql connect root");
engine.processEvent(e14);
// Protocol anomaly (UDP on port 80)
NetworkEvent e15(15, "172.16.0.5", "192.168.1.1", 12345, 80, "UDP",
"suspicious udp payload");
engine.processEvent(e15);
// Oversized packet
NetworkEvent e16(16, "192.168.1.88", "8.8.8.8", 54400, 53, "UDP",
"large dns query", 2000);
engine.processEvent(e16);
// Normal HTTPS
NetworkEvent e17(17, "192.168.1.5", "93.184.216.34", 49152, 443, "TCP",
"TLS ClientHello");
engine.processEvent(e17);
engine.printAlerts();
engine.printStats();
return 0;
}