-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdhcp-stats.cpp
615 lines (486 loc) · 14.2 KB
/
dhcp-stats.cpp
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
603
604
605
606
607
608
609
610
611
612
613
614
615
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <math.h>
#include <arpa/inet.h>
#include <netinet/if_ether.h>
#include <err.h>
#include <map>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#ifdef __linux__ // for Linux
#include <netinet/ether.h>
#include <time.h>
#include <pcap/pcap.h>
#endif
#ifndef PCAP_ERRBUF_SIZE
#define PCAP_ERRBUF_SIZE (256)
#endif
#define SIZE_ETHERNET (14) // offset of Ethernet header to L3 protocol
#define SIZE_UDP 8 /* length of UDP header */
#define DHCP_OPTIONS_START 240
#define IP_LENGTH 32
#define DHCP_OPTION_TYPE 53
#define DHCP_OPTION_LEASE 51
#define DHCP_OPTION_END 255
// DHCP Messagess
#define DHCP_DECLINE 4
#define DHCP_ACK 5
#define DHCP_NACK 6
#define DHCP_RELEASE 7
#define DHCP_INFO 8
#define STATE_LOAD 0
#define STATE_TYPE 35
#define STATE_LEASE 33
#define OUTPUT_PREFIX_LENGTH 25
#define OUTPUT_MAX_LENGTH 15
#define OUTPUT_ALLOCATED_LENGTH 25
#define OUTPUT_UTILIZATION_LENGTH 15
using namespace std;
namespace std {
template<typename T>
std::string to_string(const T &n) {
std::ostringstream s;
s << n;
return s.str();
}
}
struct dhcpOptions {
int type;
uint32_t lease;
};
struct udphdr {
u_int16_t uh_sport; /* source port */
u_int16_t uh_dport; /* destination port */
u_int16_t uh_ulen; /* udp length */
u_int16_t uh_sum; /* udp checksum */
};
struct device {
string address;
time_t expire;
};
struct network {
string address;
int prefix;
string bits;
std::vector<device> devices;
};
/**
* Analyze packet header and decide what to with DHCP Data
*/
void analyzePacket(const u_char *packet, const ip *my_ip, u_int size_ip);
/**
* Check if device exist in network structure
*/
bool hasDeviceInNetwork(string deviceIp, network & myNetwork, int *index);
/**
*
* Add device to network structure
*/
void addDevice(string deviceIp, dhcpOptions options);
/**
* Remove device from network structure
*/
void removeDevice(const ip *my_ip);
/**
* Check if the device is in network with specific prefix
*/
bool isInNetwork(string device, string network, int prefix);
/**
* Split string by delimiter into vector of strings
*/
vector<string> split(string input,const char* delimiter);
/**
* Check if the given string contains only digits
*/
bool isNumber(const std::string& s);
/**
* Convert integer to string with bit representation
*/
string intToStringBits(int number);
/**
* Convert given ip address to bit representation
*/
string ipToStringBits(string input);
/**
* Handler of pcap library, catch packet
*/
void mypcapHandler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
/**
* Get options from DHCP options data
*/
dhcpOptions getOptions(const u_char *payload, int size_payload);
/**
* Check experiation of leastime for device, and if it expiry then remove device from network structure
*/
void checkExpiration();
/**
* Find index of specific parameter
*/
int findParam(int argc, char * argv[], string find);
/**
* Find value of parameter on given index
*/
string foundValue(int argc, char * argv[], int pos);
/**
* Parse and check all parameters
*/
bool parseParameters(int argc, char *argv[]);
/**
* Print statistics
*/
void printStats();
int n = 0;
std::vector<network> networks;
string interface("");
bool isInNetwork(string device, string network, int prefix)
{
for (int i = 0; i < prefix; i++) {
if (device[i] != network[i]) {
return false;
}
}
return true;
}
vector<string> split(string input,const char* delimiter)
{
char data[input.length() + 1];
memcpy(data, input.c_str(), input.length() + 1);
char* token = strtok(data, delimiter);
vector<string> result;
while(token != NULL)
{
result.push_back(token);
token = strtok(NULL,delimiter);
}
return result;
}
bool isNumber(const std::string& s)
{
std::string::const_iterator i = s.begin();
while (i != s.end() && std::isdigit(*i)) {
i++;
}
return !s.empty() && i == s.end();
}
string intToStringBits(int number)
{
string binary ("");
int mask = 1;
for (int i = 0; i < 8; i++) {
if ((mask & number) >= 1) {
binary = "1" + binary;
} else {
binary = "0" + binary;
}
mask <<= 1;
}
return binary;
}
string ipToStringBits(string input)
{
vector<string> octets = split(input, ".");
string ipBytes ("");
for (auto &i : octets) {
int number = std::stoi(i);
string bits = intToStringBits(number);
ipBytes.append(bits);
}
return ipBytes;
}
void mypcapHandler(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
struct ip *my_ip; // pointer to the beginning of IP header
struct ether_header *eptr; // pointer to the beginning of Ethernet header
const struct tcphdr *my_tcp; // pointer to the beginning of TCP header
u_int size_ip;
n++;
// read the Ethernet header
eptr = (struct ether_header *) packet;
if (ntohs(eptr->ether_type) == ETHERTYPE_IP) { // see /usr/include/net/ethernet.h for types
my_ip = (struct ip *) (packet + SIZE_ETHERNET); // skip Ethernet header
size_ip = my_ip->ip_hl * 4; // length of IP header
if (my_ip->ip_p == 17) {
analyzePacket(packet, my_ip, size_ip);
}
}
}
dhcpOptions getOptions(const u_char *payload, int size_payload) {
int state = STATE_LOAD;
int i = DHCP_OPTIONS_START;
dhcpOptions options;
options.lease = 0;
options.type = 0;
while (i < size_payload) {
u_char actual = payload[i];
switch (state) {
case STATE_LOAD:
if (actual == DHCP_OPTION_TYPE) {
state = STATE_TYPE;
i += 2;
} else if (actual == DHCP_OPTION_LEASE) {
state = STATE_LEASE;
i += 2;
} else if (actual == DHCP_OPTION_END) {
return options;
} else {
i += payload[i + 1] + 2;
}
break;
case STATE_TYPE:
options.type = payload[i];
state = STATE_LOAD;
i++;
break;
case STATE_LEASE:
options.lease = (int) (payload[i] << 24 | payload[i + 1] << 16 | payload[i + 2] << 8 | payload[i + 3]);
state = STATE_LOAD;
i += 5;
break;
}
}
return options;
}
void analyzePacket(const u_char *packet, const ip *my_ip, u_int size_ip) {
const struct udphdr *my_udp;
const u_char *payload;
int size_payload;
my_udp = (struct udphdr *) (packet + SIZE_ETHERNET + size_ip);
payload = (u_char *) (packet + SIZE_ETHERNET + size_ip + SIZE_UDP);
size_payload = ntohs(my_ip->ip_len) - (size_ip + SIZE_UDP);
if (size_payload > ntohs(my_udp->uh_ulen)) {
size_payload = ntohs(my_udp->uh_ulen);
}
if (!size_payload || size_payload < DHCP_OPTIONS_START) {
return;
}
dhcpOptions options = getOptions(payload, size_payload);
switch (options.type) {
case DHCP_ACK:
addDevice(inet_ntoa(my_ip->ip_dst), options);
break;
case DHCP_INFO:
break;
case DHCP_DECLINE:
case DHCP_NACK:
case DHCP_RELEASE:
removeDevice(my_ip);
break;
default:
break;
}
}
void addDevice(string deviceIp, dhcpOptions options) {
network *actual;
string deviceBits = ipToStringBits(deviceIp);
time_t leasTime = time(NULL) + options.lease;
for ( auto &i : networks ) {
if (!isInNetwork(deviceBits, i.bits, i.prefix)) {
continue;
}
int index;
bool found = hasDeviceInNetwork(deviceIp, i, &index);
if (!found) {
device newDevice;
newDevice.address = deviceIp;
newDevice.expire = leasTime;
i.devices.push_back(newDevice);
} else {
i.devices.at(index).expire = leasTime;
}
}
printStats();
}
void removeDevice(const ip *my_ip) {
string deviceIp = inet_ntoa(my_ip->ip_src);
for ( auto &i : networks ) {
int index;
bool found = hasDeviceInNetwork(deviceIp, i, &index);
if (!found) {
continue;
}
i.devices.erase(i.devices.begin() + index);
}
printStats();
}
bool hasDeviceInNetwork(string deviceIp, network & myNetwork, int *index) {
*index = 0;
for (auto &networkDevice : myNetwork.devices) {
if (networkDevice.address == deviceIp) {
return true;
}
(*index)++;
}
return false;
}
void checkExpiration() {
time_t actualTime = time(NULL);
int index;
for (auto &network : networks ) {
index = 0;
for (auto &networkDevice : network.devices) {
if (networkDevice.expire < actualTime) {
network.devices.erase(network.devices.begin() + index);
}
index++;
}
}
}
void printHeader()
{
cout << left << setw(OUTPUT_PREFIX_LENGTH) << setfill(' ') << "IP Prefix";
cout << left << setw(OUTPUT_MAX_LENGTH) << setfill(' ') << "Max hosts";
cout << left << setw(OUTPUT_ALLOCATED_LENGTH) << setfill(' ') << "Allocated addresses";
cout << left << setw(OUTPUT_UTILIZATION_LENGTH) << setfill(' ') << "Utilization";
cout << endl;
}
void printStats() {
checkExpiration();
for ( auto &network : networks ) {
double max = pow(2, IP_LENGTH - network.prefix);
if (network.prefix < 31) {
max -= 2;
}
string networkName("");
networkName.append(network.address);
networkName.append("/");
networkName.append(std::to_string(network.prefix));
string utilization("");
utilization.append(std::to_string(100 * network.devices.size() / max));
utilization.append("%");
cout << left << setw(OUTPUT_PREFIX_LENGTH) << setfill(' ') << networkName;
cout << left << setw(OUTPUT_MAX_LENGTH) << setfill(' ') << max;
cout << left << setw(OUTPUT_ALLOCATED_LENGTH) << setfill(' ') << network.devices.size();
cout << left << setw(OUTPUT_UTILIZATION_LENGTH) << setfill(' ') << utilization;
cout << endl;
}
if (networks.size() > 0) {
cout << endl;
}
}
int findParam(int argc, char * argv[], string find)
{
for (int i = 1; i < argc; i++) {
if (argv[i] == find) {
return i;
}
}
return -1;
}
string foundValue(int argc, char * argv[], int pos)
{
if (pos + 2 > argc) {
return string("");
}
return argv[pos + 1];
}
bool parseParameters(int argc, char *argv[])
{
if (argc < 3) {
return false;
}
int interfacePosition = findParam(argc, argv, "-i");
if (interfacePosition < 0) {
return false;
}
interface = foundValue(argc, argv, interfacePosition);
if (interface.empty()) {
return false;
}
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-i") == 0) {
i++;
continue;
}
vector<string> addressAndPrefix = split(argv[i], "/");
if (addressAndPrefix.size() != 2) {
return false;
}
vector<string> octets = split(addressAndPrefix[0], ".");
if (octets.size() != 4) {
return false;
}
for (auto &octet : octets) {
if (!isNumber(octet)) {
return false;
}
int octetNumber = std::stoi(octet);
if (octetNumber < 0 || octetNumber > 255) {
return false;
}
}
if (!isNumber(addressAndPrefix[1])) {
return false;
}
int prefix = std::stoi(addressAndPrefix[1]);
if (prefix < 0 || prefix > 32) {
return false;
}
network network;
network.prefix = prefix;
network.address = addressAndPrefix[0];
network.bits = ipToStringBits(addressAndPrefix[0]);
networks.push_back(network);
}
return networks.size() != 0;
}
int main (int argc, char * argv[])
{
char errbuf[PCAP_ERRBUF_SIZE]; // constant defined in pcap.h
pcap_t *handle; // packet capture handle
char *dev; // input device
struct in_addr a,b;
bpf_u_int32 netaddr; // network network configured at the input device
bpf_u_int32 mask; // network mask of the input device
struct bpf_program fp; // the compiled filter
if (!parseParameters(argc, argv)) {
cerr << "Bad parameters!" << endl;
return EXIT_FAILURE;
};
dev = (char *)interface.c_str();
// get IP network and mask of the sniffing interface
if (pcap_lookupnet(dev,&netaddr,&mask,errbuf) == -1) {
cerr << "Bad interface" << endl;
return EXIT_FAILURE;
}
a.s_addr=netaddr;
b.s_addr=mask;
// open the interface for live sniffing
if ((handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf)) == NULL) {
cerr << "pcap_open_live() failed" << endl;
return EXIT_FAILURE;
}
// compile the filter
if (pcap_compile(handle, &fp, "port 67 or port 68", 0, netaddr) == -1) {
cerr << "pcap_compile() failed" << endl;
return EXIT_FAILURE;
}
// set the filter to the packet capture handle
if (pcap_setfilter(handle, &fp) == -1) {
cerr << "pcap_setfilter() failed" << endl;
return EXIT_FAILURE;
}
printHeader();
// read packets from the interface in the infinite loop (count == -1)
// incoming packets are processed by function mypcapHandler()
if (pcap_loop(handle, -1, mypcapHandler, NULL) == -1) {
cerr << "pcap_loop() failed" << endl;
return EXIT_FAILURE;
}
// close the capture device and deallocate resources
pcap_close(handle);
return EXIT_SUCCESS;
}