-
Notifications
You must be signed in to change notification settings - Fork 1
/
blockpage.py
93 lines (71 loc) · 2.44 KB
/
blockpage.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
"""
Matcher for response pages to blockpage signatures.
References
----------
Adapted from:
https://github.com/censoredplanet/censoredplanet-analysis
"""
from collections import OrderedDict
import json
import io
import pkgutil
import re
from typing import Optional, Dict, Tuple
# Signature filenames
FALSE_POSITIVES = 'flatten_data/false_positive_signatures.json'
BLOCKPAGES = 'flatten_data/blockpage_signatures.json'
def _load_signatures(filepath: str) -> Dict[str, re.Pattern]:
"""Load signatures for blockpage matching.
Args:
filepath: relative path to json file containing signatures
Returns:
Dictionary mapping fingerprints to signature patterns
"""
data = pkgutil.get_data(__name__, filepath)
if not data:
raise FileNotFoundError(f"Couldn't find file {filepath}")
content = io.TextIOWrapper(io.BytesIO(data), encoding='utf-8')
signatures = OrderedDict()
for line in content.readlines():
if line != '\n':
signature = json.loads(line.strip())
pattern = signature['pattern']
fingerprint = signature['fingerprint']
signatures[fingerprint] = re.compile(pattern, re.DOTALL)
return signatures
class BlockpageMatcher:
"""
Matcher to confirm blockpages or false positives.
References
----------
Adapted from:
https://github.com/censoredplanet/censoredplanet-analysis/blob/master/pipeline/metadata/blockpage.py
"""
def __init__(self) -> None:
"""Create a Blockpage Matcher."""
self.false_positives = _load_signatures(FALSE_POSITIVES)
self.blockpages = _load_signatures(BLOCKPAGES)
def match_page(self, page: str) -> Tuple[Optional[bool], Optional[str]]:
"""
Check if the input page matches a known blockpage or false positive.
Parameters
----------
page: str
A string containing the HTTP body of the potential blockpage
Returns
-------
Tuple[Optional[bool], Optional[str]]
(match_outcome, match_fingerprint)
match_outcome is
- *True* if page matches a blockpage signature.
- *False* if page matches a false positive signature.
- *None* otherwise.
match_fingerprint is a signature for a blockpage/fp like 'a_prod_cisco'
"""
for fingerprint, pattern in self.false_positives.items():
if pattern.search(page):
return (False, fingerprint)
for fingerprint, pattern in self.blockpages.items():
if pattern.search(page):
return (True, fingerprint)
return (None, None)