0
# Rules, Matches, and Targets
1
2
Comprehensive rule creation, matching, and targeting system supporting all iptables match and target extensions. This module enables precise packet filtering and manipulation through flexible rule construction with extensible match conditions and actions.
3
4
## Capabilities
5
6
### Rule Creation and Management
7
8
Rules are the core filtering units in iptables that define packet matching criteria and actions. Each rule can contain multiple matches and must have exactly one target.
9
10
```python { .api }
11
class Rule:
12
"""
13
Represents an individual iptables rule with packet matching criteria and target action.
14
"""
15
16
def __init__(self, entry=None, chain=None):
17
"""
18
Initialize a Rule object.
19
20
Args:
21
entry: Optional low-level rule entry
22
chain: Optional parent chain
23
"""
24
25
@property
26
def src(self) -> str:
27
"""Source address/network (e.g., '192.168.1.0/24')"""
28
29
@src.setter
30
def src(self, value: str) -> None:
31
"""Set source address/network"""
32
33
@property
34
def dst(self) -> str:
35
"""Destination address/network (e.g., '10.0.0.0/8')"""
36
37
@dst.setter
38
def dst(self, value: str) -> None:
39
"""Set destination address/network"""
40
41
@property
42
def protocol(self) -> str:
43
"""Protocol (tcp, udp, icmp, etc.)"""
44
45
@protocol.setter
46
def protocol(self, value: str) -> None:
47
"""Set protocol"""
48
49
@property
50
def in_interface(self) -> str:
51
"""Input interface (e.g., 'eth0', 'eth+')"""
52
53
@in_interface.setter
54
def in_interface(self, value: str) -> None:
55
"""Set input interface"""
56
57
@property
58
def out_interface(self) -> str:
59
"""Output interface (e.g., 'eth0', 'eth+')"""
60
61
@out_interface.setter
62
def out_interface(self, value: str) -> None:
63
"""Set output interface"""
64
65
@property
66
def fragment(self) -> bool:
67
"""Fragment flag"""
68
69
@fragment.setter
70
def fragment(self, value: bool) -> None:
71
"""Set fragment flag"""
72
73
@property
74
def target(self) -> 'Target':
75
"""Rule target (action to take)"""
76
77
@target.setter
78
def target(self, value: 'Target') -> None:
79
"""Set rule target"""
80
81
@property
82
def matches(self) -> list:
83
"""List of Match objects"""
84
85
@property
86
def counters(self) -> tuple:
87
"""Packet and byte counters as (packets, bytes)"""
88
89
def create_match(self, name: str, revision: int = None) -> 'Match':
90
"""
91
Create and add a match to this rule.
92
93
Args:
94
name: Match name (tcp, udp, state, etc.)
95
revision: Optional match revision
96
97
Returns:
98
Match object
99
"""
100
101
def create_target(self, name: str, revision: int = None, goto: bool = False) -> 'Target':
102
"""
103
Create a target for this rule.
104
105
Args:
106
name: Target name (ACCEPT, DROP, MASQUERADE, etc.)
107
revision: Optional target revision
108
goto: Use goto instead of jump
109
110
Returns:
111
Target object
112
"""
113
114
def add_match(self, match: 'Match') -> None:
115
"""
116
Add an existing match to this rule.
117
118
Args:
119
match: Match object to add
120
"""
121
122
def remove_match(self, match: 'Match') -> None:
123
"""
124
Remove a match from this rule.
125
126
Args:
127
match: Match object to remove
128
"""
129
130
def get_counters(self) -> tuple:
131
"""
132
Get packet and byte counters.
133
134
Returns:
135
Tuple of (packets, bytes)
136
"""
137
138
def set_counters(self, packets: int, bytes: int) -> None:
139
"""
140
Set packet and byte counters.
141
142
Args:
143
packets: Packet count
144
bytes: Byte count
145
"""
146
147
def final_check(self) -> None:
148
"""Validate rule completeness and configuration"""
149
```
150
151
### Match Extensions
152
153
Matches provide flexible packet filtering conditions. All iptables match extensions are supported through dynamic attribute access.
154
155
```python { .api }
156
class Match:
157
"""
158
Represents an iptables match extension for packet filtering conditions.
159
"""
160
161
def __init__(self, rule: Rule, name: str = None, match=None, revision: int = None):
162
"""
163
Initialize a Match object.
164
165
Args:
166
rule: Parent Rule object
167
name: Match name (tcp, udp, state, etc.)
168
match: Optional low-level match object
169
revision: Optional match revision
170
"""
171
172
@property
173
def name(self) -> str:
174
"""Match name (tcp, udp, state, etc.)"""
175
176
@property
177
def parameters(self) -> dict:
178
"""Dictionary of all match parameters"""
179
180
@property
181
def size(self) -> int:
182
"""Size of underlying C structure"""
183
184
@property
185
def rule(self) -> Rule:
186
"""Parent Rule object"""
187
188
def set_parameter(self, parameter: str, value: str = None) -> None:
189
"""
190
Set a match parameter.
191
192
Args:
193
parameter: Parameter name
194
value: Parameter value
195
"""
196
197
def reset(self) -> None:
198
"""Reset match to default state"""
199
200
def final_check(self) -> None:
201
"""Validate match configuration"""
202
```
203
204
### Target Actions
205
206
Targets define what action to take when a packet matches a rule's conditions. Both standard targets and extension targets are supported.
207
208
```python { .api }
209
class Target:
210
"""
211
Represents an iptables target extension defining packet actions.
212
"""
213
214
STANDARD_TARGETS: list # List of standard target names
215
216
def __init__(self, rule: Rule, name: str = None, target=None, revision: int = None, goto: bool = None):
217
"""
218
Initialize a Target object.
219
220
Args:
221
rule: Parent Rule object
222
name: Target name (ACCEPT, DROP, MASQUERADE, etc.)
223
target: Optional low-level target object
224
revision: Optional target revision
225
goto: Use goto instead of jump
226
"""
227
228
@property
229
def name(self) -> str:
230
"""Target name"""
231
232
@property
233
def parameters(self) -> dict:
234
"""Dictionary of all target parameters"""
235
236
@property
237
def standard_target(self) -> str:
238
"""Standard target name if applicable"""
239
240
@property
241
def goto(self) -> bool:
242
"""Whether target uses goto"""
243
244
def set_parameter(self, parameter: str, value: str = None) -> None:
245
"""
246
Set a target parameter.
247
248
Args:
249
parameter: Parameter name
250
value: Parameter value
251
"""
252
253
def reset(self) -> None:
254
"""Reset target to default state"""
255
256
def final_check(self) -> None:
257
"""Validate target configuration"""
258
```
259
260
## Usage Examples
261
262
### Basic Rule Creation
263
264
```python
265
import iptc
266
267
# Create table and chain
268
table = iptc.Table(iptc.Table.FILTER)
269
chain = iptc.Chain(table, "INPUT")
270
271
# Create a rule to accept SSH traffic from specific network
272
rule = iptc.Rule()
273
rule.protocol = "tcp"
274
rule.src = "192.168.1.0/24"
275
rule.in_interface = "eth0"
276
277
# Add TCP match for SSH port
278
tcp_match = rule.create_match("tcp")
279
tcp_match.dport = "22"
280
281
# Set target to ACCEPT
282
rule.target = rule.create_target("ACCEPT")
283
284
# Insert rule into chain
285
chain.insert_rule(rule)
286
```
287
288
### Advanced Rule with Multiple Matches
289
290
```python
291
import iptc
292
293
table = iptc.Table(iptc.Table.FILTER)
294
chain = iptc.Chain(table, "INPUT")
295
296
# Create rule with multiple conditions
297
rule = iptc.Rule()
298
rule.protocol = "tcp"
299
300
# Add TCP match
301
tcp_match = rule.create_match("tcp")
302
tcp_match.dport = "80"
303
304
# Add state match for established connections
305
state_match = rule.create_match("state")
306
state_match.state = "ESTABLISHED,RELATED"
307
308
# Add comment match for documentation
309
comment_match = rule.create_match("comment")
310
comment_match.comment = "Allow established HTTP connections"
311
312
# Set target
313
rule.target = rule.create_target("ACCEPT")
314
315
chain.insert_rule(rule)
316
```
317
318
### NAT Rule Example
319
320
```python
321
import iptc
322
323
# Access NAT table
324
nat_table = iptc.Table(iptc.Table.NAT)
325
postrouting_chain = iptc.Chain(nat_table, "POSTROUTING")
326
327
# Create masquerade rule for outgoing traffic
328
rule = iptc.Rule()
329
rule.protocol = "tcp"
330
rule.out_interface = "eth0"
331
332
# Create MASQUERADE target
333
masq_target = rule.create_target("MASQUERADE")
334
masq_target.to_ports = "1024-65535"
335
336
rule.target = masq_target
337
postrouting_chain.append_rule(rule)
338
```
339
340
### Rule with Negation
341
342
```python
343
import iptc
344
345
table = iptc.Table(iptc.Table.FILTER)
346
chain = iptc.Chain(table, "INPUT")
347
348
# Create rule to block specific MAC address
349
rule = iptc.Rule()
350
351
# Add MAC match with negation
352
mac_match = rule.create_match("mac")
353
mac_match.mac_source = "!00:11:22:33:44:55" # ! for negation
354
355
rule.target = rule.create_target("DROP")
356
chain.insert_rule(rule)
357
```
358
359
### Complex Matching with iprange
360
361
```python
362
import iptc
363
364
table = iptc.Table(iptc.Table.FILTER)
365
chain = iptc.Chain(table, "INPUT")
366
367
rule = iptc.Rule()
368
rule.protocol = "tcp"
369
370
# Add TCP match
371
tcp_match = rule.create_match("tcp")
372
tcp_match.dport = "22"
373
374
# Add IP range match
375
iprange_match = rule.create_match("iprange")
376
iprange_match.src_range = "192.168.1.100-192.168.1.200"
377
iprange_match.dst_range = "172.22.33.106"
378
379
rule.target = rule.create_target("DROP")
380
chain.insert_rule(rule)
381
382
# This is equivalent to:
383
# iptables -A INPUT -p tcp --dport 22 -m iprange --src-range 192.168.1.100-192.168.1.200 --dst-range 172.22.33.106 -j DROP
384
```
385
386
### Working with Counters
387
388
```python
389
import iptc
390
import time
391
392
table = iptc.Table(iptc.Table.FILTER)
393
chain = iptc.Chain(table, "OUTPUT")
394
395
# Get current counters
396
for rule in chain.rules:
397
packets, bytes = rule.get_counters()
398
print(f"Rule counters: {packets} packets, {bytes} bytes")
399
400
# Wait and refresh to get updated counters
401
time.sleep(5)
402
table.refresh() # Important: refresh to get updated counters
403
404
for rule in chain.rules:
405
packets, bytes = rule.get_counters()
406
print(f"Updated counters: {packets} packets, {bytes} bytes")
407
```
408
409
### Match and Target Parameters
410
411
Different matches and targets have different parameters. Here are some common examples:
412
413
```python
414
import iptc
415
416
rule = iptc.Rule()
417
418
# TCP match parameters
419
tcp_match = rule.create_match("tcp")
420
tcp_match.sport = "80" # Source port
421
tcp_match.dport = "443" # Destination port
422
tcp_match.tcp_flags = "SYN,ACK SYN" # TCP flags
423
424
# UDP match parameters
425
udp_match = rule.create_match("udp")
426
udp_match.sport = "53"
427
udp_match.dport = "53"
428
429
# State match parameters
430
state_match = rule.create_match("state")
431
state_match.state = "NEW,ESTABLISHED,RELATED"
432
433
# Limit match parameters
434
limit_match = rule.create_match("limit")
435
limit_match.limit = "10/min"
436
limit_match.limit_burst = "5"
437
438
# MARK target parameters
439
mark_target = rule.create_target("MARK")
440
mark_target.set_mark = "0x1"
441
442
# DNAT target parameters
443
dnat_target = rule.create_target("DNAT")
444
dnat_target.to_destination = "192.168.1.100:8080"
445
446
# LOG target parameters
447
log_target = rule.create_target("LOG")
448
log_target.log_prefix = "DROPPED: "
449
log_target.log_level = "4"
450
```