-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathip4tc.py
More file actions
1847 lines (1552 loc) · 65.2 KB
/
ip4tc.py
File metadata and controls
1847 lines (1552 loc) · 65.2 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
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
# -*- coding: utf-8 -*-
import os
import re
import shlex
import sys
import ctypes as ct
import socket
import struct
import weakref
from .util import find_library, load_kernel, find_libc
from .xtables import (XT_INV_PROTO, NFPROTO_IPV4, XTablesError, xtables,
xt_align, xt_counters, xt_entry_target, xt_entry_match)
__all__ = ["Table", "Chain", "Rule", "Match", "Target", "Policy", "IPTCError"]
try:
load_kernel("ip_tables")
except:
pass
# Add IPPROTO_SCTP to socket module if not available
if not hasattr(socket, 'IPPROTO_SCTP'):
setattr(socket, 'IPPROTO_SCTP', 132)
_IFNAMSIZ = 16
_libc = find_libc()
_get_errno_loc = _libc.__errno_location
_get_errno_loc.restype = ct.POINTER(ct.c_int)
_malloc = _libc.malloc
_malloc.restype = ct.POINTER(ct.c_ubyte)
_malloc.argtypes = [ct.c_size_t]
_free = _libc.free
_free.restype = None
_free.argtypes = [ct.POINTER(ct.c_ubyte)]
# Make sure xt_params is set up.
xtables(NFPROTO_IPV4)
def is_table_available(name):
try:
if name in Table.existing_table_names:
return Table.existing_table_names[name]
Table(name)
Table.existing_table_names[name] = True
return True
except IPTCError:
pass
Table.existing_table_names[name] = False
return False
class in_addr(ct.Structure):
"""This class is a representation of the C struct in_addr."""
_fields_ = [("s_addr", ct.c_uint32)]
class ipt_ip(ct.Structure):
"""This class is a representation of the C struct ipt_ip."""
_fields_ = [("src", in_addr),
("dst", in_addr),
("smsk", in_addr),
("dmsk", in_addr),
("iniface", ct.c_char * _IFNAMSIZ),
("outiface", ct.c_char * _IFNAMSIZ),
("iniface_mask", ct.c_char * _IFNAMSIZ),
("outiface_mask", ct.c_char * _IFNAMSIZ),
("proto", ct.c_uint16),
("flags", ct.c_uint8),
("invflags", ct.c_uint8)]
# flags
IPT_F_FRAG = 0x01 # set if rule is a fragment rule
IPT_F_GOTO = 0x02 # set if jump is a goto
IPT_F_MASK = 0x03 # all possible flag bits mask
# invflags
IPT_INV_VIA_IN = 0x01 # invert the sense of IN IFACE
IPT_INV_VIA_OUT = 0x02 # invert the sense of OUT IFACE
IPT_INV_TOS = 0x04 # invert the sense of TOS
IPT_INV_SRCIP = 0x08 # invert the sense of SRC IP
IPT_INV_DSTIP = 0x10 # invert the sense of DST OP
IPT_INV_FRAG = 0x20 # invert the sense of FRAG
IPT_INV_PROTO = XT_INV_PROTO # invert the sense of PROTO (XT_INV_PROTO)
IPT_INV_MASK = 0x7F # all possible flag bits mask
def __init__(self):
# default: full netmask
self.smsk.s_addr = self.dmsk.s_addr = 0xffffffff
class ipt_entry(ct.Structure):
"""This class is a representation of the C struct ipt_entry."""
_fields_ = [("ip", ipt_ip),
("nfcache", ct.c_uint), # mark with fields that we care about
("target_offset", ct.c_uint16), # size of ipt_entry + matches
("next_offset", ct.c_uint16), # size of e + matches + target
("comefrom", ct.c_uint), # back pointer
("counters", xt_counters), # packet and byte counters
("elems", ct.c_ubyte * 0)] # any matches then the target
class IPTCError(Exception):
"""This exception is raised when a low-level libiptc error occurs.
It contains a short description about the error that occurred while
executing an iptables operation.
"""
_libiptc, _ = find_library("ip4tc", "iptc") # old iptables versions use iptc
class iptc(object):
"""This class contains all libiptc API calls."""
iptc_init = _libiptc.iptc_init
iptc_init.restype = ct.POINTER(ct.c_int)
iptc_init.argstype = [ct.c_char_p]
iptc_free = _libiptc.iptc_free
iptc_free.restype = None
iptc_free.argstype = [ct.c_void_p]
iptc_commit = _libiptc.iptc_commit
iptc_commit.restype = ct.c_int
iptc_commit.argstype = [ct.c_void_p]
iptc_builtin = _libiptc.iptc_builtin
iptc_builtin.restype = ct.c_int
iptc_builtin.argstype = [ct.c_char_p, ct.c_void_p]
iptc_first_chain = _libiptc.iptc_first_chain
iptc_first_chain.restype = ct.c_char_p
iptc_first_chain.argstype = [ct.c_void_p]
iptc_next_chain = _libiptc.iptc_next_chain
iptc_next_chain.restype = ct.c_char_p
iptc_next_chain.argstype = [ct.c_void_p]
iptc_is_chain = _libiptc.iptc_is_chain
iptc_is_chain.restype = ct.c_int
iptc_is_chain.argstype = [ct.c_char_p, ct.c_void_p]
iptc_create_chain = _libiptc.iptc_create_chain
iptc_create_chain.restype = ct.c_int
iptc_create_chain.argstype = [ct.c_char_p, ct.c_void_p]
iptc_delete_chain = _libiptc.iptc_delete_chain
iptc_delete_chain.restype = ct.c_int
iptc_delete_chain.argstype = [ct.c_char_p, ct.c_void_p]
iptc_rename_chain = _libiptc.iptc_rename_chain
iptc_rename_chain.restype = ct.c_int
iptc_rename_chain.argstype = [ct.c_char_p, ct.c_char_p, ct.c_void_p]
iptc_flush_entries = _libiptc.iptc_flush_entries
iptc_flush_entries.restype = ct.c_int
iptc_flush_entries.argstype = [ct.c_char_p, ct.c_void_p]
iptc_zero_entries = _libiptc.iptc_zero_entries
iptc_zero_entries.restype = ct.c_int
iptc_zero_entries.argstype = [ct.c_char_p, ct.c_void_p]
# get the policy of a given built-in chain
iptc_get_policy = _libiptc.iptc_get_policy
iptc_get_policy.restype = ct.c_char_p
iptc_get_policy.argstype = [ct.c_char_p, ct.POINTER(xt_counters),
ct.c_void_p]
# Set the policy of a chain
iptc_set_policy = _libiptc.iptc_set_policy
iptc_set_policy.restype = ct.c_int
iptc_set_policy.argstype = [ct.c_char_p, ct.c_char_p,
ct.POINTER(xt_counters), ct.c_void_p]
# Get first rule in the given chain: NULL for empty chain.
iptc_first_rule = _libiptc.iptc_first_rule
iptc_first_rule.restype = ct.POINTER(ipt_entry)
iptc_first_rule.argstype = [ct.c_char_p, ct.c_void_p]
# Returns NULL when rules run out.
iptc_next_rule = _libiptc.iptc_next_rule
iptc_next_rule.restype = ct.POINTER(ipt_entry)
iptc_next_rule.argstype = [ct.POINTER(ipt_entry), ct.c_void_p]
# Returns a pointer to the target name of this entry.
iptc_get_target = _libiptc.iptc_get_target
iptc_get_target.restype = ct.c_char_p
iptc_get_target.argstype = [ct.POINTER(ipt_entry), ct.c_void_p]
# These functions return TRUE for OK or 0 and set errno. If errno ==
# 0, it means there was a version error (ie. upgrade libiptc).
# Rule numbers start at 1 for the first rule.
# Insert the entry `e' in chain `chain' into position `rulenum'.
iptc_insert_entry = _libiptc.iptc_insert_entry
iptc_insert_entry.restype = ct.c_int
iptc_insert_entry.argstype = [ct.c_char_p, ct.POINTER(ipt_entry),
ct.c_int, ct.c_void_p]
# Atomically replace rule `rulenum' in `chain' with `e'.
iptc_replace_entry = _libiptc.iptc_replace_entry
iptc_replace_entry.restype = ct.c_int
iptc_replace_entry.argstype = [ct.c_char_p, ct.POINTER(ipt_entry),
ct.c_int, ct.c_void_p]
# Append entry `e' to chain `chain'. Equivalent to insert with
# rulenum = length of chain.
iptc_append_entry = _libiptc.iptc_append_entry
iptc_append_entry.restype = ct.c_int
iptc_append_entry.argstype = [ct.c_char_p, ct.POINTER(ipt_entry),
ct.c_void_p]
# Delete the first rule in `chain' which matches `e', subject to
# matchmask (array of length == origfw)
iptc_delete_entry = _libiptc.iptc_delete_entry
iptc_delete_entry.restype = ct.c_int
iptc_delete_entry.argstype = [ct.c_char_p, ct.POINTER(ipt_entry),
ct.POINTER(ct.c_ubyte), ct.c_void_p]
# Delete the rule in position `rulenum' in `chain'.
iptc_delete_num_entry = _libiptc.iptc_delete_num_entry
iptc_delete_num_entry.restype = ct.c_int
iptc_delete_num_entry.argstype = [ct.c_char_p, ct.c_uint, ct.c_void_p]
# Check the packet `e' on chain `chain'. Returns the verdict, or
# NULL and sets errno.
# iptc_check_packet = _libiptc.iptc_check_packet
# iptc_check_packet.restype = ct.c_char_p
# iptc_check_packet.argstype = [ct.c_char_p, ct.POINTER(ipt), ct.c_void_p]
# Get the number of references to this chain
iptc_get_references = _libiptc.iptc_get_references
iptc_get_references.restype = ct.c_int
iptc_get_references.argstype = [ct.c_uint, ct.c_char_p, ct.c_void_p]
# read packet and byte counters for a specific rule
iptc_read_counter = _libiptc.iptc_read_counter
iptc_read_counter.restype = ct.POINTER(xt_counters)
iptc_read_counter.argstype = [ct.c_char_p, ct.c_uint, ct.c_void_p]
# zero packet and byte counters for a specific rule
iptc_zero_counter = _libiptc.iptc_zero_counter
iptc_zero_counter.restype = ct.c_int
iptc_zero_counter.argstype = [ct.c_char_p, ct.c_uint, ct.c_void_p]
# set packet and byte counters for a specific rule
iptc_set_counter = _libiptc.iptc_set_counter
iptc_set_counter.restype = ct.c_int
iptc_set_counter.argstype = [ct.c_char_p, ct.c_uint,
ct.POINTER(xt_counters), ct.c_void_p]
# Translates errno numbers into more human-readable form than strerror.
iptc_strerror = _libiptc.iptc_strerror
iptc_strerror.restype = ct.c_char_p
iptc_strerror.argstype = [ct.c_int]
class IPTCModule(object):
"""Superclass for Match and Target."""
pattern = re.compile(
r'\s*(!)?\s*--([-\w]+)\s+(!)?\s*"?([^"]*?)"?(?=\s*(?:!?\s*--|$))')
def __init__(self):
self._name = None
self._rule = None
self._module = None
self._revision = None
self._ptr = None
self._ptrptr = None
raise NotImplementedError()
def set_parameter(self, parameter, value=None):
"""
Set a parameter for target or match extension, with an optional value.
@param parameter: name of the parameter to set
@type parameter: C{str}
@param value: optional value of the parameter, defaults to C{None}
@type value: C{str} or a C{list} of C{str}
"""
if value is None:
value = ""
return self.parse(parameter.replace("_", "-"), value)
def parse(self, parameter, value):
# Parameter name must always be a string.
parameter = parameter.encode()
# Check if we are dealing with an inverted parameter value.
inv = ct.c_int(0)
if len(value) > 0 and value[0] == "!":
inv = ct.c_int(1)
value = value[1:]
# Value can be either a string, or a list of strings, e.g. "8888",
# "!0:65535" or ["!", "example_set", "dst"].
args = []
is_str = isinstance(value, str)
try:
if not is_str:
is_str = isinstance(value, unicode)
except:
pass
if is_str:
args = [value.encode()]
else:
try:
args = [val.encode() for val in value]
except:
raise TypeError("Invalid parameter value: "
"must be string or list of strings")
if not self._module.extra_opts and not self._module.x6_options:
raise AttributeError("%s: invalid parameter %s" %
(self._module.name, parameter))
parameter = parameter.strip()
N = len(args)
argv = (ct.c_char_p * (N + 1))()
argv[0] = parameter
for i in range(N):
argv[i + 1] = args[i]
entry = self._rule.entry and ct.pointer(self._rule.entry) or None
self._parse(argv, inv, entry)
def _parse(self, argv, inv, entry):
raise NotImplementedError()
def final_check(self):
if self._module:
self._update_parameters()
self._final_check() # subclasses override this
def _final_check(self):
raise NotImplementedError()
def _get_saved_buf(self, ip):
if not self._module or not self._module.save:
return None
# redirect C stdout to a pipe and read back the output of m->save
# Flush stdout to avoid getting buffered results
sys.stdout.flush()
# Save the current C stdout.
stdout = os.dup(1)
try:
# Create a pipe and use the write end to replace the original C
# stdout.
pipes = os.pipe()
os.dup2(pipes[1], 1)
self._xt.save(self._module, ip, self._ptr)
# Use the read end to read whatever was written.
buf = os.read(pipes[0], 1024)
# Clean up the pipe.
os.close(pipes[0])
os.close(pipes[1])
return buf
finally:
# Put the original C stdout back in place.
os.dup2(stdout, 1)
# Clean up the copy we made.
os.close(stdout)
def save(self, name):
return self._save(name, self.rule.get_ip())
def _save(self, name, ip):
buf = self._get_saved_buf(ip).decode()
if buf is None:
return None
if not self._module or not self._module.save:
return None
if name:
return self._get_value(buf, name)
else:
return self._get_all_values(buf)
def _get_all_values(self, buf):
table = {} # variable -> (value, inverted)
res = re.findall(IPTCModule.pattern, buf)
for x in res:
value, invert = (x[3], x[0] or x[2])
table[x[1].replace("-", "_")] = "%s%s" % (invert and "!" or "",
value)
return table
def _get_value(self, buf, name):
table = {} # variable -> (value, inverted)
res = re.findall(IPTCModule.pattern, buf)
for x in res:
table[x[1]] = (x[3], x[0] or x[2])
try:
value, invert = table[name]
return "%s%s" % (invert and "!" or "", value)
except KeyError:
return None
def get_all_parameters(self):
params = {}
ip = self.rule.get_ip()
buf = self._get_saved_buf(ip)
if buf is None:
return params
if type(buf) != str:
# In Python3, string and bytes are different types.
buf = buf.decode()
res = shlex.split(buf)
res.reverse()
inv = False
key = None
while len(res) > 0:
x = res.pop()
if x == '!':
# Next parameter is negated.
inv = True
continue
if x.startswith('--'): # This is a parameter name.
key = x[2:]
if inv:
params[key] = ['!']
else:
params[key] = []
inv = False
continue
# At this point key should be set, unless the output from save is
# not formatted right. Let's be defensive, since some users
# reported that problem.
if key is not None:
params[key].append(x) # This is a parameter value.
return params
def _update_parameters(self):
params = self.get_all_parameters().items()
self.reset()
for k, v in params:
self.set_parameter(k, v)
def _get_alias_name(self):
if not self._module or not self._ptr:
return None
alias = getattr(self._module, 'alias', None)
if not alias:
return None
return self._module.alias(self._ptr).decode()
def __setattr__(self, name, value):
if not name.startswith('_') and name not in dir(self):
self.parse(name.replace("_", "-"), value)
else:
object.__setattr__(self, name, value)
def __getattr__(self, name):
if not name.startswith('_'):
return self.save(name.replace("_", "-"))
def _get_parameters(self):
return self.save(None)
parameters = property(_get_parameters)
"""Dictionary with all parameters in the form of name -> value. A match or
target might have default parameters as well, so this dictionary will
contain those set by the module by default too."""
def _get_name(self):
alias = self._get_alias_name()
return alias and alias or self._name
name = property(_get_name)
"""Name of this target or match."""
def _get_rule(self):
return self._rule
def _set_rule(self, rule):
self._rule = rule
rule = property(_get_rule, _set_rule)
"""The rule this target or match belong to."""
class _Buffer(object):
def __init__(self, size=0):
if size > 0:
self.buffer = _malloc(size)
if self.buffer is None:
raise Exception("Can't allocate buffer")
else:
self.buffer = None
def __del__(self):
if self.buffer is not None:
_free(self.buffer)
class Match(IPTCModule):
"""Matches are extensions which can match for special header fields or
other attributes of a packet.
Target and match extensions in iptables have parameters. These parameters
are implemented as instance attributes in python. However, to make the
names of parameters legal attribute names they have to be converted. The
rule is to cut the leading double dash from the name, and replace
dashes in parameter names with underscores so they are accepted by
python as attribute names. E.g. the *TOS* target has parameters
*--set-tos*, *--and-tos*, *--or-tos* and *--xor-tos*; they become
*target.set_tos*, *target.and_tos*, *target.or_tos* and *target.xor_tos*,
respectively. The value of a parameter is always a string, if a parameter
does not take any value in the iptables extension, an empty string *""*
should be used.
"""
def __init__(self, rule, name=None, match=None, revision=None):
"""
*rule* is the Rule object this match belongs to; it can be changed
later via *set_rule()*. *name* is the name of the iptables match
extension (in lower case), *match* is the raw buffer of the match
structure if the caller has it. Either *name* or *match* must be
provided. *revision* is the revision number of the extension that
should be used; different revisions use different structures in C and
they usually only work with certain kernel versions. Python-iptables
by default will use the latest revision available.
"""
if not name and not match:
raise ValueError("can't create match based on nothing")
if not name:
name = match.u.user.name.decode()
self._name = name
self._rule = rule
self._orig_parse = None
self._orig_options = None
self._xt = xtables(rule.nfproto)
module = self._xt.find_match(name)
real_name = module and getattr(module[0], 'real_name', None) or None
if real_name:
# Alias name, look up real module.
self._name = real_name.decode()
self._orig_parse = getattr(module[0], 'x6_parse', None)
self._orig_options = getattr(module[0], 'x6_options', None)
module = self._xt.find_match(real_name)
if not module:
raise XTablesError("can't find match %s" % (name))
self._module = module[0]
self._module.mflags = 0
if revision is not None:
self._revision = revision
else:
self._revision = self._module.revision
self._match_buf = (ct.c_ubyte * self.size)()
if match:
ct.memmove(ct.byref(self._match_buf), ct.byref(match), self.size)
self._update_pointers()
self._check_alias()
else:
self.reset()
def _check_alias(self):
name = self._get_alias_name()
if name is None:
return
alias_module = self._xt.find_match(name)
if alias_module is None:
return
self._alias_module = alias_module[0]
self._orig_parse = getattr(self._alias_module, 'x6_parse', None)
self._orig_options = getattr(self._alias_module, 'x6_options', None)
def __eq__(self, match):
basesz = ct.sizeof(xt_entry_match)
if (self.name == match.name and
self.match_buf[basesz:self.usersize] ==
match.match_buf[basesz:match.usersize]):
return True
return False
def __hash__(self):
return (hash(self.match.u.match_size) ^
hash(self.match.u.user.name) ^
hash(self.match.u.user.revision) ^
hash(bytes(self.match_buf)))
def __ne__(self, match):
return not self.__eq__(match)
def _final_check(self):
self._xt.final_check_match(self._module)
def _parse(self, argv, inv, entry):
self._xt.parse_match(argv, inv, self._module, entry,
ct.cast(self._ptrptr, ct.POINTER(ct.c_void_p)),
self._orig_parse, self._orig_options)
def _get_size(self):
return xt_align(self._module.size + ct.sizeof(xt_entry_match))
size = property(_get_size)
"""This is the full size of the underlying C structure."""
def _get_user_size(self):
return self._module.userspacesize + ct.sizeof(xt_entry_match)
usersize = property(_get_user_size)
"""This is the size of the part of the underlying C structure that is used
in userspace."""
def _update_pointers(self):
self._ptr = ct.cast(ct.byref(self._match_buf),
ct.POINTER(xt_entry_match))
self._ptrptr = ct.cast(ct.pointer(self._ptr),
ct.POINTER(ct.POINTER(xt_entry_match)))
self._module.m = self._ptr
self._update_name()
def _update_name(self):
m = self._ptr[0]
m.u.user.name = self.name.encode()
def reset(self):
"""Reset the match.
Parameters are set to their default values, any flags are cleared."""
ct.memset(ct.byref(self._match_buf), 0, self.size)
self._update_pointers()
m = self._ptr[0]
m.u.match_size = self.size
m.u.user.revision = self._revision
if self._module.init:
self._module.init(self._ptr)
self._module.mflags = 0
udata_size = getattr(self._module, 'udata_size', 0)
if udata_size > 0:
udata_buf = (ct.c_ubyte * udata_size)()
self._module.udata = ct.cast(ct.byref(udata_buf), ct.c_void_p)
def _get_match(self):
return ct.cast(ct.byref(self.match_buf), ct.POINTER(xt_entry_match))[0]
match = property(_get_match)
"""This is the C structure used by the extension."""
def _get_match_buf(self):
return self._match_buf
match_buf = property(_get_match_buf)
"""This is the buffer holding the C structure used by the extension."""
class Target(IPTCModule):
"""Targets specify what to do with a packet when a match is found while
traversing the list of rule entries in a chain.
Target and match extensions in iptables have parameters. These parameters
are implemented as instance attributes in python. However, to make the
names of parameters legal attribute names they have to be converted. The
rule is to cut the leading double dash from the name, and replace
dashes in parameter names with underscores so they are accepted by
python as attribute names. E.g. the *TOS* target has parameters
*--set-tos*, *--and-tos*, *--or-tos* and *--xor-tos*; they become
*target.set_tos*, *target.and_tos*, *target.or_tos* and *target.xor_tos*,
respectively. The value of a parameter is always a string, if a parameter
does not take any value in the iptables extension, an empty string i.e. ""
should be used.
"""
STANDARD_TARGETS = ["", "ACCEPT", "DROP", "REJECT", "RETURN", "REDIRECT", "SNAT", "DNAT", \
"MASQUERADE", "MIRROR", "TOS", "MARK", "QUEUE", "LOG"]
"""This is the constant for all standard targets."""
def __init__(self, rule, name=None, target=None, revision=None, goto=None):
"""
*rule* is the Rule object this match belongs to; it can be changed
later via *set_rule()*. *name* is the name of the iptables target
extension (in upper case), *target* is the raw buffer of the target
structure if the caller has it. Either *name* or *target* must be
provided. *revision* is the revision number of the extension that
should be used; different revisions use different structures in C and
they usually only work with certain kernel versions. Python-iptables
by default will use the latest revision available.
If goto is True, then it converts '-j' to '-g'.
"""
if name is None and target is None:
raise ValueError("can't create target based on nothing")
if name is None:
name = target.u.user.name.decode()
self._name = name
self._rule = rule
self._orig_parse = None
self._orig_options = None
# NOTE:
# get_ip() returns the 'ip' structure that contains (1)the 'flags' field, and
# (2)the value for the GOTO flag.
# We *must* use get_ip() because the actual name of the field containing the
# structure apparently differs between implementation
ipstruct = rule.get_ip()
f_goto_attrs = [a for a in dir(ipstruct) if a.endswith('_F_GOTO')]
if len(f_goto_attrs) == 0:
raise RuntimeError('What kind of struct is this? It does not have "*_F_GOTO" constant!')
_F_GOTO = getattr(ipstruct, f_goto_attrs[0])
if target is not None or goto is None:
# We are 'decoding' existing Target
self._goto = bool(ipstruct.flags & _F_GOTO)
if goto is not None:
assert isinstance(goto, bool)
self._goto = goto
if goto:
ipstruct.flags |= _F_GOTO
else:
ipstruct.flags &= ~_F_GOTO
self._xt = xtables(rule.nfproto)
module = (self._is_standard_target() and
self._xt.find_target('') or
self._xt.find_target(name))
real_name = module and getattr(module[0], 'real_name', None) or None
if real_name:
# Alias name, look up real module.
self._name = real_name.decode()
self._orig_parse = getattr(module[0], 'x6_parse', None)
self._orig_options = getattr(module[0], 'x6_options', None)
module = self._xt.find_target(real_name)
if not module:
raise XTablesError("can't find target %s" % (name))
self._module = module[0]
self._module.tflags = 0
if revision is not None:
self._revision = revision
else:
self._revision = self._module.revision
self._create_buffer(target)
if self._is_standard_target():
self.standard_target = name
elif target:
self._check_alias()
def _check_alias(self):
name = self._get_alias_name()
if name is None:
return
alias_module = self._xt.find_target(name)
if alias_module is None:
return
self._alias_module = alias_module[0]
self._orig_parse = getattr(self._alias_module, 'x6_parse', None)
self._orig_options = getattr(self._alias_module, 'x6_options', None)
def __eq__(self, targ):
basesz = ct.sizeof(xt_entry_target)
if (self.target.u.target_size != targ.target.u.target_size or
self.target.u.user.name != targ.target.u.user.name or
self.target.u.user.revision != targ.target.u.user.revision):
return False
if (self.target.u.user.name == b"" or
self.target.u.user.name == b"standard" or
self.target.u.user.name == b"ACCEPT" or
self.target.u.user.name == b"DROP" or
self.target.u.user.name == b"RETURN" or
self.target.u.user.name == b"ERROR" or
self._is_standard_target()):
return True
if (self._target_buf[basesz:self.usersize] ==
targ._target_buf[basesz:targ.usersize]):
return True
return False
def __ne__(self, target):
return not self.__eq__(target)
def _create_buffer(self, target):
self._buffer = _Buffer(self.size)
self._target_buf = self._buffer.buffer
if target:
ct.memmove(self._target_buf, ct.byref(target), self.size)
self._update_pointers()
else:
self.reset()
def _is_standard_target(self):
if self._name in Target.STANDARD_TARGETS:
return False
for t in self._rule.tables:
if t.is_chain(self._name):
return True
return False
def _final_check(self):
self._xt.final_check_target(self._module)
def _parse(self, argv, inv, entry):
self._xt.parse_target(argv, inv, self._module, entry,
ct.cast(self._ptrptr, ct.POINTER(ct.c_void_p)),
self._orig_parse, self._orig_options)
self._target_buf = ct.cast(self._module.t, ct.POINTER(ct.c_ubyte))
if self._buffer.buffer != self._target_buf:
self._buffer.buffer = self._target_buf
self._update_pointers()
def _get_size(self):
return xt_align(self._module.size + ct.sizeof(xt_entry_target))
size = property(_get_size)
"""This is the full size of the underlying C structure."""
def _get_user_size(self):
return self._module.userspacesize + ct.sizeof(xt_entry_target)
usersize = property(_get_user_size)
"""This is the size of the part of the underlying C structure that is used
in userspace."""
def _get_standard_target(self):
t = self._ptr[0]
return t.u.user.name.decode()
def _set_standard_target(self, name):
t = self._ptr[0]
if isinstance(name, str):
name = name.encode()
t.u.user.name = name
if isinstance(name, bytes):
name = name.decode()
self._name = name
standard_target = property(_get_standard_target, _set_standard_target)
"""This attribute is used for standard targets. It can be set to
*ACCEPT*, *DROP*, *RETURN* or to a name of a chain the rule should jump
into."""
def _update_pointers(self):
self._ptr = ct.cast(self._target_buf, ct.POINTER(xt_entry_target))
self._ptrptr = ct.cast(ct.pointer(self._ptr),
ct.POINTER(ct.POINTER(xt_entry_target)))
self._module.t = self._ptr
self._update_name()
def _update_name(self):
m = self._ptr[0]
m.u.user.name = self.name.encode()
def reset(self):
"""Reset the target. Parameters are set to their default values, any
flags are cleared."""
ct.memset(self._target_buf, 0, self.size)
self._update_pointers()
t = self._ptr[0]
t.u.target_size = self.size
t.u.user.revision = self._revision
if self._module.init:
self._module.init(self._ptr)
self._module.tflags = 0
udata_size = getattr(self._module, 'udata_size', 0)
if udata_size > 0:
udata_buf = (ct.c_ubyte * udata_size)()
self._module.udata = ct.cast(ct.byref(udata_buf), ct.c_void_p)
def _get_target(self):
return self._ptr[0]
target = property(_get_target)
"""This is the C structure used by the extension."""
def _get_goto(self):
return self._goto
goto = property(_get_goto)
class Policy(object):
"""
If the end of a built-in chain is reached or a rule in a built-in chain
with target RETURN is matched, the target specified by the chain policy
determines the fate of the packet.
"""
ACCEPT = "ACCEPT"
"""If no matching rule has been found so far then accept the packet."""
DROP = "DROP"
"""If no matching rule has been found so far then drop the packet."""
QUEUE = "QUEUE"
"""If no matching rule has been found so far then queue the packet to
userspace."""
RETURN = "RETURN"
"""Return to calling chain."""
_cache = weakref.WeakValueDictionary()
def __new__(cls, name):
obj = Policy._cache.get(name, None)
if not obj:
obj = object.__new__(cls)
Policy._cache[name] = obj
return obj
def __init__(self, name):
self.name = name
def _a_to_i(addr):
return struct.unpack("I", addr)[0]
def _i_to_a(ip):
return struct.pack("I", int(ip.s_addr))
class Rule(object):
"""Rules are entries in chains.
Each rule has three parts:
* An entry with protocol family attributes like source and destination
address, transport protocol, etc. If the packet does not match the
attributes set here, then processing continues with the next rule or
the chain policy is applied at the end of the chain.
* Any number of matches. They are optional, and make it possible to
match for further packet attributes.
* One target. This determines what happens with the packet if it is
matched.
"""
protocols = {0: "all",
socket.IPPROTO_AH: "ah",
socket.IPPROTO_DSTOPTS: "dstopts",
socket.IPPROTO_EGP: "egp",
socket.IPPROTO_ESP: "esp",
socket.IPPROTO_FRAGMENT: "fragment",
socket.IPPROTO_GRE: "gre",
socket.IPPROTO_HOPOPTS: "hopopts",
socket.IPPROTO_ICMP: "icmp",
socket.IPPROTO_ICMPV6: "icmpv6",
socket.IPPROTO_IDP: "idp",
socket.IPPROTO_IGMP: "igmp",
socket.IPPROTO_IP: "ip",
socket.IPPROTO_IPIP: "ipip",
socket.IPPROTO_IPV6: "ipv6",
socket.IPPROTO_NONE: "none",
socket.IPPROTO_PIM: "pim",
socket.IPPROTO_PUP: "pup",
socket.IPPROTO_RAW: "raw",
socket.IPPROTO_ROUTING: "routing",
socket.IPPROTO_RSVP: "rsvp",
socket.IPPROTO_SCTP: "sctp",
socket.IPPROTO_TCP: "tcp",
socket.IPPROTO_TP: "tp",
socket.IPPROTO_UDP: "udp",
}
def __init__(self, entry=None, chain=None):
"""
*entry* is the ipt_entry buffer or None if the caller does not have
it. *chain* is the chain object this rule belongs to.
"""
self.nfproto = NFPROTO_IPV4
self._matches = []
self._target = None
self.chain = chain
self.rule = entry
def __eq__(self, rule):
if self._target != rule._target:
return False
if len(self._matches) != len(rule._matches):
return False
if set(rule._matches) != set([x for x in rule._matches if x in
self._matches]):
return False
if (self.src == rule.src and self.dst == rule.dst and
self.protocol == rule.protocol and
self.fragment == rule.fragment and
self.in_interface == rule.in_interface and
self.out_interface == rule.out_interface):
return True
return False
def __ne__(self, rule):
return not self.__eq__(rule)
def _get_tables(self):
return [Table(t) for t in Table.ALL if is_table_available(t)]
tables = property(_get_tables)
"""This is the list of tables for our protocol."""
def final_check(self):
"""Do a final check on the target and the matches."""
if self.target:
self.target.final_check()
for match in self.matches:
match.final_check()