-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoE-Honeypot.ino
More file actions
602 lines (508 loc) · 18.4 KB
/
Copy pathPoE-Honeypot.ino
File metadata and controls
602 lines (508 loc) · 18.4 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/*
* PoE-Honeypot.ino
*
* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
* https://github.com/Xorlent/PoE-Honeypot
*
* Raw Socket Implementation - Now monitors unlimited ports and ICMP types
* Designed for M5Stack Unit-PoE-P4 or other device with sufficient resources
*
* CONFIGURATION: All user-configurable settings are in Config.h
* Edit Config.h to customize your honeypot deployment.
*/
#include "Config.h"
////////--------------------------------------- DO NOT EDIT ANYTHING BELOW THIS LINE ---------------------------------------////////
#include <ETH.h>
#include <WiFiUdp.h>
#include <NTP.h>
#include <lwip/ip.h>
#include <lwip/tcp.h>
#include <lwip/udp.h>
#include <lwip/icmp.h>
#include <lwip/raw.h>
#include <lwip/prot/tcp.h>
#include "HoneypotLogging.h"
#include "ConfigValidation.h"
// Define TCP structures and flags if not already available
#ifndef TCPH_FLAGS
#define TCPH_FLAGS(phdr) (lwip_ntohs((phdr)->_hdrlen_rsvd_flags) & 0xFF)
#endif
#ifndef TCP_SYN
#define TCP_SYN 0x02U
#endif
#ifndef TCP_ACK
#define TCP_ACK 0x10U
#endif
#define ETH_ADDR 1
#define ETH_POWER_PIN 51
#define ETH_TYPE ETH_PHY_TLK110
#define ETH_PHY_MDC 31
#define ETH_PHY_MDIO 52
#define ETH_CLK_MODE EMAC_CLK_EXT_IN
////////--------------------------------------- Create runtime objects ---------------------------------------////////
// Compile-time array size validation
static_assert(honeypotNumPorts <= 65535, "TCP port array exceeds maximum size");
static_assert(honeypotNumUDPPorts <= 65535, "UDP port array exceeds maximum size");
static_assert(honeypotNumICMPTypes <= 255, "ICMP type array exceeds maximum size");
// Port bitmaps for O(1) lookups (65536 ports = 8192 bytes each)
// Bit N set = port N is monitored
uint8_t tcpPortBitmap[8192];
uint8_t udpPortBitmap[8192];
// Set bit in bitmap (mark port as monitored)
inline void setBitInBitmap(uint8_t* bitmap, uint16_t port) {
bitmap[port >> 3] |= (1 << (port & 0x07));
}
// Check if bit set in bitmap (is port monitored?)
inline bool isBitSetInBitmap(const uint8_t* bitmap, uint16_t port) {
return (bitmap[port >> 3] & (1 << (port & 0x07))) != 0;
}
// Syslog and NTP clients
WiFiUDP syslog;
NTP ntp(syslog);
// Logging system
HoneypotLogging logger(hostName, ip, syslogSvr, syslogPort, DEBUG,
TCP_HOLDOFF_SECONDS, UDP_HOLDOFF_SECONDS, ICMP_HOLDOFF_SECONDS,
&syslog, &ntp,
USE_SMTP, smtpServer, smtpPort, smtpFromAddr, smtpToAddr);
// Raw sockets for packet capture (one per protocol)
struct raw_pcb *tcp_raw_socket;
struct raw_pcb *udp_raw_socket;
struct raw_pcb *icmp_raw_socket;
// NTP update tracking
unsigned long lastNTP = 0;
// Static string constants for suspicious traffic logging
static const char* const SUSPICIOUS_TCP_FRAGMENT = "TCP-fragment";
static const char* const SUSPICIOUS_UDP_FRAGMENT = "UDP-fragment";
static const char* const SUSPICIOUS_ICMP_FRAGMENT = "ICMP-fragment";
static const char* const SUSPICIOUS_UNKNOWN_FRAGMENT = "unknown-fragment";
static const char* const SUSPICIOUS_TCP_IP_OPTIONS = "TCP-ip-options";
static const char* const SUSPICIOUS_UDP_IP_OPTIONS = "UDP-ip-options";
static const char* const SUSPICIOUS_ICMP_IP_OPTIONS = "ICMP-ip-options";
static const char* const SUSPICIOUS_UNKNOWN_IP_OPTIONS = "unknown-ip-options";
////////--------------------------------------- End create runtime objects ---------------------------------------////////
// Check if TCP port is monitored (O(1) bitmap lookup)
bool isHoneypotTCPPort(uint16_t port) {
return isBitSetInBitmap(tcpPortBitmap, port);
}
// Get service name for TCP port
const char* getTCPServiceName(uint16_t port) {
for(int i = 0; i < honeypotNumPorts; i++) {
if(honeypotTCPPorts[i].port == port) {
return (honeypotTCPPorts[i].service != NULL) ? honeypotTCPPorts[i].service : "unknown";
}
}
return "unknown";
}
// Check if UDP port is monitored (O(1) bitmap lookup)
bool isHoneypotUDPPort(uint16_t port) {
if (!MONITOR_UDP) return false;
return isBitSetInBitmap(udpPortBitmap, port);
}
// Get service name for UDP port
const char* getUDPServiceName(uint16_t port) {
if (!MONITOR_UDP) return "unknown";
for(int i = 0; i < honeypotNumUDPPorts; i++) {
if(honeypotUDPPorts[i].port == port) {
return (honeypotUDPPorts[i].service != NULL) ? honeypotUDPPorts[i].service : "unknown";
}
}
return "unknown";
}
// Check if ICMP type is monitored
bool isHoneypotICMPType(uint8_t type) {
if (!MONITOR_ICMP) return false;
for(int i = 0; i < honeypotNumICMPTypes; i++) {
if(honeypotICMPTypes[i].type == type) {
return true;
}
}
return false;
}
// Get name for ICMP type
const char* getICMPTypeName(uint8_t type) {
if (!MONITOR_ICMP) return "unknown";
for(int i = 0; i < honeypotNumICMPTypes; i++) {
if(honeypotICMPTypes[i].type == type) {
return (honeypotICMPTypes[i].name != NULL) ? honeypotICMPTypes[i].name : "unknown";
}
}
return "unknown";
}
// Get fragment description string for protocol
static const char* getFragmentDescription(u8_t protocol) {
switch(protocol) {
case IP_PROTO_TCP: return SUSPICIOUS_TCP_FRAGMENT;
case IP_PROTO_UDP: return SUSPICIOUS_UDP_FRAGMENT;
case IP_PROTO_ICMP: return SUSPICIOUS_ICMP_FRAGMENT;
default: return SUSPICIOUS_UNKNOWN_FRAGMENT;
}
}
// Get IP options description string for protocol
static const char* getIPOptionsDescription(u8_t protocol) {
switch(protocol) {
case IP_PROTO_TCP: return SUSPICIOUS_TCP_IP_OPTIONS;
case IP_PROTO_UDP: return SUSPICIOUS_UDP_IP_OPTIONS;
case IP_PROTO_ICMP: return SUSPICIOUS_ICMP_IP_OPTIONS;
default: return SUSPICIOUS_UNKNOWN_IP_OPTIONS;
}
}
// Update NTP if 10 minutes elapsed
void updateNTPIfNeeded() {
unsigned long currentMillis = millis();
if(currentMillis - lastNTP >= 600000) {
if(ntp.update()) {
lastNTP = currentMillis;
}
}
}
// Validate IP header, return IP header length or 0 if invalid
static u8_t validateIPHeader(struct pbuf *p, struct ip_hdr **iphdr_out) {
// Validate packet size
if (p == NULL || p->tot_len < sizeof(struct ip_hdr)) {
return 0;
}
// Ensure header in first pbuf (prevents buffer overrun)
if (p->len < sizeof(struct ip_hdr)) {
return 0;
}
struct ip_hdr *iphdr = (struct ip_hdr *)p->payload;
// Validate header length (20-60 bytes)
u8_t ip_header_len = IPH_HL(iphdr) * 4;
if (ip_header_len < 20 || ip_header_len > 60 || p->tot_len < ip_header_len) {
return 0;
}
// Ensure entire header (with options) in first pbuf
if (p->len < ip_header_len) {
return 0;
}
*iphdr_out = iphdr;
return ip_header_len;
}
// Raw packet receive callback (all protocols)
static u8_t raw_recv_callback(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr) {
// Validate packet
struct ip_hdr *iphdr;
u8_t ip_header_len = validateIPHeader(p, &iphdr);
if (ip_header_len == 0) {
if (p != NULL) pbuf_free(p);
return 1;
}
// Detect IP fragmentation (suspicious)
// Offset in 8-byte units, non-zero = fragmented
u16_t fragment_offset = (lwip_ntohs(IPH_OFFSET(iphdr)) & IP_OFFMASK) * 8;
u16_t ip_flags = lwip_ntohs(IPH_OFFSET(iphdr)) & 0xE000;
bool more_fragments = (ip_flags & IP_MF) != 0;
bool is_fragment = (fragment_offset > 0) || more_fragments;
if (is_fragment) {
// Log fragmented packet (suspicious)
uint32_t sourceIPAddr = ip4_addr_get_u32(&iphdr->src);
u8_t protocol = IPH_PROTO(iphdr);
const char* fragDesc = getFragmentDescription(protocol);
logger.enqueueLogEvent(0, sourceIPAddr, PROTO_TCP, fragDesc);
// Drop fragmented packets
pbuf_free(p);
return 1;
}
// Detect IP options (suspicious)
// Options rarely used; often indicates attacks or manipulation
if (ip_header_len > 20) {
// Log IP options (suspicious)
uint32_t sourceIPAddr = ip4_addr_get_u32(&iphdr->src);
u8_t protocol = IPH_PROTO(iphdr);
const char* optDesc = getIPOptionsDescription(protocol);
logger.enqueueLogEvent(0, sourceIPAddr, PROTO_TCP, optDesc);
// Drop packets with IP options
pbuf_free(p);
return 1;
}
u8_t protocol = IPH_PROTO(iphdr);
// Handle TCP
if (protocol == IP_PROTO_TCP) {
// Validate TCP header size
if (p->tot_len < ip_header_len + sizeof(struct tcp_hdr)) {
pbuf_free(p);
return 1;
}
// Ensure TCP header in first pbuf (not fragmented across pbufs)
if (p->len < ip_header_len + sizeof(struct tcp_hdr)) {
pbuf_free(p);
return 1;
}
// Get TCP header
struct tcp_hdr *tcphdr = (struct tcp_hdr *)((u8_t *)p->payload + ip_header_len);
// Extract destination port
uint16_t dest_port = ntohs(tcphdr->dest);
// Check for SYN without ACK (new connection)
u8_t flags = TCPH_FLAGS(tcphdr);
bool is_syn = (flags & TCP_SYN) != 0;
bool is_ack = (flags & TCP_ACK) != 0;
if (is_syn && !is_ack) {
// Check if port is monitored
if (isHoneypotTCPPort(dest_port)) {
// Extract source IP
uint32_t sourceIPAddr = ip4_addr_get_u32(&iphdr->src);
// Enqueue event for main loop processing
// Filtering (broadcast/multicast/holdoff) happens in main loop
logger.enqueueLogEvent(dest_port, sourceIPAddr, PROTO_TCP, getTCPServiceName(dest_port));
}
}
}
// Handle UDP
else if (protocol == IP_PROTO_UDP && MONITOR_UDP) {
// Validate UDP header size
if (p->tot_len < ip_header_len + sizeof(struct udp_hdr)) {
pbuf_free(p);
return 1;
}
// Ensure UDP header in first pbuf (not fragmented)
if (p->len < ip_header_len + sizeof(struct udp_hdr)) {
pbuf_free(p);
return 1;
}
// Get UDP header
struct udp_hdr *udphdr = (struct udp_hdr *)((u8_t *)p->payload + ip_header_len);
// Extract destination port
uint16_t dest_port = ntohs(udphdr->dest);
// Check if port is monitored
if (isHoneypotUDPPort(dest_port)) {
// Extract source IP
uint32_t sourceIPAddr = ip4_addr_get_u32(&iphdr->src);
// Enqueue event for main loop processing
// Filtering (broadcast/multicast/holdoff) happens in main loop
logger.enqueueLogEvent(dest_port, sourceIPAddr, PROTO_UDP, getUDPServiceName(dest_port));
}
}
// Handle ICMP
else if (protocol == IP_PROTO_ICMP && MONITOR_ICMP) {
// Validate ICMP header size
if (p->tot_len < ip_header_len + sizeof(struct icmp_echo_hdr)) {
pbuf_free(p);
return 1;
}
// Ensure ICMP header in first pbuf (not fragmented)
if (p->len < ip_header_len + sizeof(struct icmp_echo_hdr)) {
pbuf_free(p);
return 1;
}
// Extract ICMP type
struct icmp_echo_hdr *icmphdr = (struct icmp_echo_hdr *)((u8_t *)p->payload + ip_header_len);
u8_t icmp_type = ICMPH_TYPE(icmphdr);
// Check if ICMP type is monitored
if (isHoneypotICMPType(icmp_type)) {
// Extract source IP
uint32_t sourceIPAddr = ip4_addr_get_u32(&iphdr->src);
// Enqueue event for main loop processing
// Filtering (broadcast/multicast/holdoff) happens in main loop
logger.enqueueLogEvent(icmp_type, sourceIPAddr, PROTO_ICMP, getICMPTypeName(icmp_type));
}
}
pbuf_free(p);
// Return 1 = packet consumed and freed
return 1;
}
void setup() {
Serial.begin(115200);
while (!Serial) {
delay(100);
}
Serial.println("Starting...");
// Validate configuration before proceeding - halt on critical errors
if (!validateConfiguration()) {
Serial.println("HALTED: Fix configuration errors in Config.h, recompile and reflash");
while(1) {
delay(1000);
}
}
Serial.print("Monitoring ");
Serial.print(honeypotNumPorts);
Serial.print(" TCP ports");
if (MONITOR_UDP) {
Serial.print(", ");
Serial.print(honeypotNumUDPPorts);
Serial.print(" UDP ports");
}
if (MONITOR_ICMP) {
Serial.print(", ");
Serial.print(honeypotNumICMPTypes);
Serial.print(" ICMP types");
}
Serial.println();
// Initialize port bitmaps
Serial.println("Initializing port bitmaps...");
// Clear bitmaps
memset(tcpPortBitmap, 0, sizeof(tcpPortBitmap));
memset(udpPortBitmap, 0, sizeof(udpPortBitmap));
// Populate TCP bitmap
for(int i = 0; i < honeypotNumPorts; i++) {
setBitInBitmap(tcpPortBitmap, honeypotTCPPorts[i].port);
}
Serial.print(" TCP bitmap: ");
Serial.print(honeypotNumPorts);
Serial.println(" ports indexed");
// Populate UDP bitmap
if (MONITOR_UDP) {
for(int i = 0; i < honeypotNumUDPPorts; i++) {
setBitInBitmap(udpPortBitmap, honeypotUDPPorts[i].port);
}
Serial.print(" UDP bitmap: ");
Serial.print(honeypotNumUDPPorts);
Serial.println(" ports indexed");
}
// Initialize Ethernet
ETH.begin(ETH_TYPE, ETH_ADDR, ETH_PHY_MDC, ETH_PHY_MDIO, ETH_POWER_PIN, ETH_CLK_MODE);
ETH.config(ip, gateway, subnet, dns1, dns2);
while(!ETH.linkUp()) {
delay(1000);
Serial.println("Waiting for Ethernet...");
}
Serial.println("Ethernet connected.");
Serial.print("IP Address: ");
Serial.println(ETH.localIP());
// Start NTP
ntp.begin(ntpSvr);
ntp.updateInterval(3600000);
// Wait for initial NTP sync
Serial.println("Waiting for NTP sync...");
while(!ntp.update())
{
Serial.println("NTP retry...");
delay(500);
};
lastNTP = millis();
Serial.print("NTP synchronized: ");
Serial.print(ntp.formattedTime("%b %d %T "));
Serial.println("UTC");
// Initialize logging (all Serial output must be thread-safe after this)
logger.begin();
// Create raw sockets (lwIP requires separate sockets per protocol)
// Create TCP raw socket
tcp_raw_socket = raw_new(IP_PROTO_TCP);
if (tcp_raw_socket != NULL) {
raw_bind(tcp_raw_socket, IP_ADDR_ANY);
raw_recv(tcp_raw_socket, raw_recv_callback, NULL);
if (DEBUG) {
logger.safePrintln("[DEBUG] TCP raw socket created");
}
} else {
logger.safePrintln("ERROR: Could not create TCP raw socket!");
}
// UDP socket (if enabled)
if (MONITOR_UDP) {
udp_raw_socket = raw_new(IP_PROTO_UDP);
if (udp_raw_socket != NULL) {
raw_bind(udp_raw_socket, IP_ADDR_ANY);
raw_recv(udp_raw_socket, raw_recv_callback, NULL);
if (DEBUG) {
logger.safePrintln("[DEBUG] UDP raw socket created");
}
} else {
logger.safePrintln("ERROR: Could not create UDP raw socket!");
}
}
// ICMP socket (if enabled)
if (MONITOR_ICMP) {
icmp_raw_socket = raw_new(IP_PROTO_ICMP);
if (icmp_raw_socket != NULL) {
raw_bind(icmp_raw_socket, IP_ADDR_ANY);
raw_recv(icmp_raw_socket, raw_recv_callback, NULL);
if (DEBUG) {
logger.safePrintln("[DEBUG] ICMP raw socket created");
}
} else {
logger.safePrintln("ERROR: Could not create ICMP raw socket!");
}
}
// Print summary
if (tcp_raw_socket != NULL || udp_raw_socket != NULL || icmp_raw_socket != NULL) {
logger.safePrintln("Configured protocols and ports:");
// Print monitored TCP ports
if (tcp_raw_socket != NULL) {
char portList[512] = " TCP ports: ";
int offset = strlen(portList);
for(int i = 0; i < honeypotNumPorts; i++) {
int ret = snprintf(portList + offset, sizeof(portList) - offset, "%d", honeypotTCPPorts[i].port);
// Check for truncation or error
if (ret < 0 || ret >= (int)(sizeof(portList) - offset)) {
// Buffer full, indicate truncation
snprintf(portList + offset, sizeof(portList) - offset, "...");
break;
}
offset += ret;
// Add separator if not last item
if(i < honeypotNumPorts - 1) {
ret = snprintf(portList + offset, sizeof(portList) - offset, ", ");
if (ret < 0 || ret >= (int)(sizeof(portList) - offset)) {
// Buffer full, indicate truncation
snprintf(portList + offset, sizeof(portList) - offset, "...");
break;
}
offset += ret;
}
}
logger.safePrintln(portList);
}
// Print monitored UDP ports if enabled
if (udp_raw_socket != NULL && MONITOR_UDP) {
char portList[512] = " UDP ports: ";
int offset = strlen(portList);
for(int i = 0; i < honeypotNumUDPPorts; i++) {
int ret = snprintf(portList + offset, sizeof(portList) - offset, "%d", honeypotUDPPorts[i].port);
// Check for truncation or error
if (ret < 0 || ret >= (int)(sizeof(portList) - offset)) {
// Buffer full, indicate truncation
snprintf(portList + offset, sizeof(portList) - offset, "...");
break;
}
offset += ret;
// Add separator if not last item
if(i < honeypotNumUDPPorts - 1) {
ret = snprintf(portList + offset, sizeof(portList) - offset, ", ");
if (ret < 0 || ret >= (int)(sizeof(portList) - offset)) {
// Buffer full, indicate truncation
snprintf(portList + offset, sizeof(portList) - offset, "...");
break;
}
offset += ret;
}
}
logger.safePrintln(portList);
}
// Print monitored ICMP types if enabled
if (icmp_raw_socket != NULL && MONITOR_ICMP) {
char typeList[512] = " ICMP types: ";
int offset = strlen(typeList);
for(int i = 0; i < honeypotNumICMPTypes; i++) {
int ret = snprintf(typeList + offset, sizeof(typeList) - offset, "%d", honeypotICMPTypes[i].type);
// Check for truncation or error
if (ret < 0 || ret >= (int)(sizeof(typeList) - offset)) {
// Buffer full, indicate truncation
snprintf(typeList + offset, sizeof(typeList) - offset, "...");
break;
}
offset += ret;
// Add separator if not last item
if(i < honeypotNumICMPTypes - 1) {
ret = snprintf(typeList + offset, sizeof(typeList) - offset, ", ");
if (ret < 0 || ret >= (int)(sizeof(typeList) - offset)) {
// Buffer full, indicate truncation
snprintf(typeList + offset, sizeof(typeList) - offset, "...");
break;
}
offset += ret;
}
}
logger.safePrintln(typeList);
}
} else {
logger.safePrintln("ERROR: Could not create any raw sockets");
logger.safePrintln("Please check ESP-IDF configuration for raw socket support");
}
logger.safePrintln("Listening...");
}
void loop() {
// Process queued log events from lwIP task
logger.processLogQueue(ip, subnet);
// Update NTP if needed
updateNTPIfNeeded();
delay(1);
}