flask-waf 2.0.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flask_Waf/__init__.py +12 -0
- flask_Waf/anomaly_detection.py +37 -0
- flask_Waf/config.py +31 -0
- flask_Waf/content_security.py +25 -0
- flask_Waf/geo_ip.py +16 -0
- flask_Waf/logging.py +48 -0
- flask_Waf/rate_limiter.py +20 -0
- flask_Waf/rules.py +43 -0
- flask_Waf/session_protection.py +25 -0
- flask_Waf/threat_intelligence.py +36 -0
- flask_Waf/waf.py +100 -0
- flask_waf-2.0.9.dist-info/METADATA +222 -0
- flask_waf-2.0.9.dist-info/RECORD +16 -0
- flask_waf-2.0.9.dist-info/WHEEL +5 -0
- flask_waf-2.0.9.dist-info/licenses/LICENCE +21 -0
- flask_waf-2.0.9.dist-info/top_level.txt +1 -0
flask_Waf/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .waf import WAF
|
|
2
|
+
from .rules import RuleEngine
|
|
3
|
+
from .logging import WAFLogger
|
|
4
|
+
from .config import WAFConfig
|
|
5
|
+
from .rate_limiter import RateLimiter
|
|
6
|
+
from .session_protection import SessionProtection
|
|
7
|
+
from .content_security import ContentSecurityPolicy
|
|
8
|
+
from .threat_intelligence import ThreatIntelligence
|
|
9
|
+
from .anomaly_detection import AnomalyDetection
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from collections import defaultdict
|
|
2
|
+
import time
|
|
3
|
+
|
|
4
|
+
class AnomalyDetection:
|
|
5
|
+
def __init__(self, threshold=10):
|
|
6
|
+
self.threshold = threshold
|
|
7
|
+
self.request_count = defaultdict(int)
|
|
8
|
+
self.last_reset = time.time()
|
|
9
|
+
self.reset_interval = 60 # Reset counters every 60 seconds
|
|
10
|
+
|
|
11
|
+
def is_anomalous(self, request):
|
|
12
|
+
current_time = time.time()
|
|
13
|
+
if current_time - self.last_reset > self.reset_interval:
|
|
14
|
+
self.request_count.clear()
|
|
15
|
+
self.last_reset = current_time
|
|
16
|
+
|
|
17
|
+
ip = request.remote_addr
|
|
18
|
+
self.request_count[ip] += 1
|
|
19
|
+
|
|
20
|
+
if self.request_count[ip] > self.threshold:
|
|
21
|
+
return True
|
|
22
|
+
|
|
23
|
+
# Check for unusual patterns in headers
|
|
24
|
+
if self._check_unusual_headers(request.headers):
|
|
25
|
+
return True
|
|
26
|
+
|
|
27
|
+
# Check for unusual payload size
|
|
28
|
+
content_length = request.headers.get('Content-Length', 0)
|
|
29
|
+
if int(content_length) > 1000000: # 1MB
|
|
30
|
+
return True
|
|
31
|
+
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
def _check_unusual_headers(self, headers):
|
|
35
|
+
unusual_headers = ['X-Forwarded-For', 'X-Real-IP', 'X-Originating-IP']
|
|
36
|
+
return any(header in headers for header in unusual_headers)
|
|
37
|
+
|
flask_Waf/config.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
class WAFConfig:
|
|
4
|
+
def __init__(self):
|
|
5
|
+
self.max_request_size = 1024 * 1024 # 1 MB
|
|
6
|
+
self.allowed_content_types = [
|
|
7
|
+
'application/x-www-form-urlencoded',
|
|
8
|
+
'application/json',
|
|
9
|
+
'multipart/form-data'
|
|
10
|
+
]
|
|
11
|
+
self.max_url_length = 2083 # Common max URL length
|
|
12
|
+
self.max_query_params = 100
|
|
13
|
+
self.max_headers = 100
|
|
14
|
+
self.required_headers = ['Host', 'User-Agent']
|
|
15
|
+
self.blocked_countries = [] # List of country codes to block
|
|
16
|
+
self.rate_limit = 100 # Requests per minute
|
|
17
|
+
self.geoip_database_path = 'path/to/geoip/database'
|
|
18
|
+
|
|
19
|
+
def load_from_file(self, config_file):
|
|
20
|
+
with open(config_file, 'r') as f:
|
|
21
|
+
config_data = json.load(f)
|
|
22
|
+
|
|
23
|
+
for key, value in config_data.items():
|
|
24
|
+
if hasattr(self, key):
|
|
25
|
+
setattr(self, key, value)
|
|
26
|
+
|
|
27
|
+
def save_to_file(self, config_file):
|
|
28
|
+
config_data = {key: value for key, value in self.__dict__.items() if not key.startswith('__')}
|
|
29
|
+
with open(config_file, 'w') as f:
|
|
30
|
+
json.dump(config_data, f, indent=4)
|
|
31
|
+
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
class ContentSecurityPolicy:
|
|
2
|
+
def __init__(self):
|
|
3
|
+
self.policies = {
|
|
4
|
+
'default-src': ["'self'"],
|
|
5
|
+
'script-src': ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
|
|
6
|
+
'style-src': ["'self'", "'unsafe-inline'"],
|
|
7
|
+
'img-src': ["'self'", "data:", "https:"],
|
|
8
|
+
'font-src': ["'self'", "https:", "data:"],
|
|
9
|
+
'connect-src': ["'self'"],
|
|
10
|
+
'media-src': ["'self'"],
|
|
11
|
+
'object-src': ["'none'"],
|
|
12
|
+
'frame-src': ["'self'"],
|
|
13
|
+
'base-uri': ["'self'"],
|
|
14
|
+
'form-action': ["'self'"],
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
def add_policy(self, directive, source):
|
|
18
|
+
if directive in self.policies:
|
|
19
|
+
self.policies[directive].append(source)
|
|
20
|
+
else:
|
|
21
|
+
self.policies[directive] = [source]
|
|
22
|
+
|
|
23
|
+
def generate_csp_header(self):
|
|
24
|
+
return '; '.join(f"{key} {' '.join(value)}" for key, value in self.policies.items())
|
|
25
|
+
|
flask_Waf/geo_ip.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import geoip2.database
|
|
2
|
+
|
|
3
|
+
class GeoIPDatabase:
|
|
4
|
+
def __init__(self, database_path):
|
|
5
|
+
self.reader = geoip2.database.Reader(database_path)
|
|
6
|
+
|
|
7
|
+
def lookup(self, ip_address):
|
|
8
|
+
try:
|
|
9
|
+
response = self.reader.country(ip_address)
|
|
10
|
+
return response.country.iso_code
|
|
11
|
+
except geoip2.errors.AddressNotFoundError:
|
|
12
|
+
return None
|
|
13
|
+
|
|
14
|
+
def __del__(self):
|
|
15
|
+
self.reader.close()
|
|
16
|
+
|
flask_Waf/logging.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from flask import request
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
|
|
6
|
+
class WAFLogger:
|
|
7
|
+
def __init__(self, log_file='waf.log'):
|
|
8
|
+
self.logger = logging.getLogger('flask_waf')
|
|
9
|
+
self.logger.setLevel(logging.INFO)
|
|
10
|
+
handler = logging.FileHandler(log_file)
|
|
11
|
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
12
|
+
handler.setFormatter(formatter)
|
|
13
|
+
self.logger.addHandler(handler)
|
|
14
|
+
|
|
15
|
+
def log_request(self, req):
|
|
16
|
+
log_data = {
|
|
17
|
+
'timestamp': datetime.now().isoformat(),
|
|
18
|
+
'method': req.method,
|
|
19
|
+
'url': req.url,
|
|
20
|
+
'headers': dict(req.headers),
|
|
21
|
+
'body': req.get_data(as_text=True),
|
|
22
|
+
'remote_addr': req.remote_addr
|
|
23
|
+
}
|
|
24
|
+
self.logger.info(f"Request: {json.dumps(log_data)}")
|
|
25
|
+
|
|
26
|
+
def log_violations(self, req, violations):
|
|
27
|
+
log_data = {
|
|
28
|
+
'timestamp': datetime.now().isoformat(),
|
|
29
|
+
'method': req.method,
|
|
30
|
+
'url': req.url,
|
|
31
|
+
'remote_addr': req.remote_addr,
|
|
32
|
+
'violations': violations
|
|
33
|
+
}
|
|
34
|
+
self.logger.warning(f"Violations: {json.dumps(log_data)}")
|
|
35
|
+
|
|
36
|
+
def log_blocked_request(self, req, reason):
|
|
37
|
+
log_data = {
|
|
38
|
+
'timestamp': datetime.now().isoformat(),
|
|
39
|
+
'method': req.method,
|
|
40
|
+
'url': req.url,
|
|
41
|
+
'remote_addr': req.remote_addr,
|
|
42
|
+
'reason': reason
|
|
43
|
+
}
|
|
44
|
+
self.logger.warning(f"Blocked Request: {json.dumps(log_data)}")
|
|
45
|
+
|
|
46
|
+
def log_error(self, message):
|
|
47
|
+
self.logger.error(message)
|
|
48
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
class RateLimiter:
|
|
4
|
+
def __init__(self, limit, window):
|
|
5
|
+
self.limit = limit
|
|
6
|
+
self.window = window
|
|
7
|
+
self.requests = {}
|
|
8
|
+
|
|
9
|
+
def is_rate_limited(self, ip):
|
|
10
|
+
current_time = time.time()
|
|
11
|
+
if ip in self.requests:
|
|
12
|
+
request_times = self.requests[ip]
|
|
13
|
+
request_times = [t for t in request_times if current_time - t <= self.window]
|
|
14
|
+
if len(request_times) >= self.limit:
|
|
15
|
+
return True
|
|
16
|
+
self.requests[ip] = request_times + [current_time]
|
|
17
|
+
else:
|
|
18
|
+
self.requests[ip] = [current_time]
|
|
19
|
+
return False
|
|
20
|
+
|
flask_Waf/rules.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from flask import request
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
class Rule:
|
|
6
|
+
def __init__(self, name, pattern, locations):
|
|
7
|
+
self.name = name
|
|
8
|
+
self.pattern = re.compile(pattern, re.IGNORECASE)
|
|
9
|
+
self.locations = locations
|
|
10
|
+
|
|
11
|
+
def check(self, data):
|
|
12
|
+
return bool(self.pattern.search(data))
|
|
13
|
+
|
|
14
|
+
class RuleEngine:
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self.rules = [
|
|
17
|
+
Rule('SQL Injection', r'(\s|^)(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER)(\s|$)', ['params', 'form', 'json']),
|
|
18
|
+
Rule('XSS', r'<script.*?>|<.*?on\w+\s*=|javascript:', ['params', 'form', 'json']),
|
|
19
|
+
Rule('Path Traversal', r'\.\.\/|\.\.\\|%2e%2e%2f|%2e%2e/', ['params', 'path']),
|
|
20
|
+
Rule('Command Injection', r';\s*(\w+\s+)*(\w+)|\||\$\(|\`', ['params', 'form', 'json']),
|
|
21
|
+
Rule('File Inclusion', r'\.\./|\.\.\\|file://', ['params', 'path']),
|
|
22
|
+
Rule('HTTP Response Splitting', r'\r|\n', ['headers']),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
def check_request(self, req):
|
|
26
|
+
violations = []
|
|
27
|
+
|
|
28
|
+
for rule in self.rules:
|
|
29
|
+
if 'params' in rule.locations and rule.check(str(req.args)):
|
|
30
|
+
violations.append((rule.name, 'URL parameters'))
|
|
31
|
+
if 'form' in rule.locations and rule.check(str(req.form)):
|
|
32
|
+
violations.append((rule.name, 'Form data'))
|
|
33
|
+
if 'json' in rule.locations and req.is_json:
|
|
34
|
+
json_data = json.dumps(req.get_json())
|
|
35
|
+
if rule.check(json_data):
|
|
36
|
+
violations.append((rule.name, 'JSON data'))
|
|
37
|
+
if 'headers' in rule.locations and rule.check(str(req.headers)):
|
|
38
|
+
violations.append((rule.name, 'Headers'))
|
|
39
|
+
if 'path' in rule.locations and rule.check(req.path):
|
|
40
|
+
violations.append((rule.name, 'URL path'))
|
|
41
|
+
|
|
42
|
+
return violations
|
|
43
|
+
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
from flask import session
|
|
3
|
+
|
|
4
|
+
class SessionProtection:
|
|
5
|
+
def __init__(self):
|
|
6
|
+
self.secret_key = 'your-secret-key' # In production, use a secure random key
|
|
7
|
+
|
|
8
|
+
def validate_session(self, request):
|
|
9
|
+
if 'user_id' not in session:
|
|
10
|
+
return False
|
|
11
|
+
|
|
12
|
+
expected_hash = self._generate_session_hash(request)
|
|
13
|
+
return session.get('session_hash') == expected_hash
|
|
14
|
+
|
|
15
|
+
def set_session_data(self, request):
|
|
16
|
+
session['session_hash'] = self._generate_session_hash(request)
|
|
17
|
+
|
|
18
|
+
def _generate_session_hash(self, request):
|
|
19
|
+
user_agent = request.headers.get('User-Agent', '')
|
|
20
|
+
ip_address = request.remote_addr
|
|
21
|
+
user_id = session.get('user_id', '')
|
|
22
|
+
|
|
23
|
+
hash_input = f"{user_agent}{ip_address}{user_id}{self.secret_key}"
|
|
24
|
+
return hashlib.sha256(hash_input.encode()).hexdigest()
|
|
25
|
+
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
class ThreatIntelligence:
|
|
4
|
+
def __init__(self):
|
|
5
|
+
self.malicious_ip_ranges = [
|
|
6
|
+
('192.0.2.0', '192.0.2.255'), # Example range, replace with actual threat intel
|
|
7
|
+
]
|
|
8
|
+
self.malicious_patterns = [
|
|
9
|
+
r'malware\.com',
|
|
10
|
+
r'evil\.org',
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
def is_malicious(self, request):
|
|
14
|
+
ip = request.remote_addr
|
|
15
|
+
if self._is_ip_in_range(ip):
|
|
16
|
+
return True
|
|
17
|
+
|
|
18
|
+
url = request.url
|
|
19
|
+
user_agent = request.headers.get('User-Agent', '')
|
|
20
|
+
if self._match_patterns(url) or self._match_patterns(user_agent):
|
|
21
|
+
return True
|
|
22
|
+
|
|
23
|
+
return False
|
|
24
|
+
|
|
25
|
+
def _is_ip_in_range(self, ip):
|
|
26
|
+
ip_parts = list(map(int, ip.split('.')))
|
|
27
|
+
for start, end in self.malicious_ip_ranges:
|
|
28
|
+
start_parts = list(map(int, start.split('.')))
|
|
29
|
+
end_parts = list(map(int, end.split('.')))
|
|
30
|
+
if start_parts <= ip_parts <= end_parts:
|
|
31
|
+
return True
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
def _match_patterns(self, text):
|
|
35
|
+
return any(re.search(pattern, text, re.IGNORECASE) for pattern in self.malicious_patterns)
|
|
36
|
+
|
flask_Waf/waf.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from flask import abort , request
|
|
2
|
+
from werkzeug.exceptions import HTTPException
|
|
3
|
+
from .rules import RuleEngine
|
|
4
|
+
from .logging import WAFLogger
|
|
5
|
+
from .config import WAFConfig
|
|
6
|
+
from .rate_limiter import RateLimiter
|
|
7
|
+
from .session_protection import SessionProtection
|
|
8
|
+
from .content_security import ContentSecurityPolicy
|
|
9
|
+
from .threat_intelligence import ThreatIntelligence
|
|
10
|
+
from .anomaly_detection import AnomalyDetection
|
|
11
|
+
|
|
12
|
+
class WAF:
|
|
13
|
+
def __init__(self, app=None, config=None, config_file=None):
|
|
14
|
+
self.app = app
|
|
15
|
+
self.config = WAFConfig()
|
|
16
|
+
if config_file:
|
|
17
|
+
self.config.load_from_file(config_file)
|
|
18
|
+
if config:
|
|
19
|
+
for key, value in config.items():
|
|
20
|
+
if hasattr(self.config, key):
|
|
21
|
+
setattr(self.config, key, value)
|
|
22
|
+
self.rule_engine = RuleEngine()
|
|
23
|
+
self.logger = WAFLogger()
|
|
24
|
+
self.rate_limiter = RateLimiter(self.config.rate_limit, 60) # 60 seconds window
|
|
25
|
+
self.session_protection = SessionProtection()
|
|
26
|
+
self.csp = ContentSecurityPolicy()
|
|
27
|
+
self.threat_intel = ThreatIntelligence()
|
|
28
|
+
self.anomaly_detection = AnomalyDetection()
|
|
29
|
+
|
|
30
|
+
if app is not None:
|
|
31
|
+
self.init_app(app)
|
|
32
|
+
|
|
33
|
+
def init_app(self, app):
|
|
34
|
+
app.before_request(self.check_request)
|
|
35
|
+
app.after_request(self.add_security_headers)
|
|
36
|
+
|
|
37
|
+
def check_request(self):
|
|
38
|
+
# Basic checks
|
|
39
|
+
self._check_request_size()
|
|
40
|
+
self._check_url_length()
|
|
41
|
+
self._check_query_params()
|
|
42
|
+
self._check_headers()
|
|
43
|
+
self._check_rate_limit()
|
|
44
|
+
# Advanced checks
|
|
45
|
+
self._check_threat_intelligence()
|
|
46
|
+
self._check_anomalies()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _check_request_size(self):
|
|
50
|
+
if int(request.headers.get('Content-Length', 0)) > self.config.max_request_size:
|
|
51
|
+
self.logger.log_blocked_request(request, "Payload too large")
|
|
52
|
+
abort(413, description="Payload too large")
|
|
53
|
+
def _check_url_length(self):
|
|
54
|
+
if len(request.url) > self.config.max_url_length:
|
|
55
|
+
self.logger.log_blocked_request(request, "URI too long")
|
|
56
|
+
abort(414, description="URI too long")
|
|
57
|
+
|
|
58
|
+
def _check_query_params(self):
|
|
59
|
+
if len(request.args) > self.config.max_query_params:
|
|
60
|
+
self.logger.log_blocked_request(request, "Too many query parameters")
|
|
61
|
+
abort(400, description="Too many query parameters")
|
|
62
|
+
|
|
63
|
+
def _check_headers(self):
|
|
64
|
+
if len(request.headers) > self.config.max_headers:
|
|
65
|
+
self.logger.log_blocked_request(request, "Too many headers")
|
|
66
|
+
abort(400, description="Too many headers")
|
|
67
|
+
|
|
68
|
+
for header in self.config.required_headers:
|
|
69
|
+
if header not in request.headers:
|
|
70
|
+
self.logger.log_blocked_request(request, f"Missing required header: {header}")
|
|
71
|
+
abort(400, description=f"Missing required header: {header}")
|
|
72
|
+
|
|
73
|
+
def _check_rate_limit(self):
|
|
74
|
+
if self.rate_limiter.is_rate_limited(request.remote_addr):
|
|
75
|
+
self.logger.log_blocked_request(request, "Rate limit exceeded")
|
|
76
|
+
abort(429, description="Too many requests")
|
|
77
|
+
|
|
78
|
+
def _check_threat_intelligence(self):
|
|
79
|
+
if self.threat_intel.is_malicious(request):
|
|
80
|
+
self.logger.log_blocked_request(request, "Threat intelligence match")
|
|
81
|
+
abort(403, description="Request blocked by threat intelligence")
|
|
82
|
+
|
|
83
|
+
def _check_anomalies(self):
|
|
84
|
+
if self.anomaly_detection.is_anomalous(request):
|
|
85
|
+
self.logger.log_blocked_request(request, "Anomalous behavior detected")
|
|
86
|
+
abort(403, description="Request blocked due to anomalous behavior")
|
|
87
|
+
|
|
88
|
+
def add_security_headers(self, response):
|
|
89
|
+
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
|
|
90
|
+
response.headers['X-XSS-Protection'] = '1; mode=block'
|
|
91
|
+
response.headers['X-Content-Type-Options'] = 'nosniff'
|
|
92
|
+
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains; preload'
|
|
93
|
+
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
|
|
94
|
+
response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'
|
|
95
|
+
|
|
96
|
+
csp_header = self.csp.generate_csp_header()
|
|
97
|
+
response.headers['Content-Security-Policy'] = csp_header
|
|
98
|
+
|
|
99
|
+
return response
|
|
100
|
+
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flask_waf
|
|
3
|
+
Version: 2.0.9
|
|
4
|
+
Summary: Flask-WAF is an advanced Web Application Firewall (WAF) extension for Flask applications. It provides comprehensive protection against various web application threats, enhancing the security of your Flask-based web applications.
|
|
5
|
+
Home-page: https://github.com/ishanoshada/Flask-Waf
|
|
6
|
+
Author: Ishan Oshada
|
|
7
|
+
Author-email: ic31908@gmail.com
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENCE
|
|
13
|
+
Dynamic: author
|
|
14
|
+
Dynamic: author-email
|
|
15
|
+
Dynamic: classifier
|
|
16
|
+
Dynamic: description
|
|
17
|
+
Dynamic: description-content-type
|
|
18
|
+
Dynamic: home-page
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
Dynamic: summary
|
|
21
|
+
|
|
22
|
+
## Flask-WAF
|
|
23
|
+
|
|
24
|
+
Flask-WAF is an advanced Web Application Firewall (WAF) extension for Flask applications. It provides comprehensive protection against various web application threats, enhancing the security of your Flask-based web applications.
|
|
25
|
+
|
|
26
|
+
## Table of Contents
|
|
27
|
+
|
|
28
|
+
1. [Features](#features)
|
|
29
|
+
2. [Installation](#installation)
|
|
30
|
+
3. [Quick Start](#quick-start)
|
|
31
|
+
4. [Configuration](#configuration)
|
|
32
|
+
5. [Advanced Usage](#advanced-usage)
|
|
33
|
+
6. [API Reference](#api-reference)
|
|
34
|
+
7. [Contributing](#contributing)
|
|
35
|
+
8. [License](#license)
|
|
36
|
+
|
|
37
|
+
## Features
|
|
38
|
+
|
|
39
|
+
- Advanced rule engine for detecting and blocking malicious requests
|
|
40
|
+
- Session protection to prevent session hijacking and fixation attacks
|
|
41
|
+
- Content Security Policy (CSP) implementation
|
|
42
|
+
- Threat intelligence integration
|
|
43
|
+
- Anomaly detection to identify unusual patterns
|
|
44
|
+
- Rate limiting to prevent abuse
|
|
45
|
+
- Comprehensive logging
|
|
46
|
+
- Customizable security rules and policies
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
You can install Flask-WAF using pip:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install flask-waf
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Alternatively, you can install from the source:
|
|
57
|
+
|
|
58
|
+
```shellscript
|
|
59
|
+
git clone https://github.com/yourusername/flask-waf.git
|
|
60
|
+
cd flask-waf
|
|
61
|
+
pip install -e .
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Quick Start
|
|
65
|
+
|
|
66
|
+
Here's a simple example of how to use Flask-WAF:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from flask import Flask
|
|
70
|
+
from flask_waf import WAF
|
|
71
|
+
|
|
72
|
+
app = Flask(__name__)
|
|
73
|
+
app.config['SECRET_KEY'] = 'your-secret-key' # Required for session handling
|
|
74
|
+
waf = WAF(app)
|
|
75
|
+
|
|
76
|
+
@app.route('/')
|
|
77
|
+
def hello_world():
|
|
78
|
+
return 'Hello, World!'
|
|
79
|
+
|
|
80
|
+
if __name__ == '__main__':
|
|
81
|
+
app.run(debug=True)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
This basic setup will apply default WAF protection to your Flask application.
|
|
85
|
+
|
|
86
|
+
## Configuration
|
|
87
|
+
|
|
88
|
+
Flask-WAF can be configured using a JSON file or by passing a dictionary to the WAF constructor. Here's an example configuration:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
waf_config = {
|
|
92
|
+
"max_request_size": 1048576, # 1MB
|
|
93
|
+
"allowed_content_types": [
|
|
94
|
+
"application/x-www-form-urlencoded",
|
|
95
|
+
"application/json",
|
|
96
|
+
"multipart/form-data"
|
|
97
|
+
],
|
|
98
|
+
"max_url_length": 2083,
|
|
99
|
+
"max_query_params": 100,
|
|
100
|
+
"max_headers": 100,
|
|
101
|
+
"required_headers": ["Host", "User-Agent"],
|
|
102
|
+
"rate_limit": 100, # requests per minute
|
|
103
|
+
"session_protection": True,
|
|
104
|
+
"content_security_policy": {
|
|
105
|
+
"default-src": ["'self'"],
|
|
106
|
+
"script-src": ["'self'", "'unsafe-inline'"],
|
|
107
|
+
"style-src": ["'self'", "'unsafe-inline'"],
|
|
108
|
+
},
|
|
109
|
+
"anomaly_detection": {
|
|
110
|
+
"request_threshold": 10,
|
|
111
|
+
"time_window": 60
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
waf = WAF(app, config=waf_config)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
You can also load the configuration from a JSON file:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
waf = WAF(app, config_file='waf_config.json')
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Advanced Usage
|
|
125
|
+
|
|
126
|
+
### Custom Rules
|
|
127
|
+
|
|
128
|
+
You can add custom rules to the WAF's rule engine:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from flask_waf import WAF, Rule
|
|
132
|
+
|
|
133
|
+
waf = WAF(app)
|
|
134
|
+
|
|
135
|
+
custom_rule = Rule(
|
|
136
|
+
name='Custom SQL Injection Check',
|
|
137
|
+
pattern=r'UNION\s+SELECT',
|
|
138
|
+
locations=['params', 'form', 'json'],
|
|
139
|
+
severity='high',
|
|
140
|
+
description='Detected potential SQL injection attempt'
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
waf.rule_engine.add_rule(custom_rule)
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### Threat Intelligence Integration
|
|
147
|
+
|
|
148
|
+
You can update the threat intelligence module with custom malicious patterns:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
waf.threat_intel.add_malicious_pattern(r'malware\.com')
|
|
152
|
+
waf.threat_intel.add_malicious_ip_range('192.0.2.0', '192.0.2.255')
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Logging
|
|
156
|
+
|
|
157
|
+
Flask-WAF provides comprehensive logging. You can customize the log file location:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
waf.logger.set_log_file('/path/to/waf.log')
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## API Reference
|
|
164
|
+
|
|
165
|
+
### WAF Class
|
|
166
|
+
|
|
167
|
+
The main class for initializing the Web Application Firewall.
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
class WAF:
|
|
171
|
+
def __init__(self, app=None, config=None, config_file=None):
|
|
172
|
+
...
|
|
173
|
+
|
|
174
|
+
def init_app(self, app):
|
|
175
|
+
...
|
|
176
|
+
|
|
177
|
+
def check_request(self):
|
|
178
|
+
...
|
|
179
|
+
|
|
180
|
+
def add_security_headers(self, response):
|
|
181
|
+
...
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### Rule Class
|
|
185
|
+
|
|
186
|
+
Used for defining custom security rules.
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
class Rule:
|
|
190
|
+
def __init__(self, name, pattern, locations, severity='medium', description=''):
|
|
191
|
+
...
|
|
192
|
+
|
|
193
|
+
def check(self, data):
|
|
194
|
+
...
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
### RuleEngine Class
|
|
198
|
+
|
|
199
|
+
Manages and applies security rules.
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
class RuleEngine:
|
|
203
|
+
def add_rule(self, rule):
|
|
204
|
+
...
|
|
205
|
+
|
|
206
|
+
def remove_rule(self, rule_name):
|
|
207
|
+
...
|
|
208
|
+
|
|
209
|
+
def check_request(self, request):
|
|
210
|
+
...
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
For a complete API reference, please refer to the [API documentation](https://flask-waf.readthedocs.io/en/latest/api.html).
|
|
214
|
+
|
|
215
|
+
## Contributing
|
|
216
|
+
|
|
217
|
+
We welcome contributions! Please see our [contributing guide](CONTRIBUTING.md) for more details.
|
|
218
|
+
|
|
219
|
+
## License
|
|
220
|
+
|
|
221
|
+
Flask-WAF is released under the MIT License. See the [LICENSE](LICENSE) file for more details.
|
|
222
|
+
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
flask_Waf/__init__.py,sha256=DkgpXD8_XZVKnA0qstBhO01TkDzyF8BrClbtts-JQH4,355
|
|
2
|
+
flask_Waf/anomaly_detection.py,sha256=ZLFC-j3cB8prrSi5IuBZsEZWV-FXQyoEQ-uH8RtfDI8,1194
|
|
3
|
+
flask_Waf/config.py,sha256=5ofbOlW1JVZ7DdkDptxSPgxLOKNc9kMuzyg_y-7AkYU,1129
|
|
4
|
+
flask_Waf/content_security.py,sha256=n_L_y9A9tZKLPSmnAd-93ktnKW5-r17a8j2P6PO1_ak,922
|
|
5
|
+
flask_Waf/geo_ip.py,sha256=vlYqPuUSqug1CgfTBOeOOhn7tIAL2YolYoxdbPdrh-w,420
|
|
6
|
+
flask_Waf/logging.py,sha256=4iZqUV4KPFuw_5cN36-azjvYWS7MN-nO4jqFSRpOQ2Y,1589
|
|
7
|
+
flask_Waf/rate_limiter.py,sha256=mFytUWPm8f9mzoLgktEN-0f3TxDm9XMK89gJqW31pEM,616
|
|
8
|
+
flask_Waf/rules.py,sha256=3958Cp95udPDA7D3H3dVupjQXnBvjCLoW0pHd6zCd5E,1810
|
|
9
|
+
flask_Waf/session_protection.py,sha256=3Zmlzvdr02Io_a92pbpE0ZQTMxY1pnMOxBz9OS8VSvc,849
|
|
10
|
+
flask_Waf/threat_intelligence.py,sha256=aWbWqJV6stvehslW9lrPN5FVZpZIK8d0FoD8DDalhGw,1131
|
|
11
|
+
flask_Waf/waf.py,sha256=S5H2AU0MzxkRGznddW94eg8_g4lWIQ7mNuQwlu13N2I,4268
|
|
12
|
+
flask_waf-2.0.9.dist-info/licenses/LICENCE,sha256=njDqcnA-qVVDMzcvGXLTHi7atAFt_0uciWJ8FFVSXtc,1072
|
|
13
|
+
flask_waf-2.0.9.dist-info/METADATA,sha256=hw8vz6E2CrDiulYCTrHBaRk2RaTNzoSDvsSwKSSjmFM,5322
|
|
14
|
+
flask_waf-2.0.9.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
15
|
+
flask_waf-2.0.9.dist-info/top_level.txt,sha256=n8f3_GZufNUZ2GF76-BDwwMMq3_uEunJXtNVOfssE9U,10
|
|
16
|
+
flask_waf-2.0.9.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 K.A.ISHAN OSHADA
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
flask_Waf
|