-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity_utils.py
More file actions
284 lines (218 loc) · 8.42 KB
/
Copy pathsecurity_utils.py
File metadata and controls
284 lines (218 loc) · 8.42 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
"""Security utilities - Input validation, sanitization, and protection"""
import re
from typing import Optional
from urllib.parse import urlparse
from loguru import logger
class InputValidator:
"""Validate and sanitize user input"""
# Dangerous patterns that could indicate injection attempts
DANGEROUS_PATTERNS = [
r'javascript:',
r'<script',
r'onerror=',
r'onload=',
r'eval\(',
r'expression\(',
r'vbscript:',
r'data:text/html',
]
# Valid URL schemes (expanded for multiple protocols)
VALID_SCHEMES = [
'http', 'https', # Web
'ftp', 'ftps', # File transfer
'ws', 'wss', # WebSocket
'rtsp', 'rtmp', # Streaming
'ssh', 'sftp', # Secure protocols
]
# Maximum URL length
MAX_URL_LENGTH = 2048
@classmethod
def validate_url(cls, url: str) -> tuple[bool, Optional[str]]:
"""
Validate URL for security and format
Returns:
(is_valid, error_message)
"""
if not url:
return False, "URL cannot be empty"
# Strip whitespace
url = url.strip()
# Check length
if len(url) > cls.MAX_URL_LENGTH:
return False, f"URL too long (max {cls.MAX_URL_LENGTH} characters)"
# Check for dangerous patterns
for pattern in cls.DANGEROUS_PATTERNS:
if re.search(pattern, url, re.IGNORECASE):
logger.warning(f"Dangerous pattern detected in URL: {pattern}")
return False, "Invalid URL format (security check failed)"
# Add scheme if missing
supported_protocols = (
'http://', 'https://',
'ftp://', 'ftps://',
'ws://', 'wss://',
'rtsp://', 'rtmp://',
'ssh://', 'sftp://',
)
if not any(url.startswith(proto) for proto in supported_protocols):
url = 'https://' + url
# Parse URL
try:
parsed = urlparse(url)
# Check scheme
if parsed.scheme not in cls.VALID_SCHEMES:
return False, f"Invalid URL scheme (must be {' or '.join(cls.VALID_SCHEMES)})"
# Check netloc (domain)
if not parsed.netloc:
return False, "Invalid URL format (no domain found)"
# Check for IP address (optional - you might want to allow this)
# Uncomment if you want to block direct IP access
# if re.match(r'^\d+\.\d+\.\d+\.\d+$', parsed.netloc):
# return False, "Direct IP addresses are not allowed"
return True, None
except Exception as e:
logger.error(f"URL parsing error: {e}")
return False, "Invalid URL format"
@classmethod
def sanitize_url(cls, url: str) -> str:
"""Sanitize URL for safe processing"""
# Strip whitespace
url = url.strip()
# Supported protocols
supported_protocols = (
'http://', 'https://',
'ftp://', 'ftps://',
'ws://', 'wss://',
'rtsp://', 'rtmp://',
'ssh://', 'sftp://',
)
# Add scheme if missing
if not any(url.startswith(proto) for proto in supported_protocols):
url = 'https://' + url
# Parse and reconstruct to normalize
try:
parsed = urlparse(url)
# Reconstruct with only safe components
sanitized = f"{parsed.scheme}://{parsed.netloc}"
if parsed.path:
sanitized += parsed.path
if parsed.query:
sanitized += f"?{parsed.query}"
return sanitized
except Exception:
return url
@classmethod
def validate_bookmark_name(cls, name: str) -> tuple[bool, Optional[str]]:
"""Validate bookmark name"""
if not name:
return False, "Name cannot be empty"
if len(name) > 100:
return False, "Name too long (max 100 characters)"
# Check for dangerous patterns
for pattern in cls.DANGEROUS_PATTERNS:
if re.search(pattern, name, re.IGNORECASE):
return False, "Invalid name format"
return True, None
@classmethod
def sanitize_text(cls, text: str) -> str:
"""Sanitize text for safe display"""
if not text:
return ""
# Remove potential XSS patterns
text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.IGNORECASE | re.DOTALL)
text = re.sub(r'javascript:', '', text, flags=re.IGNORECASE)
text = re.sub(r'on\w+\s*=', '', text, flags=re.IGNORECASE)
return text.strip()
class RateLimitTracker:
"""Track and enforce rate limits per user"""
def __init__(self):
self.user_requests = {}
def check_rate_limit(
self,
user_id: int,
max_requests: int = 10,
time_window: int = 60
) -> tuple[bool, Optional[str]]:
"""
Check if user has exceeded rate limit
Args:
user_id: Telegram user ID
max_requests: Maximum requests allowed
time_window: Time window in seconds
Returns:
(is_allowed, error_message)
"""
import time
now = time.time()
# Initialize user if not exists
if user_id not in self.user_requests:
self.user_requests[user_id] = []
# Remove old requests outside time window
self.user_requests[user_id] = [
req_time for req_time in self.user_requests[user_id]
if now - req_time < time_window
]
# Check limit
if len(self.user_requests[user_id]) >= max_requests:
remaining_time = time_window - (now - self.user_requests[user_id][0])
return False, f"Rate limit exceeded. Try again in {int(remaining_time)}s"
# Record this request
self.user_requests[user_id].append(now)
return True, None
class SecurityHeaders:
"""Security headers for web responses"""
@staticmethod
def get_security_headers() -> dict:
"""Get recommended security headers"""
return {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
'Content-Security-Policy': "default-src 'self'",
'Referrer-Policy': 'strict-origin-when-cross-origin'
}
class DataEncryption:
"""Simple encryption utilities for sensitive data"""
@staticmethod
def hash_sensitive_data(data: str) -> str:
"""Hash sensitive data (e.g., for logging)"""
import hashlib
return hashlib.sha256(data.encode()).hexdigest()[:16]
@staticmethod
def redact_sensitive_info(text: str) -> str:
"""Redact sensitive information from text"""
# Redact API keys
text = re.sub(
r'(?i)(api[_-]?key|token|secret)["\']?\s*[:=]\s*["\']?([a-zA-Z0-9_-]+)',
r'\1: ***REDACTED***',
text
)
# Redact passwords
text = re.sub(
r'(?i)(password|passwd|pwd)["\']?\s*[:=]\s*["\']?([^\s"\']+)',
r'\1: ***REDACTED***',
text
)
# Redact email addresses
text = re.sub(
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
'***EMAIL***',
text
)
return text
# Global instances
input_validator = InputValidator()
rate_limit_tracker = RateLimitTracker()
# Convenience functions
def validate_url(url: str) -> tuple[bool, Optional[str]]:
"""Validate URL"""
return input_validator.validate_url(url)
def sanitize_url(url: str) -> str:
"""Sanitize URL"""
return input_validator.sanitize_url(url)
def check_rate_limit(user_id: int) -> tuple[bool, Optional[str]]:
"""Check rate limit for user"""
return rate_limit_tracker.check_rate_limit(user_id)
def sanitize_text(text: str) -> str:
"""Sanitize text"""
return input_validator.sanitize_text(text)