-
Notifications
You must be signed in to change notification settings - Fork 7
/
mignis.py
executable file
·1589 lines (1394 loc) · 65.9 KB
/
mignis.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
mignis.py is a semantic based tool for firewall configuration.
For usage instructions type:
$ ./mignis.py -h
'''
import argparse
import bisect
import os
import pprint
import re
import sys
import tempfile
import traceback
from collections import Counter, OrderedDict
from ipaddr import AddressValueError, IPv4Address, IPv4Network
from ipaddr_ext import IPv4Range
from itertools import product
class RuleException(Exception):
pass
class Rule:
# Reference to the Mignis object
mignis = None
# Dictionary with rule parameters
params = {}
def __init__(self, mignis, abstract_rule, abstract_rule_collapsed, ruletype, r_from, r_to, protocol, filters, nat):
self.mignis = mignis
if filters is None:
filters = ''
# Sanitize filters
self._check_filters(filters)
# Extract protocol from filters
# filters, protocol = self._extract_protocol(filters)
# Expand r_from, r_to and r_nat to aliases, interfaces, IPs and ports
from_alias, from_intf, from_ip, from_port = self.expand_address(mignis, r_from)
to_alias, to_intf, to_ip, to_port = self.expand_address(mignis, r_to)
nat_alias, nat_intf, nat_ip, nat_port = self.expand_address(mignis, nat) if nat else (None, None, None, None)
self.params = {
# The rule as written in the configuration file (expanded)
'abstract': abstract_rule,
# The rule as written in the configuration file (collapsed, might include lists)
'abstract_collapsed': abstract_rule_collapsed,
# The type of rule, one of: /, //, >, <>, >S, >M, >D
'rtype': ruletype,
# Custom filters for the rule
'filters': filters,
'protocol': protocol,
# From/To addresses
'from_alias': from_alias,
'from_intf': from_intf,
'from_ip': from_ip,
'from_port': from_port,
'to_alias': to_alias,
'to_intf': to_intf,
'to_ip': to_ip,
'to_port': to_port,
# NAT options
'nat_alias': nat_alias,
'nat_intf': nat_intf,
'nat_ip': nat_ip,
'nat_port': nat_port,
}
def __repr__(self):
return pprint.pformat(self.params)
@staticmethod
def ruletype_str(ruletype):
if ruletype == '/':
return 'Drop'
elif ruletype == '//':
return 'Reject'
elif ruletype == '<>':
return 'Forward (bidirectional)'
elif ruletype == '>':
return 'Forward'
elif ruletype == '>D':
return 'Destination Nat'
elif ruletype == '>M':
return 'Masquerade'
elif ruletype == '>S':
return 'Source Nat'
elif ruletype == '{':
return 'Sequence'
else:
raise RuleException('Invalid ruletype.')
def _check_filters(self, filters):
'''Verify that some options are not used inside filters.
At the moment we look for:
--dport, --dports, --destination-port, --destination-ports,
--sport, --sports, --source-port, --source-ports,
-s, --source, -d, --destination,
-p, --protocol,
-j, -C, -S, -F, -L, -Z, -N, -X, -P, -E
'''
check_regexp = ('( |\A)('
'--dport|--dports|--destination-port|--destination-ports|'
'--sport|--sports|--source-port|--source-ports'
')( |\Z)')
invalid_option = re.search(check_regexp, filters)
if invalid_option:
raise RuleException('Invalid filter specified: {0}.\n'
'You have to use the Mignis\'s syntax to specify ports.'
.format(invalid_option.groups()[1]))
check_regexp = ('( |\A)('
#'-s|--source|-d|--destination|'
'-p|--protocol|'
'-j|-C|-S|-F|-L|-Z|-N|-X|-P|-E'
')( |\Z)')
invalid_option = re.search(check_regexp, filters)
if invalid_option:
raise RuleException('Invalid filter specified: {0}.\n'
'You can\'t use this switch as a filter.'
.format(invalid_option.groups()[1]))
# def _extract_protocol(self, filters):
# '''Extract the protocol part from filters, and return the new filters
# string and protocol, if present.
# '''
# proto_regexp = '( |\A)(-p|--protocol) (.*?)( |\Z)'
# protocol = re.search(proto_regexp, filters)
# if protocol:
# filters = re.sub(proto_regexp, ' ', filters)
# protocol = protocol.groups()[2]
# else:
# protocol = None
# return filters, protocol
@staticmethod
def expand_address(mignis, addr):
'''Given an address in the form ([*|interface|ip|subnet], port)
a tuple containing (alias, interface, ip, port) is returned.
Note that ip can be either an IPv4Address, a list of IP addresses
(in the case of an IP range) or an IPv4Network.
'''
ipsub, port = addr
if ipsub == '*':
alias = intf = ip = None
elif ipsub in mignis.intf:
alias = ipsub
intf = mignis.intf[ipsub][0]
# TODO: why only local has a subnet? every intf does have one.
ip = mignis.intf['local'][1] if ipsub == 'local' else None
else:
if '/' in ipsub:
# It's a custom subnet
alias = intf = None
ip = IPv4Network(ipsub, strict=True)
elif '-' in ipsub:
# It's a range of ip addresses
alias = intf = None
# ip = map(IPv4Address, ipsub.split('-'))
ip = IPv4Range(ipsub)
# if len(ip) != 2:
# raise Mignis.intfException(self, 'The range "{0}" is invalid.'.format(ipsub))
else:
ip = IPv4Address(ipsub)
alias = Rule.ip2subnet(mignis, ip)
if alias is None:
raise MignisException(mignis, 'The IP address "{0}" does not belong to any subnet.'.format(ipsub))
intf = mignis.intf[alias][0]
return (alias, intf, ip, port)
@staticmethod
def ip2subnet(mignis, ip):
'''Returns the alias of the subnet the ip is in, or None if not found
'''
# TODO: fix this for 0.0.0.0/0. We are doing a hack here to exclude 0.0.0.0/0 and
# assign it only to an ip we don't know, which should be an external one in that case.
all_addresses = None
for alias in mignis.intf:
subnet = mignis.intf[alias][1]
if subnet == IPv4Network('0.0.0.0/0'):
all_addresses = alias
continue
if subnet and ip in subnet:
return alias
else:
return all_addresses
def _format_intfip(self, srcdst, direction, params, iponly=False, portonly=False):
'''Given 'srcdst' (which specifies if we want a source (s) or destination (d) filter type),
converts the given address (which may be any of: alias, interface, ip, port) to a string ready for filtering in the form
'-[io] intf -[ds] ip --[sd]port port'.
The address is get by using '<direction>_ip', where direction can be any of 'from', 'to' or 'nat'.
If iponly is specified, an IP address is returned instead of an interface.
If portonly is specified, no interface/ip filters are added.
'''
intf_alias = '{0}_alias'.format(direction)
intf = '{0}_intf'.format(direction)
ip = '{0}_ip'.format(direction)
port = '{0}_port'.format(direction)
io = 'i' if srcdst == 's' else 'o'
r = ''
if not portonly:
if params[ip]:
# If there is an IP, we use that instead of the interface as it's more specific
if isinstance(params[ip], IPv4Range):
srcdst_long = 'src' if srcdst == 's' else 'dst'
r = '-m iprange --{0}-range {1}'.format(srcdst_long, params[ip])
else:
r = '-{0} {1}'.format(srcdst, params[ip])
elif iponly:
# We need to return an IP address instead of the interface,
# but since no IP was explicitly specified, we have to return the subnet
if params[intf_alias]:
subnet = self.mignis.intf[params[intf_alias]][1]
r = '-{0} {1}'.format(srcdst, str(subnet))
else:
r = ''
elif params[intf]:
# If there is no IP, we use the interface
r = '-{0} {1}'.format(io, params[intf])
else:
# If there is no IP or interface, we don't add any filter
r = ''
if params[port]:
r += ' --{0}port {1}'.format(srcdst, ':'.join(map(str, params[port])))
return r
def get_iptables_rules(self, rulesdict):
params = self.params.copy()
if self.params['rtype'] == '>':
return self._forward(params)
elif self.params['rtype'] == '<>':
return self._dbl_forward(params)
elif self.params['rtype'] == '/':
return self._forward_deny(params)
elif self.params['rtype'] == '//':
return self._forward_deny(params, reject=True)
elif self.params['rtype'] == '>M':
return self._snat(params, masquerade=True)
elif self.params['rtype'] == '>S':
return self._snat(params)
elif self.params['rtype'] == '>D':
'''We will issue a warning in this situation:
ext > lan
ext > [lan] 10.0.0.1:1234
If a rule is written this way the DNAT will take place anyway and the first rule will be useless.
We won't check filters for this kind of match.
We are going to do the check here because '>D' is translated after '>'.
TODO (the checks below are missing and need to be implemented):
ext > 1.1.1.1
ext > [10.0.0.1] 1.1.1.1
ext [1.1.1.2] > 1.1.1.1
ext > [1.1.1.3] 1.1.1.1
'''
# FIXME: improve nat overlap check!
# for rule in rulesdict['>']:
# if (rule.params['from_intf'] == params['from_intf'] and
# rule.params['to_intf'] == params['nat_intf']):
# self.mignis.warning('Forward and NAT rules collision:\n- {0}\n- {1}\n'
# .format(rule.params['abstract'], params['abstract']))
# TODO: should we check ports? otherwise isn't this warning too broad?
return self._dnat(params)
else:
raise RuleException('Key error: invalid rule type \'{0}\'.'.format(self.params['rtype']))
@staticmethod
def ip_isinside(a, b):
'''Returns True if a is inside b.
a and b can be either None, IPv4Address or IPv4Network.
'''
a_class = type(a)
b_class = type(b)
if b is None:
return True
if a is None:
# b is not None, while a is
return False
if b_class == IPv4Network:
# a can be either an IPv4Network, an IPv4Range or an IPv4Address
if a_class == IPv4Range:
# we have to handle the match manually as ipaddr can't handle this
# todo: we really should just extend the whole _BaseNet class in ipaddr.py
return (int(b.network) <= a._ip_from and
int(b.broadcast) >= a._ip_to)
else:
return a in b
if b_class == IPv4Range:
# a can be either an IPv4Network, an IPv4Range or an IPv4Address
return a in b
elif b_class == IPv4Address and a_class == IPv4Address:
return a == b
# We are here if b_class == IPv4Address and a_class == IPv4Network or IPv4Range
return False
@staticmethod
def port_isinside(a, b):
'''Returns True if the port range a is inside b.
a and b can be either None, or a list of length 2 maximum.
'''
if b is None:
return True
if a is None:
# b is not None, while a is
return False
if len(b) == 1:
# b is a port
if len(a) == 1:
# a is a port
return a[0] == b[0]
else:
# a is a range
return False
else:
# b is a range
if len(a) == 1:
# a is a port
return a[0] >= b[0] and a[0] <= b[1]
else:
# a is a range
return a[0] >= b[0] and a[1] <= b[1]
def overlaps(self, a):
'''Check if rule "a" is already matched by us (rule "b").
At the moment we only match rules which are already matched by wider rules with empty filters.
'''
params_a = a.params
params_b = self.params
# If b has filters, rules don't overlap.
# TODO: this is not so easy, we should improve the matching here
if params_b['filters'] != '':
return False
# If from/to interfaces don't match, rules don't overlap.
if not ((params_b['from_intf'] is None or params_a['from_intf'] == params_b['from_intf']) and
(params_b['to_intf'] is None or params_a['to_intf'] == params_b['to_intf'])):
return False
# Check if from_ip and to_ip of a are subset of, respectively, from_ip and to_ip of b
if not (Rule.ip_isinside(params_a['from_ip'], params_b['from_ip']) and
Rule.ip_isinside(params_a['to_ip'], params_b['to_ip'])):
return False
# Do the same for ports
if not (Rule.port_isinside(params_a['from_port'], params_b['from_port']) and
Rule.port_isinside(params_a['to_port'], params_b['to_port'])):
return False
# Do the same for protocols
protocol_a = params_a['protocol']
protocol_b = params_b['protocol']
if not (protocol_a == protocol_b or protocol_a == 'all' or protocol_b == 'all'):
return False
# This is used to avoid printing a warning when we are doing both SNAT/MASQERADE and DNAT
# TODO: this is probably not the best way to perform this check
if protocol_a == protocol_b and params_a['to_port'] == params_b['to_port'] and \
params_a['from_intf'] == params_b['from_intf'] and \
params_a['from_ip'] == params_b['from_ip'] and \
params_a['to_ip'] == params_b['to_ip'] and \
params_a['to_intf'] == params_b['to_intf'] and \
((params_a['rtype'] in ('>M', '>S') and params_b['rtype'] == '>D') or
(params_b['rtype'] in ('>M', '>S') and params_a['rtype'] == '>D')):
return False
# Check if nat overlaps
# TODO: do this
return True
def involves(self, alias, interface, ip):
'''Given an alias, interface and ip
check if it is involved in the rule.
'''
def check_involves(x):
xintf = x + '_intf'
xip = x + '_ip'
return (
(
interface == self.params[xintf] or
None in [interface, self.params[xintf]]
) and
(Rule.ip_isinside(ip, self.params[xip]) or
Rule.ip_isinside(self.params[xip], ip) or
None in [ip, self.params[xip]]
)
)
# TODO: should "local" be involved by a rule with masquerade?
# we skip masquerade at the moment! we should at least check if the ip
# is one defined in the interfaces (when this will be added to interfaces...)
checks = {
'from': check_involves('from'),
'to': check_involves('to'),
'dnat': self.is_dnat() and check_involves('nat'),
'snat': self.is_snat() and check_involves('nat'),
}
return (any(checks.values()), checks)
def is_drop(self):
return self.params['rtype'] == '/'
def is_reject(self):
return self.params['rtype'] == '//'
def is_forward_dbl(self):
return self.params['rtype'] == '<>'
def is_forward(self):
return self.params['rtype'] == '>'
def is_dnat(self):
return self.params['rtype'] == '>D'
def is_snat(self):
return self.params['rtype'] == '>S'
def is_masquerade(self):
return self.params['rtype'] == '>M'
def is_sequence(self):
return self.params['rtype'] == '{'
def has_nat(self):
return self.is_dnat() or self.is_snat() or self.is_masquerade()
# Rule-translation functions
@staticmethod
def _format_protocol(params):
'''Add the protocol to the rule.
We need to add this before adding the --[ds]port switch as
iptables won't recognize the -p switch if placed after --dport.
'''
# We add the protocol if a port or protocol have been specified.
port = (('to_port' in params and params['to_port']) or
('from_port' in params and params['from_port']) or
('nat_port' in params and params['nat_port']))
protocol = params['protocol'] if 'protocol' in params else None
if port or protocol:
if port and not protocol:
# If a port has been specified without a protocol, add a default 'all' protocol.
protocol = 'all'
return ' -p ' + protocol
return ''
@staticmethod
def format_rule(fmt, params):
if 'abstract' in params:
# Escape the " character
params['rule_escaped'] = params['abstract'].replace('"', '\\"')
fmt += ' -m comment --comment "{rule_escaped}"'
params['proto'] = Rule._format_protocol(params)
rule = re.sub(' +', ' ', fmt.format(**params))
return rule
def _forward(self, params, flip=False):
'''Translation for ">".
If flip is True, the 'to' and 'from' parameters are switched
(this only happens for the non-local case).
'''
rules = []
if params['from_alias'] == 'local' or params['to_alias'] == 'local':
# local case
dir1 = 'from'
dir2 = 'to'
else:
# forward case
dir1 = 'to' if flip else 'from'
dir2 = 'from' if flip else 'to'
if params['from_alias'] == 'local' and params['to_alias'] == 'local':
# OUTPUT and INPUT rule (this is the "local > local" case)
# TODO: we can avoid this and use the same code as 'from_alias', so by exploiting the generic "established,related" rule
# but as we know how to do it without it, maybe it's better? We should think about it.
params['source'] = self._format_intfip('s', dir1, params, portonly=True)
params['destination'] = self._format_intfip('d', dir2, params)
rules.append(self.format_rule('-A OUTPUT {proto} {source} {destination} {filters} -j ACCEPT', params))
params['source'] = self._format_intfip('s', dir2, params)
params['destination'] = self._format_intfip('d', dir1, params, portonly=True)
rules.append(self.format_rule('-A INPUT {proto} {source} {destination} {filters} -j ACCEPT', params))
elif params['from_alias'] == 'local':
# OUTPUT rule
if flip:
params['source'] = self._format_intfip('s', dir2, params)
params['destination'] = self._format_intfip('d', dir1, params, portonly=True)
rules.append(self.format_rule('-A INPUT {proto} {source} {destination} {filters} -j ACCEPT', params))
else:
params['source'] = self._format_intfip('s', dir1, params, portonly=True)
params['destination'] = self._format_intfip('d', dir2, params)
rules.append(self.format_rule('-A OUTPUT {proto} {source} {destination} {filters} -j ACCEPT', params))
elif params['to_alias'] == 'local':
# INPUT rule
if flip:
params['source'] = self._format_intfip('s', dir2, params, portonly=True)
params['destination'] = self._format_intfip('d', dir1, params)
rules.append(self.format_rule('-A OUTPUT {proto} {source} {destination} {filters} -j ACCEPT', params))
else:
params['source'] = self._format_intfip('s', dir1, params)
params['destination'] = self._format_intfip('d', dir2, params, portonly=True)
rules.append(self.format_rule('-A INPUT {proto} {source} {destination} {filters} -j ACCEPT', params))
else:
# FORWARD rule
params['source'] = self._format_intfip('s', dir1, params)
params['destination'] = self._format_intfip('d', dir2, params)
rules.append(self.format_rule('-A FORWARD {proto} {source} {destination} {filters} -j ACCEPT', params))
return rules
def _dbl_forward(self, params):
'''Translation for "<>"
'''
rules = []
rules.extend(self._forward(params))
rules.extend(self._forward(params, flip=True))
return rules
def _forward_deny(self, params, reject=False):
'''Translation for "/" and "//"
'''
rules = []
target = 'REJECT' if reject else 'DROP'
if params['from_alias'] == 'local':
# OUTPUT rule
# this also matches the "local / local" rule
params['source'] = self._format_intfip('s', 'from', params, portonly=True)
params['destination'] = self._format_intfip('d', 'to', params)
chain = 'OUTPUT'
elif params['to_alias'] == 'local':
# INPUT rule
params['source'] = self._format_intfip('s', 'from', params)
params['destination'] = self._format_intfip('d', 'to', params, portonly=True)
chain = 'INPUT'
else:
# FORWARD rule
params['source'] = self._format_intfip('s', 'from', params)
params['destination'] = self._format_intfip('d', 'to', params)
chain = 'FORWARD'
rules.append(
self.format_rule('-A ' + chain + ' {proto} {source} {destination} {filters} -j ' + target, params))
return rules
def _snat(self, params, masquerade=False):
'''Translation for ">" in the case of a SNAT
'''
rules = []
rules.extend(self._forward(params))
if masquerade:
target = 'MASQUERADE'
else:
params['nat'] = str(params['nat_ip'])
if params['nat_port']:
params['nat'] += ':' + '-'.join(map(str, params['nat_port']))
target = 'SNAT --to-source {nat}'
params['source'] = self._format_intfip('s', 'from', params, iponly=True)
params['destination'] = self._format_intfip('d', 'to', params)
rules.append(
self.format_rule('-t nat -A POSTROUTING {proto} {source} {destination} {filters} -j ' + target, params))
return rules
def _dnat(self, params):
'''Translation for ">" in the case of a DNAT
'''
rules = []
if re.search('(^| )-m state ', params['filters']):
self.mignis.warning('Inspectioning the state in DNAT might corrupt the rule.' +
'Use it only if you know what you\'re doing.\n- {0}'.format(params['abstract']))
params['source'] = self._format_intfip('s', 'from', params)
params['destination'] = self._format_intfip('d', 'to', params, iponly=True)
rules.append(self.format_rule(
'-t mangle -A PREROUTING {proto} {source} {destination} {filters} -m state --state NEW -j DROP', params))
# Forward rules without filters
filters = params['filters']
params['filters'] = ''
rules.extend(self._forward(params))
params['filters'] = filters
if params['from_alias'] == 'local':
params['source'] = self._format_intfip('s', 'from', params, portonly=True)
params['chain'] = 'OUTPUT'
else:
params['source'] = self._format_intfip('s', 'from', params)
params['chain'] = 'PREROUTING'
params['destination'] = self._format_intfip('d', 'nat', params, iponly=True)
# TODO: verify that to_ip is not None.
params['nat'] = str(params['to_ip'])
if params['to_port']:
params['nat'] += ':' + '-'.join(map(str, params['to_port']))
rules.append(self.format_rule(
'-t nat -A {chain} {proto} {source} {destination} {filters} -j DNAT --to-destination {nat}', params))
return rules
##
class MignisException(Exception):
def __init__(self, mignis, message):
Exception.__init__(self, message)
# mignis.reset_iptables(False)
class MignisConfigException(Exception):
pass
class Mignis:
old_rules = []
'''
intf contains the alias/interface/subnet mapping for each interface.
An example of how its structure looks like:
{
'lan': ('eth0', IPv4Network('10.0.0.0/24')),
'ext': ('eth1', IPv4Network('0.0.0.0/0'))
}
'''
intf = {}
# Rules to be executed, as strings, in the correct order
iptables_rules = []
def __init__(self, config_file, debug, force, dryrun, write_rules_filename, execute_rules, flush):
self.config_file = config_file
self.debug = debug
self.force = force
self.dryrun = dryrun
self.write_rules_filename = write_rules_filename
self.execute_rules = execute_rules
self.flush = flush
# The config file should not be parsed and only flush rules should be generated
if self.flush:
self.all_rules = self.flush_rules
else:
self.read_config()
def wr(self, s):
'''Print a string to stdout
'''
if self.debug >= 1:
print(s)
def execute(self, cmd):
'''Execute the command s only if we are not in dryrun mode
'''
# TODO: use subprocess.check_call with try/except in place of system
if not self.dryrun:
if self.debug >= 2:
print('COMMAND: ' + cmd)
ret = os.system(cmd)
if ret:
raise MignisException(self, 'Command execution error (code: {0}).'.format(ret))
def test_exec_rules(self):
# Create temp file for writing the rules
temp_fd, temp_file = tempfile.mkstemp(suffix='.ipt', prefix='mignis_')
self.write_rules(None, fd=temp_fd)
# Execute the rules.
# First in dryrun mode, and if no exception is raised they are executed for real.
self.exec_rules(temp_file, force_dryrun=True)
self.exec_rules(temp_file)
# Delete the temp file
os.unlink(temp_file)
def exec_rules(self, temp_file, force_dryrun=False):
options = ' '
if self.dryrun or force_dryrun:
options += '--test '
try:
# Execute the rules
self.execute('iptables-restore' + options + temp_file)
except MignisException as e:
raise MignisException(
self, str(e) + '\nThe temporary file which generated the error is stored in "{0}"'.format(temp_file))
def write_rules(self, filename, fd=None):
if self.dryrun:
return
if fd:
f = os.fdopen(fd, 'w')
else:
if not self.force and os.path.exists(filename):
raise MignisException(self, 'The file already exists, use -f to overwrite.')
f = open(filename, 'w')
if self.flush:
# We just need to write the rules to file
for rule in self.iptables_rules:
f.write(rule.strip() + '\n')
else:
# Split the rules in filter, nat and mangle tables
separators = '[^a-zA-Z0-9\-_]'
rules = self.iptables_rules[:]
tables = {'filter': [], 'nat': [], 'mangle': []}
for table, table_opt in [
('nat', '(?:\A|{0})(-t nat)(?:\Z|{0})'.format(separators)),
('mangle', '(?:\A|{0})(-t mangle)(?:\Z|{0})'.format(separators))]:
for rule in self.iptables_rules:
if re.search(table_opt, rule):
# Extract the rule without "-t nat" or "-t mangle" switches
rules.remove(rule)
rule = re.sub(table_opt, '', rule)
tables[table].append(rule)
tables['filter'] = rules
# Write the rules by table
for table_name, rules in tables.items():
f.write('*' + table_name + '\n')
f.write('\n'.join(rules))
f.write('\nCOMMIT\n')
f.close()
def apply_rules(self):
print('\n[*] Applying rules')
if self.dryrun:
print('\n[*] Rules not applied (dryrun mode)')
else:
if self.write_rules_filename:
self.write_rules(self.write_rules_filename)
print('\n[*] Rules written.')
else:
if self.force:
self.test_exec_rules()
print('\n[*] Rules applied.')
else:
execute = ''
print('')
while execute not in ['y', 'n']:
if sys.version_info > (3,):
execute = input('Apply the rules? [y|n]: ').lower()
else:
execute = raw_input('Apply the rules? [y|n]: ').lower()
if execute == 'y':
self.test_exec_rules()
print('[*] Rules applied.')
else:
print('[!] Rules NOT applied.')
def warning(self, s):
if self.debug > 0:
print("")
print("# WARNING: " + s)
# def reset_iptables(self):
# '''Netfilter reset with default ACCEPT for every chain
# '''
#
# if not self.execute_rules:
# return
#
# print('\n[*] Resetting netfilter')
# if self.dryrun:
# print('Skipped (dryrun mode)')
# return
#
# reset_cmd = '''cat << EOF | iptables-restore
# *filter
# :INPUT ACCEPT
# :FORWARD ACCEPT
# :OUTPUT ACCEPT
# COMMIT
# *nat
# :PREROUTING ACCEPT
# :POSTROUTING ACCEPT
# :OUTPUT ACCEPT
# COMMIT
# *mangle
# :PREROUTING ACCEPT
# :INPUT ACCEPT
# :FORWARD ACCEPT
# :OUTPUT ACCEPT
# :POSTROUTING ACCEPT
# COMMIT
# EOF'''
# x = re.compile("^\s+", re.MULTILINE)
#
# try:
# self.execute(x.sub('', reset_cmd))
# except MignisException as e:
# print('\n[!] ' + str(e))
# sys.exit(-3)
def add_iptables_rule(self, r, params=None):
if params:
r = Rule.format_rule(r, params)
if self.debug >= 1:
print('iptables ' + r)
self.iptables_rules.append(r)
def prune_duplicated_rules(self):
if self.debug >= 1:
pruned = [item for item, count in Counter(self.iptables_rules).items() if count > 1]
if pruned:
num_pruned = len(pruned)
print('\n[+] Removed {:d} duplicated iptables rule{:s}:'.format(
num_pruned, 's' if num_pruned > 1 else ''))
for i, rule in enumerate(pruned):
print('[{:d}] {:s}'.format(i + 1, rule))
self.iptables_rules = list(OrderedDict.fromkeys(self.iptables_rules))
def all_rules(self):
'''Builds all rules
'''
print('\n[*] Building rules')
self.policies()
self.mandatory_rules()
self.ignore_rules()
if self.options['default_rules'] == 'yes':
self.default_rules()
self.firewall_rules()
self.policies_rules()
self.ip_intf_binding_rules()
self.custom_rules()
if self.options['logging'] == 'yes':
self.log_rules()
self.prune_duplicated_rules()
def flush_rules(self):
self.iptables_rules = '''*filter
:INPUT ACCEPT
:FORWARD ACCEPT
:OUTPUT ACCEPT
COMMIT
*nat
:PREROUTING ACCEPT
:POSTROUTING ACCEPT
:OUTPUT ACCEPT
COMMIT
*mangle
:PREROUTING ACCEPT
:INPUT ACCEPT
:FORWARD ACCEPT
:OUTPUT ACCEPT
:POSTROUTING ACCEPT
COMMIT
*raw
:OUTPUT ACCEPT
:PREROUTING ACCEPT
COMMIT'''.split('\n')
def mandatory_rules(self):
'''Rules needed for the model to work.
At this moment we only require an ESTABLISHED,RELATED
rule on every chain in filter.
'''
self.wr('\n# Mandatory rules')
self.add_iptables_rule('-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT')
self.add_iptables_rule('-A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT')
self.add_iptables_rule('-A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT')
def policies(self):
'''Default policies for input/forward/output in filter and prerouting in mangle
'''
self.wr('\n# Default policies')
self.add_iptables_rule('-P INPUT DROP')
self.add_iptables_rule('-P FORWARD DROP')
self.add_iptables_rule('-P OUTPUT DROP')
self.add_iptables_rule('-t mangle -P PREROUTING DROP')
def ignore_rules(self):
'''Ignore rules for each interface, if specified as an option
'''
self.wr('\n# Ignore rules')
for i_alias, (i_intf, i_subnet, i_options) in self.intf.items():
if 'ignore' in i_options:
self.add_iptables_rule('-A INPUT -i {0} -j ACCEPT -m comment --comment "ignore {0}"'.format(i_intf))
self.add_iptables_rule('-A OUTPUT -o {0} -j ACCEPT -m comment --comment "ignore {0}"'.format(i_intf))
self.add_iptables_rule('-A FORWARD -i {0} -j ACCEPT -m comment --comment "ignore {0}"'.format(i_intf))
self.add_iptables_rule('-A FORWARD -o {0} -j ACCEPT -m comment --comment "ignore {0}"'.format(i_intf))
self.add_iptables_rule(
'-t mangle -A PREROUTING -i {0} -j ACCEPT -m comment --comment "ignore {0}"'.format(i_intf))
def default_rules(self):
'''Default rules.
Usually safe, they can be disabled using "default_rules no" in the configuration's options section.
'''
self.wr('\n# Default rules')
# Loopback
self.wr('# - Loopback')
rule = 'loopback'
self.add_iptables_rule('-A INPUT -i lo -j ACCEPT', {'abstract': rule})
# Drop invalid packets
self.wr('# - Invalid packets')
rule = 'drop invalid'
self.add_iptables_rule(
'-t mangle -A PREROUTING -m state --state INVALID,UNTRACKED -j DROP', {'abstract': rule})
# Allow broadcast traffic
self.wr('# - Broadcast traffic')
rule = 'allow broadcast traffic'
self.add_iptables_rule('-A INPUT -d 255.255.255.255 -j ACCEPT', {'abstract': rule})
self.add_iptables_rule('-t mangle -A PREROUTING -d 255.255.255.255 -j ACCEPT', {'abstract': rule})
# Allow multicast traffic
self.wr('# - Multicast traffic')
rule = 'allow multicast traffic'
self.add_iptables_rule('-A INPUT -d 224.0.0.0/4 -j ACCEPT', {'abstract': rule})
self.add_iptables_rule('-t mangle -A PREROUTING -d 224.0.0.0/4 -j ACCEPT', {'abstract': rule})
# We don't allow packets to go out from the same interface they came in
# self.wr('# - Same-interface packets')
# for ipsub in self.intf.keys():
# self.add_iptables_rule('-A FORWARD -i {intf} -o {intf} -j DROP',
# {'intf': self.intf[ipsub][0], 'abstract': 'drop same-interface packets'})
def firewall_rules(self):
'''Execution of the firewall rules defined in section FIREWALL
'''
self.wr('\n\n## Rules')
# Rules optimization
self.fw_rulesdict = self.pre_optimize_rules(self.fw_rulesdict)
# Cycle over the dictionary using a specific order (deny rules are first)
# and add them to iptables
for ruletype in ['/', '//', '<>', '>', '>D', '>M', '>S', '{']:
for rule in self.fw_rulesdict[ruletype]:
# Debugging info
if self.debug >= 2:
print('\n# [D]\n' + str(rule))
if self.debug >= 1:
print('\n# ' + rule.params['abstract'])
# Add the rule to iptables
rules = rule.get_iptables_rules(self.fw_rulesdict)
for r in rules:
self.add_iptables_rule(r)
# Check if rules overlap
for (ruletype_a, rules_a) in self.fw_rulesdict.items():
if ruletype_a == '!':
continue
for rule_a in rules_a:
for (ruletype_b, rules_b) in self.fw_rulesdict.items():
if ruletype_b == '!':
continue
for rule_b in rules_b:
if rule_b is rule_a:
continue
# Check if rule_a and rule_b overlap
if rule_b.overlaps(rule_a):
self.warning("Two overlapping rules have been defined:\n- {0}\n- {1}\n"
.format(rule_a.params['abstract'], rule_b.params['abstract']))
self.wr('\n##\n')
def policies_rules(self):
'''Execution of the policies rules defined in section POLICIES
'''
self.wr('\n## Policies')
# Rules optimization
self.policies_rulesdict = self.pre_optimize_rules(self.policies_rulesdict)
# Cycle over the dictionary and add the rules to iptables
for ruletype in self.policies_rulesdict.keys():
for rule in self.policies_rulesdict[ruletype]:
# Debugging info
if self.debug >= 2:
print('\n# [D]\n' + str(rule))
if self.debug >= 1:
print('\n# ' + rule.params['abstract'])
# Add the rule to iptables
rules = rule.get_iptables_rules(self.policies_rulesdict)
for r in rules:
self.add_iptables_rule(r)
self.wr('\n##\n')
def pre_optimize_rules(self, rules):
'''Do all the requested optimizations over the rules, before they get