-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathiptstate.cc
2975 lines (2704 loc) · 79.2 KB
/
iptstate.cc
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* vim:textwidth=80:tabstop=2:shiftwidth=2:expandtab:ai
*
* iptstate.cc
* IPTables State
*
* -----------------------------------
*
* Copyright (C) 2002 - present Phil Dibowitz
*
* This software is provided 'as-is', without any express or
* implied warranty. In no event will the authors be held
* liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it
* and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you
* must not claim that you wrote the original software. If you use
* this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and
* must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
* -----------------------------------
*
* The idea of statetop comes from IP Filter by Darren Reed.
*
* This package's main purpose is to provide a state-top type
* interface for IP Tables. I've added in the "single run"
* option since there's no nice way to do that either.
*
* NOTE: If you are planning on packaging and/or submitting my software for/to
* a Linux distribution, I would appreciate a heads up.
*
*/
#include <cerrno>
#include <cmath>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
// There are no C++-ified versions of these.
#include <arpa/inet.h>
#include <getopt.h>
extern "C" {
#include <libnetfilter_conntrack/libnetfilter_conntrack.h>
};
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <locale.h>
#include <netdb.h>
#include <ncurses.h>
#include <unistd.h>
#include <sys/ioctl.h>
using namespace std;
#define VERSION "2.2.7"
/*
* MAXCONS is set to 16k, the default number of states in iptables. Generally
* speaking the ncurses pad is this many lines long, but since ncurses
* uses a short for their dimensions, a pad can never be longer than 32767.
* Thus we define both of these values and NLINES as the lesser of the two.
*/
#define MAXCONS 16384
#define MAXLINES 32767
#if MAXCONS < MAXLINES
#define NLINES MAXCONS
#else
#define NLINES MAXLINES
#endif
#define MAXFIELDS 20
// This is the default format string if we don't dynamically determine it
#define DEFAULT_FORMAT "%-21s %-21s %-7s %-12s %-9s\n"
// The following MUST be the same as the above
#define DEFAULT_SRC 21
#define DEFAULT_DST 21
#define DEFAULT_PROTO 7
#define DEFAULT_STATE 12
#define DEFAULT_TTL 9
// This is the format string for the "totals" line, always.
#define TOTALS_FORMAT \
"Total States: %i -- TCP: %i UDP: %i ICMP: %i Other: %i (Filtered: %i)\n"
// Options for truncating from the front or the back
#define TRUNC_FRONT 0
#define TRUNC_END 1
// maxlength for string we pass to inet_ntop()
#define NAMELEN 100
// Sorting options
#define SORT_SRC 0
#define SORT_SRC_PT 1
#define SORT_DST 2
#define SORT_DST_PT 3
#define SORT_PROTO 4
#define SORT_STATE 5
#define SORT_TTL 6
#define SORT_BYTES 7
#define SORT_PACKETS 8
#define SORT_MAX 8
/*
* GLOBAL CONSTANTS
*/
/*
* GLOBAL VARS
*/
int sort_factor = 1;
bool need_resize = false;
/* shameless stolen from libnetfilter_conntrack_tcp.c */
static const char *states[] = {
"NONE",
"SYN_SENT",
"SYN_RECV",
"ESTABLISHED",
"FIN_WAIT",
"CLOSE_WAIT",
"LAST_ACK",
"TIME_WAIT",
"CLOSE",
"LISTEN"
};
/*
* STRUCTS
*/
// One state-table entry
struct tentry_t {
string proto, state, ttl, sname, dname, spname, dpname;
in6_addr src, dst;
uint8_t family;
unsigned long srcpt, dstpt, bytes, packets, s;
};
// x/y of the terminal window
struct screensize_t {
unsigned int x, y;
};
// Struct 'o flags
struct flags_t {
bool single, totals, lookup, skiplb, staticsize, skipdns, tag_truncate,
filter_src, filter_dst, filter_srcpt, filter_dstpt, filter_inv, noscroll, nocolor,
counters;
};
// Struct 'o counters
struct counters_t {
unsigned int total, tcp, udp, icmp, other, skipped;
};
// Various filters to be applied pending the right flags in flags_t
struct filters_t {
in6_addr src, dst;
bool has_srcnet, has_dstnet;
uint8_t srcnet, dstnet;
uint8_t srcfam, dstfam;
unsigned long srcpt, dstpt;
};
// The max-length of fields in the stable table
struct max_t {
unsigned int src, dst, proto, state, ttl;
unsigned long bytes, packets;
};
struct hook_data {
vector<tentry_t*> *stable;
flags_t *flags;
max_t *max;
counters_t *counts;
const filters_t *filters;
};
/*
* GENERAL HELPER FUNCTIONS
*/
/*
* split a string into two strings based on the first occurance
* of any character
*/
void split(char s, string line, string &p1, string &p2)
{
int pos = line.find(s);
p1 = line.substr(0, pos);
p2 = line.substr(pos+1, line.size()-pos);
}
/*
* split a string into an array of strings based on
* any character
*/
void splita(char s, string line, vector<string> &result)
{
int pos, size;
int i=0;
string temp, temp1;
temp = line;
while ((temp.find(s) != string::npos) && (i < MAXFIELDS-1)) {
pos = temp.find(s);
result[i] = temp.substr(0, pos);
size = temp.size();
temp = temp.substr(pos+1, size-pos-1);
if (result[i] != "") {
i++;
}
}
result[i] = temp;
}
/*
* This determines the length of an integer (i.e. number of digits)
*/
unsigned int digits(unsigned long x)
{
return (unsigned int) floor(log10((double)x))+1;
}
/*
* Check to ensure an IP & netmask are valid
*/
bool check_ip(const char *arg, in6_addr *addr, uint8_t *family, uint8_t *netmask, bool *has_netmask)
{
const char *p_arg;
char ip[NAMELEN];
// Check for netmask prefix
p_arg = strrchr(arg, '/');
if (p_arg == NULL) {
memcpy(ip, arg, (strlen(arg) + 1));
*has_netmask = false;
} else {
size_t ip_len = strlen(arg) - strlen(p_arg);
memcpy(ip, arg, ip_len);
ip[ip_len] = '\0';
const char *net_arg = arg + ip_len + 1;
if (net_arg[0] == '\0')
return false;
int net_int = atoi(net_arg);
if (net_int < 0 || net_int > 128)
return false; // Max IPv6 prefix length
*has_netmask = true;
*netmask = (uint8_t) net_int;
}
// Get IP
int ret;
ret = inet_pton(AF_INET6, ip, addr);
if (ret) {
*family = AF_INET6;
return true;
}
ret = inet_pton(AF_INET, ip, addr);
if (ret) {
if (*has_netmask && *netmask > 32)
return false; // Max IPv4 prefix length
*family = AF_INET;
return true;
}
return false;
}
/*
* Compare IPv4/6 addresses with a netmask
* https://gist.github.com/duedal/b83303b4988a4afb2a75
*/
bool match_netmask(uint8_t family, const in6_addr &address, const in6_addr &network, uint8_t bits) {
if (family == AF_INET) {
if (bits == 0) {
// C99 6.5.7 (3): u32 << 32 is undefined behaviour
return true;
}
struct in_addr addr4, net4;
memcpy(&addr4, &address, sizeof(in_addr));
memcpy(&net4, &network, sizeof(in_addr));
return !((addr4.s_addr ^ net4.s_addr) & htonl(0xFFFFFFFFu << (32 - bits)));
} else {
const uint32_t *a = address.s6_addr32;
const uint32_t *n = network.s6_addr32;
int bits_whole, bits_incomplete;
bits_whole = bits >> 5; // number of whole u32
bits_incomplete = bits & 0x1F; // number of bits in incomplete u32
if (bits_whole) {
if (memcmp(a, n, bits_whole << 2)) {
return false;
}
}
if (bits_incomplete) {
uint32_t mask = htonl((0xFFFFFFFFu) << (32 - bits_incomplete));
if ((a[bits_whole] ^ n[bits_whole]) & mask) {
return false;
}
}
return true;
}
return false;
}
/*
* The help
*/
void version()
{
cout << "IPTables State Top Version " << VERSION << endl << endl;
}
void help()
{
cout << "IPTables State Top Version " << VERSION << endl;
cout << "Usage: iptstate [<options>]\n\n";
cout << " -c, --no-color\n";
cout << "\tToggle color-code by protocol\n\n";
cout << " -C, --counters\n";
cout << "\tToggle display of bytes/packets counters\n\n";
cout << " -d, --dst-filter <IP>[/<NETMASK>]\n";
cout << "\tOnly show states with a destination of <IP> and optional <NETMASK>\n";
cout << "\tNote: Hostname matching is not yet supported.\n\n";
cout << " -D --dstpt-filter <port>\n";
cout << "\tOnly show states with a destination port of <port>\n\n";
cout << " -h, --help\n";
cout << "\tThis help message\n\n";
cout << " -i, --invert-filters\n";
cout << "\tInvert filters to display non-matching results\n\n";
cout << " -l, --lookup\n";
cout << "\tShow hostnames instead of IP addresses. Enabling this will also"
<< " enable\n\t-L to prevent an ever-growing number of DNS requests.\n\n";
cout << " -m, --mark-truncated\n";
cout << "\tMark truncated hostnames with a '+'\n\n";
cout << " -o, --no-dynamic\n";
cout << "\tToggle dynamic formatting\n\n";
cout << " -L, --no-dns\n";
cout << "\tSkip outgoing DNS lookup states\n\n";
cout << " -f, --no-loopback\n";
cout << "\tFilter states on loopback\n\n";
cout << " -p, --no-scroll\n";
cout << "\tNo scrolling (don't use a \"pad\")\n\n";
cout << " -r, --reverse\n";
cout << "\tReverse sort order\n\n";
cout << " -R, --rate <seconds>\n";
cout << "\tRefresh rate, followed by rate in seconds\n";
cout << "\tNote: For statetop, not applicable for -s\n\n";
cout << " -1, --single\n";
cout << "\tSingle run (no curses)\n\n";
cout << " -b, --sort <column>\n";
cout << "\tThis determines what column to sort by. Options:\n";
cout << "\t d: Destination IP (or Name)\n";
cout << "\t p: Protocol\n";
cout << "\t s: State\n";
cout << "\t t: TTL\n";
cout << "\t b: Bytes\n";
cout << "\t P: Packets\n";
cout << "\tTo sort by Source IP (or Name), don't use -b.\n";
cout << "\tNote that bytes/packets are only available when"
<< " supported in the kernel,\n";
cout << "\tand enabled with -C\n\n";
cout << " -s, --src-filter <IP>[/<NETMASK>]\n";
cout << "\tOnly show states with a source of <IP> and optional <NETMASK>\n";
cout << "\tNote: Hostname matching is not yet supported.\n\n";
cout << " -S, --srcpt-filter <port>\n";
cout << "\tOnly show states with a source port of <port>\n\n";
cout << " -t, --totals\n";
cout << "\tToggle display of totals\n\n";
cout << "See man iptstate(8) or the interactive help for more"
<< " information.\n";
exit(0);
}
/*
* Resolve hostnames
*/
void resolve_host(const uint8_t &family, const in6_addr &ip, string &name)
{
struct hostent *hostinfo = NULL;
if ((hostinfo = gethostbyaddr((char *)&ip, sizeof(ip), family)) != NULL) {
name = hostinfo->h_name;
} else {
char str[NAMELEN];
name = inet_ntop(family, (void *)&ip, str, NAMELEN-1) ;
}
}
void resolve_port(const unsigned int &port, string &name, const string &proto)
{
struct servent *portinfo = NULL;
if ((portinfo = getservbyport(htons(port), proto.c_str())) != NULL) {
name = portinfo->s_name;
} else {
ostringstream buf;
buf.str("");
buf << port;
name = buf.str();
}
}
/*
* If lookup mode is on, we lookup the names and put them in the structure.
*
* If lookup mode is not on, we generate strings of the addresses and put
* those in the structure.
*
* Finally, we update the max_t structure.
*
* NOTE: We stringify addresses largely because in the IPv6 case we need
* to treat them like truncate-able strings.
*/
void stringify_entry(tentry_t *entry, max_t &max, const flags_t &flags)
{
unsigned int size = 0;
ostringstream buffer;
char tmp[NAMELEN];
bool have_port = entry->proto == "tcp" || entry->proto == "udp";
if (!have_port) {
entry->spname = entry->dpname = "";
}
if (flags.lookup) {
resolve_host(entry->family, entry->src, entry->sname);
resolve_host(entry->family, entry->dst, entry->dname);
if (have_port) {
resolve_port(entry->srcpt, entry->spname, entry->proto);
resolve_port(entry->dstpt, entry->dpname, entry->proto);
}
} else {
buffer << inet_ntop(entry->family, (void*)&(entry->src), tmp, NAMELEN-1);
entry->sname = buffer.str();
buffer.str("");
buffer << inet_ntop(entry->family, (void*)&(entry->dst), tmp, NAMELEN-1);
entry->dname = buffer.str();
buffer.str("");
if (have_port) {
buffer << entry->srcpt;
entry->spname = buffer.str();
buffer.str("");
buffer << entry->dstpt;
entry->dpname = buffer.str();
buffer.str("");
}
}
size = entry->sname.size() + entry->spname.size() + 1;
if (size > max.src)
max.src = size;
size = entry->dname.size() + entry->dpname.size() + 1;
if (size > max.dst)
max.dst = size;
}
/*
* SORT FUNCTIONS
*/
bool src_sort(tentry_t *one, tentry_t *two)
{
/*
* memcmp() will properly sort v4 or v6 addresses, but not cross-family
* (presumably because of garbage in the top 96 bytes when you store
* a v4 address in a in6_addr), so we sort by family and then memcmp()
* within the same family.
*/
if (one->family == two->family) {
return memcmp(one->src.s6_addr, two->src.s6_addr, 16) * sort_factor < 0;
} else if (one->family == AF_INET) {
return sort_factor > 0;
} else {
return sort_factor < 0;
}
}
bool srcname_sort(tentry_t *one, tentry_t *two)
{
return one->sname.compare(two->sname) * sort_factor < 0;
}
bool dst_sort(tentry_t *one, tentry_t *two)
{
// See src_sort() for details
if (one->family == two->family) {
return memcmp(one->dst.s6_addr, two->dst.s6_addr, 16) * sort_factor < 0;
} else if (one->family == AF_INET) {
return sort_factor > 0;
} else {
return sort_factor < 0;
}
}
bool dstname_sort(tentry_t *one, tentry_t *two)
{
return one->dname.compare(two->dname) * sort_factor < 0;
}
/*
* int comparison that takes care of sort_factor
* used for ports, bytes, etc...
*/
bool cmpint(int one, int two)
{
return (sort_factor > 0) ? one < two : one > two;
}
bool srcpt_sort(tentry_t *one, tentry_t *two)
{
return cmpint(one->srcpt, two->srcpt);
}
bool dstpt_sort(tentry_t *one, tentry_t *two)
{
return cmpint(one->dstpt, two->dstpt);
}
bool proto_sort(tentry_t *one, tentry_t *two)
{
return one->proto.compare(two->proto) * sort_factor < 0;
}
bool state_sort(tentry_t *one, tentry_t *two)
{
return one->state.compare(two->state) * sort_factor < 0;
}
bool ttl_sort(tentry_t *one, tentry_t *two)
{
return one->ttl.compare(two->ttl) * sort_factor < 0;
}
bool bytes_sort(tentry_t *one, tentry_t *two)
{
return cmpint(one->bytes, two->bytes);
}
bool packets_sort(tentry_t *one, tentry_t *two)
{
return cmpint(one->packets, two->packets);
}
/*
* CURSES HELPER FUNCTIONS
*/
/*
* Finish-up for curses environment
*/
void end_curses()
{
curs_set(1);
nocbreak();
endwin();
cout << endl;
}
/*
* SIGWINCH signal handler.
*/
void winch_handler(int sig)
{
sigset_t mask_set;
sigset_t old_set;
// Reset signal handler
signal(28, winch_handler);
// ignore this signal for a bit
sigfillset(&mask_set);
sigprocmask(SIG_SETMASK, &mask_set, &old_set);
need_resize = true;
}
/*
* SIGKILL signal handler
*/
void kill_handler(int sig)
{
end_curses();
printf("Caught signal %d, cleaning up.\n", sig);
exit(0);
}
/*
* Start-up for curses environment
*
* NOTE: That by default we create a pad. A pad is a special type of window that
* can be bigger than the screen. See the comments in interactive_help()
* below for how to use it and how it works.
*
* However, pad's lack the double-buffering and other features of standard
* ncurses windows and thus can appear slower. Thus we allow the user to
* downgrade to standard windows if they choose. See the comments
* switch_scroll() for more details.
*
*/
static WINDOW* start_curses(flags_t &flags)
{
int y, x;
initscr();
cbreak();
noecho();
halfdelay(1);
/*
* If we're starting curses, we care about SIGWNCH, SIGINT, and SIGTERM
* so this seems like as good a place as any to setup our signal
* handler.
*/
// Resize
signal(28, winch_handler);
// Shutdown
signal(2, kill_handler);
signal(15, kill_handler);
if (has_colors()) {
start_color();
// for tcp
init_pair(1, COLOR_GREEN, COLOR_BLACK);
// for udp
init_pair(2, COLOR_YELLOW, COLOR_BLACK);
// for icmp
init_pair(3, COLOR_RED, COLOR_BLACK);
// for prompts
init_pair(4, COLOR_BLACK, COLOR_RED);
// for the currently selected row
init_pair(5, COLOR_BLACK, COLOR_GREEN);
init_pair(6, COLOR_BLACK, COLOR_YELLOW);
init_pair(7, COLOR_BLACK, COLOR_RED);
} else {
flags.nocolor = true;
}
if (!flags.noscroll) {
getmaxyx(stdscr, y, x);
return newpad(NLINES, x);
}
return stdscr;
}
/*
* Figure out the best way to get the screensize_t, and then do it
*/
screensize_t get_size(const bool &single)
{
int maxx = 0, maxy = 0;
if (!single) {
getmaxyx(stdscr, maxy, maxx);
} else {
// https://stackoverflow.com/questions/1022957/
struct winsize w;
ioctl(0, TIOCGWINSZ, &w);
maxx = w.ws_col;
if (getenv("COLS"))
maxx = atoi(getenv("COLS"));
}
screensize_t a;
a.x = maxx;
a.y = maxy;
return a;
}
/*
* Error function for screen being too small.
*/
void term_too_small()
{
end_curses();
cout << "I'm sorry, your terminal must be atleast 72 columns"
<< "wide to run iptstate\n";
exit(3);
}
/*
* This is one of those "well, I should impliment it to be complete, but
* I doubt it'll get used very often features." It was a nice-thing-to-do
* to impliment the ability for iptstate to use stdscr instead of a pad
* as this provides the doulbe-buffering and other features that pads
* do not. This is probably useful to a small subset of users. It's pretty
* unlikely people will want to interactively want to change this during
* runtime, but since I implimented noscroll, it's only proper to impliment
* interactive toggling.
*
* TECH NOTE:
* This is just a note for myself so I remember why this is the way it is.
*
* The syntax WINDOW *&mainwin is right, thought it's doing what you'd
* expect WINDOW &*mainwin to do... except that's invalid. So it's just a
* &foo pass on a WINDOW*.
*/
void switch_scroll(flags_t &flags, WINDOW *&mainwin)
{
int x, y;
if (flags.noscroll) {
getmaxyx(stdscr, y, x);
// remove stuff from the bottom window
erase();
// build pad
wmove(mainwin, 0, 0);
mainwin = newpad(NLINES, x);
wmove(mainwin, 0, 0);
keypad(mainwin,1);
halfdelay(1);
} else {
// delete pad
delwin(mainwin);
mainwin = stdscr;
keypad(mainwin,1);
halfdelay(1);
}
flags.noscroll = !flags.noscroll;
}
/*
* Prompt the user for something, and get an answer.
*/
void get_input(WINDOW *win, string &input, const string &prompt,
const flags_t &flags)
{
/*
* This function is here so that we can prompt and get an answer
* and the user can get an echo of what they're inputting. This is
* already a non-straight-forward thing to do in cbreak() mode, but
* it turns out that using pads makes it even more difficult.
*
* It's worth noting that I tried doin a simple waddch() and then
* prefresh as one would expect, but it didn't echo the chars.
* Because we're using pads I have to do a waddchar() and then
* a prefresh().
*
* Note, that the documentation says that if we're using waddchar()
* we shouldn't need any refresh, but it doesn't echo without it.
* This is probably because waddch() calls wrefresh() instead of
* prefresh().
*/
input = "";
int x, y;
getmaxyx(stdscr, y, x);
WINDOW *cmd = subpad(win, 1, x, 0, 0);
if (!flags.nocolor)
wattron(cmd, COLOR_PAIR(4));
keypad(cmd, true);
wprintw(cmd, "%s", prompt.c_str());
wclrtoeol(cmd);
prefresh(cmd, 0, 0, 0, 0, 0, x);
int ch;
int charcount = 0;
echo();
nodelay(cmd,0);
while (1) {
ch = wgetch(cmd);
switch (ch) {
case '\n':
// 7 is ^G
case 7:
if (ch == 7)
input = "";
if (!flags.nocolor)
wattroff(cmd, COLOR_PAIR(4));
delwin(cmd);
noecho();
wmove(win, 0, 0);
return;
break;
// on most platforms KEY_BACKSPACE will catch
// all backspaces...
case KEY_BACKSPACE:
// but on some platforms ncurses fails, so ensure we catch both 8 (0x8) and 127 (0x7e)
// which are the two valid backspace keycodes
case 8:
case 127:
if (charcount > 0) {
input = input.substr(0, input.size()-1);
wechochar(cmd, '\b');
wechochar(cmd, ' ');
wechochar(cmd, '\b');
charcount--;
}
break;
case ERR:
continue;
break;
default:
input += ch;
charcount++;
wechochar(cmd, ch);
}
prefresh(cmd, 0, 0, 0, 0, 0, x);
}
}
/*
* Create a window with noticable colors (if colors are enabled)
* and print a warning. Means curses_warning.
*/
void c_warn(WINDOW *win, const string &warning, const flags_t &flags)
{
/*
* This function is here so that we can warn a user in curses,
* usually about bad input.
*/
int x, y;
getmaxyx(stdscr, y, x);
WINDOW *warn = subpad(win, 1, x, 0, 0);
if (!flags.nocolor)
wattron(warn, COLOR_PAIR(4));
wprintw(warn, "%s", warning.c_str());
wprintw(warn, " Press any key to continue...");
wclrtoeol(warn);
prefresh(warn, 0, 0, 0, 0, 0, x);
while ((y = getch())) {
if (y != ERR) {
break;
}
prefresh(warn, 0, 0, 0, 0, 0, x);
}
if (!flags.nocolor)
wattroff(warn, COLOR_PAIR(4));
delwin(warn);
noecho();
wmove(win, 0, 0);
return;
}
/*
* Initialize the max_t structure with some sane defaults. We'll grow
* them later as needed.
*/
void initialize_maxes(max_t &max, flags_t &flags)
{
/*
* For NO lookup:
* src/dst IP can be no bigger than 21 chars:
* IP (max of 15) + colon (1) + port (max of 5) = 21
*
* For lookup:
* if it's a name, we start with the width of the header, and we can
* grow from there as needed.
*/
if (flags.lookup) {
max.src = 6;
max.dst = 11;
} else {
max.src = max.dst = 21;
}
/*
* The proto starts at 3, since tcp/udp are the most common, but will
* grow if we see bigger proto strings such as "ICMP".
*/
max.proto = 3;
/*
* "ESTABLISHED" is generally the longest state, we almost always have
* several, so we'll start with this. It also looks really bad if state
* is changing size a lot, so we start with a common minumum.
*/
max.state = 11;
// TTL we statically make 7: xxx:xx:xx
max.ttl = 9;
// Start with something sane
max.bytes = 2;
max.packets = 2;
}
/*
* The actual work of handling a resize.
*/
void handle_resize(WINDOW *&win, const flags_t &flags, screensize_t &ssize)
{
if (flags.noscroll) {
endwin();
refresh();
return;
}
/*
* OK, the above case without pads is easy. But pads is tricker.
* In order to properly handle SIGWINCH we need to:
*
* - Tear down the pad (delwin)
* - Reset the terminal settings to non-visual mode (endwin)
* - Return to visual mode (refresh)
* - Get the new size (getmaxyx)
* - Rebuild the pad
*
* Note that we don't get the new size without the endwin/refresh
* and thus the new pad doesn't get built right, and everything wraps.
*
* This order must be preserved.
*/
/*
* Tear down...
*/
delwin(win);
endwin();
/*
* Start up...
*/
refresh();
getmaxyx(stdscr, ssize.y, ssize.x);
win = newpad(NLINES, ssize.x);
keypad(win, true);
wmove(win, 0, 0);
return;
}
/*
* Take in a 'curr' value, and delete a given conntrack
*/
void delete_state(WINDOW *&win, const tentry_t *entry, const flags_t &flags)
{
struct nfct_handle *cth;
struct nf_conntrack *ct;
cth = nfct_open(CONNTRACK, 0);
ct = nfct_new();
int ret;
string response;
char str[NAMELEN];
string src, dst;
src = inet_ntop(entry->family, (void *)&(entry->src), str, NAMELEN-1);
dst = inet_ntop(entry->family, (void *)&(entry->dst), str, NAMELEN-1);
ostringstream msg;
msg.str("");
msg << "Deleting state: ";
if (entry->proto == "tcp" || entry->proto == "udp") {
msg << src << ":" << entry->srcpt << " -> " << dst << ":" << entry->dstpt;
} else {
msg << src << " -> " << dst;
}
msg << " -- Are you sure? (y/n)";
get_input(win, response, msg.str(), flags);
if (response != "y" && response != "Y" && response != "yes" &&
response != "YES" && response != "Yes") {
c_warn(win, "NOT deleting state.", flags);
return;
}
nfct_set_attr_u8(ct, ATTR_ORIG_L3PROTO, entry->family);
if (entry->family == AF_INET) {
nfct_set_attr(ct, ATTR_ORIG_IPV4_SRC, (void *)&(entry->src.s6_addr));
nfct_set_attr(ct, ATTR_ORIG_IPV4_DST, (void *)&(entry->dst.s6_addr));
} else if (entry->family == AF_INET6) {
nfct_set_attr(ct, ATTR_ORIG_IPV6_SRC, (void *)&(entry->src.s6_addr));
nfct_set_attr(ct, ATTR_ORIG_IPV6_DST, (void *)&(entry->dst.s6_addr));
}
// undo our space optimization so the kernel can find the state.
protoent *pn;
if (entry->proto == "icmp6")
pn = getprotobyname("ipv6-icmp");
else
pn = getprotobyname(entry->proto.c_str());
nfct_set_attr_u8(ct, ATTR_ORIG_L4PROTO, pn->p_proto);
if (entry->proto == "tcp" || entry->proto == "udp") {
nfct_set_attr_u16(ct, ATTR_ORIG_PORT_SRC, htons(entry->srcpt));
nfct_set_attr_u16(ct, ATTR_ORIG_PORT_DST, htons(entry->dstpt));
} else if (entry->proto == "icmp" || entry->proto == "icmp6") {
string type, code, id, tmp;
split('/', entry->state, type, tmp);
split(' ', tmp, code, tmp);
split('(', tmp, tmp, id);
split(')', id, id, tmp);
nfct_set_attr_u8(ct, ATTR_ICMP_TYPE, atoi(type.c_str()));
nfct_set_attr_u8(ct, ATTR_ICMP_CODE, atoi(code.c_str()));
nfct_set_attr_u16(ct, ATTR_ICMP_ID, atoi(id.c_str()));
}
ret = nfct_query(cth, NFCT_Q_DESTROY, ct);
if (ret < 0) {
string msg = "Failed to delete state: ";
msg += strerror(errno);