-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinput_validator.py
More file actions
285 lines (233 loc) · 8.27 KB
/
input_validator.py
File metadata and controls
285 lines (233 loc) · 8.27 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
285
"""
Input validation and sanitization for BunBot favorites system.
Provides security-focused validation for user inputs.
"""
import re
import logging
from typing import Dict, Any, Optional
import validators
logger = logging.getLogger('discord')
class InputValidator:
"""Validates and sanitizes user inputs for security"""
# Maximum lengths for various inputs
MAX_STATION_NAME_LENGTH = 100
MAX_URL_LENGTH = 2048
MAX_SEARCH_TERM_LENGTH = 50
# Allowed characters for station names (alphanumeric, spaces, common punctuation)
STATION_NAME_PATTERN = re.compile(r'^[a-zA-Z0-9\s\-_.,!()&\'"]+$')
def __init__(self):
pass
def validate_url(self, url: str) -> Dict[str, Any]:
"""
Validate and sanitize a stream URL
Args:
url: URL to validate
Returns:
Dict with 'valid', 'sanitized_url', 'error' keys
"""
if not url:
return {
'valid': False,
'sanitized_url': None,
'error': 'URL cannot be empty'
}
# Remove leading/trailing whitespace
url = url.strip()
# Check length
if len(url) > self.MAX_URL_LENGTH:
return {
'valid': False,
'sanitized_url': None,
'error': f'URL too long (max {self.MAX_URL_LENGTH} characters)'
}
# Validate URL format
if not validators.url(url):
return {
'valid': False,
'sanitized_url': None,
'error': 'Invalid URL format'
}
# Check for allowed protocols
allowed_protocols = ['http', 'https']
protocol = url.split('://')[0].lower()
if protocol not in allowed_protocols:
return {
'valid': False,
'sanitized_url': None,
'error': f'Protocol not allowed. Use: {", ".join(allowed_protocols)}'
}
# Basic security checks
if self._contains_suspicious_patterns(url):
return {
'valid': False,
'sanitized_url': None,
'error': 'URL contains suspicious patterns'
}
return {
'valid': True,
'sanitized_url': url,
'error': None
}
def validate_station_name(self, name: str) -> Dict[str, Any]:
"""
Validate and sanitize a station name
Args:
name: Station name to validate
Returns:
Dict with 'valid', 'sanitized_name', 'error' keys
"""
if not name:
return {
'valid': False,
'sanitized_name': None,
'error': 'Station name cannot be empty'
}
# Remove leading/trailing whitespace and normalize
name = name.strip()
# Check length
if len(name) > self.MAX_STATION_NAME_LENGTH:
return {
'valid': False,
'sanitized_name': None,
'error': f'Station name too long (max {self.MAX_STATION_NAME_LENGTH} characters)'
}
# Check for allowed characters
if not self.STATION_NAME_PATTERN.match(name):
return {
'valid': False,
'sanitized_name': None,
'error': 'Station name contains invalid characters'
}
# Remove excessive whitespace
sanitized_name = re.sub(r'\s+', ' ', name)
return {
'valid': True,
'sanitized_name': sanitized_name,
'error': None
}
def validate_search_term(self, search_term: str) -> Dict[str, Any]:
"""
Validate and sanitize a search term
Args:
search_term: Search term to validate
Returns:
Dict with 'valid', 'sanitized_term', 'error' keys
"""
if not search_term:
return {
'valid': False,
'sanitized_term': None,
'error': 'Search term cannot be empty'
}
# Remove leading/trailing whitespace
search_term = search_term.strip()
# Check length
if len(search_term) > self.MAX_SEARCH_TERM_LENGTH:
return {
'valid': False,
'sanitized_term': None,
'error': f'Search term too long (max {self.MAX_SEARCH_TERM_LENGTH} characters)'
}
# Basic sanitization - remove SQL wildcards that could be abused
sanitized_term = search_term.replace('%', '').replace('_', '')
# Remove excessive whitespace
sanitized_term = re.sub(r'\s+', ' ', sanitized_term)
if not sanitized_term:
return {
'valid': False,
'sanitized_term': None,
'error': 'Search term contains only invalid characters'
}
return {
'valid': True,
'sanitized_term': sanitized_term,
'error': None
}
def validate_favorite_number(self, number: int) -> Dict[str, Any]:
"""
Validate a favorite number
Args:
number: Favorite number to validate
Returns:
Dict with 'valid', 'error' keys
"""
if not isinstance(number, int):
return {
'valid': False,
'error': 'Favorite number must be an integer'
}
if number < 1:
return {
'valid': False,
'error': 'Favorite number must be positive'
}
if number > 9999: # Reasonable upper limit
return {
'valid': False,
'error': 'Favorite number too large (max 9999)'
}
return {
'valid': True,
'error': None
}
def validate_role_name(self, role_name: str) -> Dict[str, Any]:
"""
Validate a permission role name
Args:
role_name: Role name to validate
Returns:
Dict with 'valid', 'sanitized_name', 'error' keys
"""
if not role_name:
return {
'valid': False,
'sanitized_name': None,
'error': 'Role name cannot be empty'
}
# Normalize to lowercase
role_name = role_name.strip().lower()
# Whitelist valid role names
valid_roles = {'user', 'dj', 'radio manager', 'admin'}
if role_name not in valid_roles:
return {
'valid': False,
'sanitized_name': None,
'error': f'Invalid role name. Valid options: {", ".join(valid_roles)}'
}
return {
'valid': True,
'sanitized_name': role_name,
'error': None
}
def _contains_suspicious_patterns(self, url: str) -> bool:
"""
Check for suspicious patterns in URLs that might indicate attacks
Args:
url: URL to check
Returns:
True if suspicious patterns found
"""
suspicious_patterns = [
# SQL injection attempts
r'(\bUNION\b|\bSELECT\b|\bINSERT\b|\bDELETE\b|\bDROP\b)',
# Script injection
r'(<script|javascript:|data:)',
# Path traversal
r'(\.\./|\.\.\\)',
# Null bytes
r'%00',
]
url_lower = url.lower()
for pattern in suspicious_patterns:
if re.search(pattern, url_lower, re.IGNORECASE):
logger.warning(f"Suspicious pattern detected in URL: {pattern}")
return True
return False
# Global input validator instance
_input_validator = None
def get_input_validator() -> InputValidator:
"""Get global input validator instance"""
global _input_validator
if _input_validator is None:
_input_validator = InputValidator()
return _input_validator