This repository was archived by the owner on Jul 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrules.py
More file actions
99 lines (83 loc) · 2.46 KB
/
Copy pathrules.py
File metadata and controls
99 lines (83 loc) · 2.46 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
# -*- coding: utf-8 -*-
#! /usr/bin/env python3
"""
This module provides utilities for loading and verifying network packet rules.
"""
from re import compile as reg_comp, VERBOSE
from typing import List
from signature import Signature
RULE_REGEX = reg_comp(r""" ^
#sID
(\d{,99999}:\s)?
#PROTO
([A-Z]{,4}\s)
#IP
(!?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:)|any:)
#PORT
(!?[0-9]{,6}\s|(any)\s|!?\[[0-9]{,6}-[0-9]{,6}\]\s)
#DIR
(<>\s|->\s)
#IP
(!?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:)|any:)
#PORT
(!?[0-9]{,6}\s|(any)\s|!?\[[0-9]{,6}-[0-9]{,6}\]\s)
#PAYLOAD
(\*)
$ """, VERBOSE)
def verify_rules(ruleset: List[str]) -> List[Signature]:
"""
Verifies a list of rules and converts them into Signature objects.
Parameters
----------
ruleset : List[str]
A list of rules in string format.
Returns
-------
List[Signature]
A list of valid Signature objects.
Raises
------
ValueError
If a rule does not match the syntax or if there are duplicate IDs.
"""
signatures = []
for rule in ruleset:
if not rule.startswith('#'):
if RULE_REGEX.match(rule):
signature = Signature(rule)
if not signature.s_id:
signature.s_id = str(len(signatures) + 1)
if signature.s_id in {s.s_id for s in signatures}:
raise ValueError(f'ID in use for {rule}')
signatures.append(signature)
else:
raise ValueError(f"{rule} does not match the syntax")
if not signatures:
raise ValueError('Empty signature set')
return signatures
def load_rules(path: str) -> List[Signature]:
"""
Loads rules from a file and verifies them.
Parameters
----------
path : str
The file path to load the rules from.
Returns
-------
List[Signature]
A list of valid Signature objects.
Raises
------
ValueError
If the file is not found or if the rules are invalid.
"""
try:
with open(path) as file:
rules = file.readlines()
except FileNotFoundError as e:
raise ValueError(f"File not found: {path}") from e
try:
verified_rules = verify_rules([rule.strip() for rule in rules if rule.strip()])
except ValueError as e:
raise ValueError(f"Error verifying rules in {path}: {e}") from e
return verified_rules