-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-input-validation-sanitization.py
More file actions
1417 lines (1064 loc) · 47.5 KB
/
01-input-validation-sanitization.py
File metadata and controls
1417 lines (1064 loc) · 47.5 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Implement comprehensive input validation and sanitization techniques.
Create a secure input handling system that validates and sanitizes different types
of user input to prevent security vulnerabilities.
Requirements:
1. Create validators for different data types (email, phone, URL, etc.)
2. Implement sanitization functions for HTML, SQL, and file paths
3. Create a comprehensive input validation framework
4. Demonstrate protection against common attacks (XSS, SQL injection, etc.)
5. Show proper error handling and logging
Example usage:
validator = InputValidator()
clean_email = validator.validate_email("user@example.com")
safe_html = sanitize_html("<script>alert('xss')</script>Hello")
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about what types of validation you need
# - Start with simple validation functions
# - Test your code step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - What are common input validation patterns?
# - How do you sanitize different types of content?
# - What security vulnerabilities should you prevent?
# - How do you handle validation errors gracefully?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create basic validation functions
# ===============================================================================
# Explanation:
# Input validation starts with basic checks for common data types.
# We'll create simple validators for email, phone numbers, and basic strings.
import re
import html
import urllib.parse
from typing import Optional, Union, List, Dict, Any
def validate_email(email: str) -> bool:
"""Validate email format using regex."""
if not email or not isinstance(email, str):
return False
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(email_pattern, email.strip()))
def validate_phone(phone: str) -> bool:
"""Validate phone number format."""
if not phone or not isinstance(phone, str):
return False
# Remove common separators
clean_phone = re.sub(r'[\s\-\(\)\+]', '', phone)
# Check if it's all digits and reasonable length
return clean_phone.isdigit() and 10 <= len(clean_phone) <= 15
def sanitize_string(text: str, max_length: int = 255) -> str:
"""Basic string sanitization."""
if not isinstance(text, str):
return ""
# Remove leading/trailing whitespace and limit length
sanitized = text.strip()[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32 or char in '\t\n\r')
return sanitized
# Test basic validation
print("=== Step 1: Basic Validation ===")
print(f"Valid email: {validate_email('user@example.com')}")
print(f"Invalid email: {validate_email('invalid-email')}")
print(f"Valid phone: {validate_phone('+1-555-123-4567')}")
print(f"Invalid phone: {validate_phone('abc123')}")
print(f"Sanitized string: '{sanitize_string(' Hello World! ')}'")
print()
# What we accomplished in this step:
# - Created basic validation functions for email and phone
# - Implemented string sanitization with length limits
# - Added protection against control characters
# Step 2: Add HTML sanitization and XSS protection
# ===============================================================================
# Explanation:
# HTML sanitization is crucial for preventing XSS attacks. We need to escape
# or remove dangerous HTML tags and attributes while preserving safe content.
import re
import html
import urllib.parse
from typing import Optional, Union, List, Dict, Any
def validate_email(email: str) -> bool:
"""Validate email format using regex."""
if not email or not isinstance(email, str):
return False
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(email_pattern, email.strip()))
def validate_phone(phone: str) -> bool:
"""Validate phone number format."""
if not phone or not isinstance(phone, str):
return False
# Remove common separators
clean_phone = re.sub(r'[\s\-\(\)\+]', '', phone)
# Check if it's all digits and reasonable length
return clean_phone.isdigit() and 10 <= len(clean_phone) <= 15
def sanitize_string(text: str, max_length: int = 255) -> str:
"""Basic string sanitization."""
if not isinstance(text, str):
return ""
# Remove leading/trailing whitespace and limit length
sanitized = text.strip()[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32 or char in '\t\n\r')
return sanitized
def sanitize_html(text: str, allowed_tags: Optional[List[str]] = None) -> str:
"""Sanitize HTML content to prevent XSS attacks."""
if not isinstance(text, str):
return ""
if allowed_tags is None:
allowed_tags = ['b', 'i', 'u', 'em', 'strong', 'p', 'br']
# First, escape all HTML entities
sanitized = html.escape(text)
# If we have allowed tags, selectively unescape them
if allowed_tags:
for tag in allowed_tags:
# Allow opening and closing tags
sanitized = sanitized.replace(f'<{tag}>', f'<{tag}>')
sanitized = sanitized.replace(f'</{tag}>', f'</{tag}>')
return sanitized
def remove_dangerous_patterns(text: str) -> str:
"""Remove dangerous patterns that could lead to XSS."""
if not isinstance(text, str):
return ""
# Remove javascript: URLs
text = re.sub(r'javascript\s*:', '', text, flags=re.IGNORECASE)
# Remove data: URLs (can contain scripts)
text = re.sub(r'data\s*:', '', text, flags=re.IGNORECASE)
# Remove on* event handlers
text = re.sub(r'\bon\w+\s*=', '', text, flags=re.IGNORECASE)
# Remove script tags completely
text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.IGNORECASE | re.DOTALL)
return text
def validate_url(url: str) -> bool:
"""Validate URL format and check for dangerous schemes."""
if not url or not isinstance(url, str):
return False
try:
parsed = urllib.parse.urlparse(url)
# Check for valid scheme
allowed_schemes = ['http', 'https', 'ftp', 'ftps']
if parsed.scheme.lower() not in allowed_schemes:
return False
# Must have a netloc (domain)
if not parsed.netloc:
return False
return True
except Exception:
return False
# Test HTML sanitization and XSS protection
print("=== Step 2: HTML Sanitization and XSS Protection ===")
malicious_html = "<script>alert('XSS')</script><b>Bold text</b>"
print(f"Original: {malicious_html}")
print(f"Sanitized: {sanitize_html(malicious_html)}")
dangerous_input = "javascript:alert('XSS') onclick=alert('click')"
print(f"Dangerous input: {dangerous_input}")
print(f"Cleaned: {remove_dangerous_patterns(dangerous_input)}")
print(f"Valid URL: {validate_url('https://example.com')}")
print(f"Invalid URL: {validate_url('javascript:alert(1)')}")
print()
# What we accomplished in this step:
# - Added HTML sanitization with configurable allowed tags
# - Implemented XSS protection by removing dangerous patterns
# - Created URL validation with scheme checking
# - Added protection against javascript: and data: URLs
# Step 3: Add SQL injection protection and file path sanitization
# ===============================================================================
# Explanation:
# SQL injection is prevented by proper escaping and parameterized queries.
# File path sanitization prevents directory traversal attacks.
import re
import html
import urllib.parse
import os
from typing import Optional, Union, List, Dict, Any
def validate_email(email: str) -> bool:
"""Validate email format using regex."""
if not email or not isinstance(email, str):
return False
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(email_pattern, email.strip()))
def validate_phone(phone: str) -> bool:
"""Validate phone number format."""
if not phone or not isinstance(phone, str):
return False
# Remove common separators
clean_phone = re.sub(r'[\s\-\(\)\+]', '', phone)
# Check if it's all digits and reasonable length
return clean_phone.isdigit() and 10 <= len(clean_phone) <= 15
def sanitize_string(text: str, max_length: int = 255) -> str:
"""Basic string sanitization."""
if not isinstance(text, str):
return ""
# Remove leading/trailing whitespace and limit length
sanitized = text.strip()[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32 or char in '\t\n\r')
return sanitized
def sanitize_html(text: str, allowed_tags: Optional[List[str]] = None) -> str:
"""Sanitize HTML content to prevent XSS attacks."""
if not isinstance(text, str):
return ""
if allowed_tags is None:
allowed_tags = ['b', 'i', 'u', 'em', 'strong', 'p', 'br']
# First, escape all HTML entities
sanitized = html.escape(text)
# If we have allowed tags, selectively unescape them
if allowed_tags:
for tag in allowed_tags:
# Allow opening and closing tags
sanitized = sanitized.replace(f'<{tag}>', f'<{tag}>')
sanitized = sanitized.replace(f'</{tag}>', f'</{tag}>')
return sanitized
def remove_dangerous_patterns(text: str) -> str:
"""Remove dangerous patterns that could lead to XSS."""
if not isinstance(text, str):
return ""
# Remove javascript: URLs
text = re.sub(r'javascript\s*:', '', text, flags=re.IGNORECASE)
# Remove data: URLs (can contain scripts)
text = re.sub(r'data\s*:', '', text, flags=re.IGNORECASE)
# Remove on* event handlers
text = re.sub(r'\bon\w+\s*=', '', text, flags=re.IGNORECASE)
# Remove script tags completely
text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.IGNORECASE | re.DOTALL)
return text
def validate_url(url: str) -> bool:
"""Validate URL format and check for dangerous schemes."""
if not url or not isinstance(url, str):
return False
try:
parsed = urllib.parse.urlparse(url)
# Check for valid scheme
allowed_schemes = ['http', 'https', 'ftp', 'ftps']
if parsed.scheme.lower() not in allowed_schemes:
return False
# Must have a netloc (domain)
if not parsed.netloc:
return False
return True
except Exception:
return False
def escape_sql(text: str) -> str:
"""Escape SQL special characters to prevent injection."""
if not isinstance(text, str):
return ""
# Escape single quotes by doubling them
escaped = text.replace("'", "''")
# Escape backslashes
escaped = escaped.replace("\\", "\\\\")
# Remove or escape null bytes
escaped = escaped.replace("\x00", "")
return escaped
def detect_sql_injection(text: str) -> bool:
"""Detect potential SQL injection patterns."""
if not isinstance(text, str):
return False
# Common SQL injection patterns
dangerous_patterns = [
r"(\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\b)",
r"(--|#|/\*|\*/)", # SQL comments
r"(\bor\b.*=.*=|\band\b.*=.*=)", # Boolean-based injection
r"(\bxp_cmdshell\b|\bsp_executesql\b)", # SQL Server specific
r"(\bload_file\b|\binto\s+outfile\b)", # MySQL specific
]
text_lower = text.lower()
for pattern in dangerous_patterns:
if re.search(pattern, text_lower, re.IGNORECASE):
return True
return False
def sanitize_filename(filename: str) -> str:
"""Sanitize filename to prevent directory traversal."""
if not isinstance(filename, str):
return ""
# Remove directory traversal patterns
sanitized = filename.replace("..", "").replace("/", "").replace("\\", "")
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32)
# Remove leading/trailing dots and spaces
sanitized = sanitized.strip('. ')
# Limit length
sanitized = sanitized[:255]
# Ensure it's not empty after sanitization
if not sanitized:
sanitized = "unnamed_file"
return sanitized
def validate_file_path(file_path: str, allowed_dirs: Optional[List[str]] = None) -> bool:
"""Validate file path to prevent directory traversal attacks."""
if not isinstance(file_path, str):
return False
try:
# Normalize the path
normalized = os.path.normpath(file_path)
# Check for directory traversal
if ".." in normalized or normalized.startswith("/"):
return False
# If allowed directories are specified, check against them
if allowed_dirs:
for allowed_dir in allowed_dirs:
if normalized.startswith(allowed_dir):
return True
return False
return True
except Exception:
return False
# Test SQL injection protection and file path sanitization
print("=== Step 3: SQL Injection Protection and File Path Sanitization ===")
# SQL injection tests
malicious_sql = "'; DROP TABLE users; --"
print(f"Malicious SQL: {malicious_sql}")
print(f"Escaped: {escape_sql(malicious_sql)}")
print(f"Is SQL injection: {detect_sql_injection(malicious_sql)}")
# File path tests
dangerous_filename = "../../../etc/passwd"
print(f"Dangerous filename: {dangerous_filename}")
print(f"Sanitized: {sanitize_filename(dangerous_filename)}")
print(f"Valid path: {validate_file_path('uploads/image.jpg', ['uploads/'])}")
print(f"Invalid path: {validate_file_path('../config/secrets.txt', ['uploads/'])}")
print()
# What we accomplished in this step:
# - Added SQL injection detection and prevention
# - Implemented file path sanitization against directory traversal
# - Created filename sanitization for safe file uploads
# - Added path validation with allowed directory restrictions
# Step 4: Create comprehensive input validation framework
# ===============================================================================
# Explanation:
# A validation framework provides a unified interface for all validation
# and sanitization operations with proper error handling and logging.
import re
import html
import urllib.parse
import os
import logging
from typing import Optional, Union, List, Dict, Any
from dataclasses import dataclass
from enum import Enum
# Configure logging for security events
logging.basicConfig(level=logging.INFO)
security_logger = logging.getLogger('security')
class ValidationError(Exception):
"""Custom exception for validation errors."""
pass
class SanitizationLevel(Enum):
"""Levels of sanitization strictness."""
BASIC = "basic"
STRICT = "strict"
PARANOID = "paranoid"
@dataclass
class ValidationResult:
"""Result of validation operation."""
is_valid: bool
sanitized_value: Any
errors: List[str]
warnings: List[str]
def validate_email(email: str) -> bool:
"""Validate email format using regex."""
if not email or not isinstance(email, str):
return False
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(email_pattern, email.strip()))
def validate_phone(phone: str) -> bool:
"""Validate phone number format."""
if not phone or not isinstance(phone, str):
return False
# Remove common separators
clean_phone = re.sub(r'[\s\-\(\)\+]', '', phone)
# Check if it's all digits and reasonable length
return clean_phone.isdigit() and 10 <= len(clean_phone) <= 15
def sanitize_string(text: str, max_length: int = 255) -> str:
"""Basic string sanitization."""
if not isinstance(text, str):
return ""
# Remove leading/trailing whitespace and limit length
sanitized = text.strip()[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32 or char in '\t\n\r')
return sanitized
def sanitize_html(text: str, allowed_tags: Optional[List[str]] = None) -> str:
"""Sanitize HTML content to prevent XSS attacks."""
if not isinstance(text, str):
return ""
if allowed_tags is None:
allowed_tags = ['b', 'i', 'u', 'em', 'strong', 'p', 'br']
# First, escape all HTML entities
sanitized = html.escape(text)
# If we have allowed tags, selectively unescape them
if allowed_tags:
for tag in allowed_tags:
# Allow opening and closing tags
sanitized = sanitized.replace(f'<{tag}>', f'<{tag}>')
sanitized = sanitized.replace(f'</{tag}>', f'</{tag}>')
return sanitized
def remove_dangerous_patterns(text: str) -> str:
"""Remove dangerous patterns that could lead to XSS."""
if not isinstance(text, str):
return ""
# Remove javascript: URLs
text = re.sub(r'javascript\s*:', '', text, flags=re.IGNORECASE)
# Remove data: URLs (can contain scripts)
text = re.sub(r'data\s*:', '', text, flags=re.IGNORECASE)
# Remove on* event handlers
text = re.sub(r'\bon\w+\s*=', '', text, flags=re.IGNORECASE)
# Remove script tags completely
text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.IGNORECASE | re.DOTALL)
return text
def validate_url(url: str) -> bool:
"""Validate URL format and check for dangerous schemes."""
if not url or not isinstance(url, str):
return False
try:
parsed = urllib.parse.urlparse(url)
# Check for valid scheme
allowed_schemes = ['http', 'https', 'ftp', 'ftps']
if parsed.scheme.lower() not in allowed_schemes:
return False
# Must have a netloc (domain)
if not parsed.netloc:
return False
return True
except Exception:
return False
def escape_sql(text: str) -> str:
"""Escape SQL special characters to prevent injection."""
if not isinstance(text, str):
return ""
# Escape single quotes by doubling them
escaped = text.replace("'", "''")
# Escape backslashes
escaped = escaped.replace("\\", "\\\\")
# Remove or escape null bytes
escaped = escaped.replace("\x00", "")
return escaped
def detect_sql_injection(text: str) -> bool:
"""Detect potential SQL injection patterns."""
if not isinstance(text, str):
return False
# Common SQL injection patterns
dangerous_patterns = [
r"(\b(union|select|insert|update|delete|drop|create|alter|exec|execute)\b)",
r"(--|#|/\*|\*/)", # SQL comments
r"(\bor\b.*=.*=|\band\b.*=.*=)", # Boolean-based injection
r"(\bxp_cmdshell\b|\bsp_executesql\b)", # SQL Server specific
r"(\bload_file\b|\binto\s+outfile\b)", # MySQL specific
]
text_lower = text.lower()
for pattern in dangerous_patterns:
if re.search(pattern, text_lower, re.IGNORECASE):
return True
return False
def sanitize_filename(filename: str) -> str:
"""Sanitize filename to prevent directory traversal."""
if not isinstance(filename, str):
return ""
# Remove directory traversal patterns
sanitized = filename.replace("..", "").replace("/", "").replace("\\", "")
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32)
# Remove leading/trailing dots and spaces
sanitized = sanitized.strip('. ')
# Limit length
sanitized = sanitized[:255]
# Ensure it's not empty after sanitization
if not sanitized:
sanitized = "unnamed_file"
return sanitized
def validate_file_path(file_path: str, allowed_dirs: Optional[List[str]] = None) -> bool:
"""Validate file path to prevent directory traversal attacks."""
if not isinstance(file_path, str):
return False
try:
# Normalize the path
normalized = os.path.normpath(file_path)
# Check for directory traversal
if ".." in normalized or normalized.startswith("/"):
return False
# If allowed directories are specified, check against them
if allowed_dirs:
for allowed_dir in allowed_dirs:
if normalized.startswith(allowed_dir):
return True
return False
return True
except Exception:
return False
class InputValidator:
"""Comprehensive input validation and sanitization framework."""
def __init__(self, sanitization_level: SanitizationLevel = SanitizationLevel.STRICT):
self.sanitization_level = sanitization_level
self.logger = security_logger
def validate_and_sanitize(self, value: Any, data_type: str, **kwargs) -> ValidationResult:
"""Main validation and sanitization method."""
errors = []
warnings = []
sanitized_value = value
try:
if data_type == "email":
sanitized_value = self._process_email(value, errors, warnings)
elif data_type == "phone":
sanitized_value = self._process_phone(value, errors, warnings)
elif data_type == "url":
sanitized_value = self._process_url(value, errors, warnings)
elif data_type == "html":
sanitized_value = self._process_html(value, errors, warnings, **kwargs)
elif data_type == "sql":
sanitized_value = self._process_sql(value, errors, warnings)
elif data_type == "filename":
sanitized_value = self._process_filename(value, errors, warnings)
elif data_type == "filepath":
sanitized_value = self._process_filepath(value, errors, warnings, **kwargs)
else:
sanitized_value = self._process_string(value, errors, warnings, **kwargs)
is_valid = len(errors) == 0
# Log security events
if errors:
self.logger.warning(f"Validation failed for {data_type}: {errors}")
if warnings:
self.logger.info(f"Validation warnings for {data_type}: {warnings}")
return ValidationResult(is_valid, sanitized_value, errors, warnings)
except Exception as e:
errors.append(f"Validation error: {str(e)}")
self.logger.error(f"Validation exception for {data_type}: {str(e)}")
return ValidationResult(False, value, errors, warnings)
def _process_email(self, value: str, errors: List[str], warnings: List[str]) -> str:
"""Process email validation."""
if not validate_email(value):
errors.append("Invalid email format")
return ""
return sanitize_string(value, 254) # RFC 5321 limit
def _process_phone(self, value: str, errors: List[str], warnings: List[str]) -> str:
"""Process phone validation."""
if not validate_phone(value):
errors.append("Invalid phone number format")
return ""
return re.sub(r'[\s\-\(\)\+]', '', value)
def _process_url(self, value: str, errors: List[str], warnings: List[str]) -> str:
"""Process URL validation."""
if not validate_url(value):
errors.append("Invalid or dangerous URL")
return ""
return sanitize_string(value, 2048)
def _process_html(self, value: str, errors: List[str], warnings: List[str], **kwargs) -> str:
"""Process HTML sanitization."""
allowed_tags = kwargs.get('allowed_tags', ['b', 'i', 'u', 'em', 'strong'])
if self.sanitization_level == SanitizationLevel.PARANOID:
# Strip all HTML
return html.escape(value)
elif self.sanitization_level == SanitizationLevel.STRICT:
# Remove dangerous patterns first
cleaned = remove_dangerous_patterns(value)
return sanitize_html(cleaned, allowed_tags)
else:
# Basic sanitization
return sanitize_html(value, allowed_tags)
def _process_sql(self, value: str, errors: List[str], warnings: List[str]) -> str:
"""Process SQL input."""
if detect_sql_injection(value):
errors.append("Potential SQL injection detected")
warnings.append("Input contains SQL-like patterns")
return escape_sql(value)
def _process_filename(self, value: str, errors: List[str], warnings: List[str]) -> str:
"""Process filename sanitization."""
original = value
sanitized = sanitize_filename(value)
if original != sanitized:
warnings.append("Filename was modified during sanitization")
return sanitized
def _process_filepath(self, value: str, errors: List[str], warnings: List[str], **kwargs) -> str:
"""Process file path validation."""
allowed_dirs = kwargs.get('allowed_dirs', [])
if not validate_file_path(value, allowed_dirs):
errors.append("Invalid or dangerous file path")
return ""
return sanitize_string(value)
def _process_string(self, value: str, errors: List[str], warnings: List[str], **kwargs) -> str:
"""Process general string sanitization."""
max_length = kwargs.get('max_length', 255)
return sanitize_string(value, max_length)
# Test the comprehensive validation framework
print("=== Step 4: Comprehensive Input Validation Framework ===")
validator = InputValidator(SanitizationLevel.STRICT)
# Test various input types
test_cases = [
("user@example.com", "email"),
("invalid-email", "email"),
("<script>alert('xss')</script><b>Bold</b>", "html"),
("'; DROP TABLE users; --", "sql"),
("../../../etc/passwd", "filename"),
]
for test_input, data_type in test_cases:
result = validator.validate_and_sanitize(test_input, data_type)
print(f"Input: {test_input}")
print(f"Type: {data_type}")
print(f"Valid: {result.is_valid}")
print(f"Sanitized: {result.sanitized_value}")
if result.errors:
print(f"Errors: {result.errors}")
if result.warnings:
print(f"Warnings: {result.warnings}")
print("-" * 50)
# What we accomplished in this step:
# - Created a comprehensive validation framework with unified interface
# - Added proper error handling and logging
# - Implemented different sanitization levels
# - Created structured validation results with errors and warnings
# Step 5: Add advanced security features and complete testing
# ===============================================================================
# Explanation:
# Advanced security includes rate limiting, input length validation,
# encoding detection, and comprehensive testing of all security features.
import re
import html
import urllib.parse
import os
import logging
import time
import hashlib
from typing import Optional, Union, List, Dict, Any
from dataclasses import dataclass
from enum import Enum
from collections import defaultdict
# Configure logging for security events
logging.basicConfig(level=logging.INFO)
security_logger = logging.getLogger('security')
class ValidationError(Exception):
"""Custom exception for validation errors."""
pass
class SanitizationLevel(Enum):
"""Levels of sanitization strictness."""
BASIC = "basic"
STRICT = "strict"
PARANOID = "paranoid"
@dataclass
class ValidationResult:
"""Result of validation operation."""
is_valid: bool
sanitized_value: Any
errors: List[str]
warnings: List[str]
class RateLimiter:
"""Simple rate limiter for validation requests."""
def __init__(self, max_requests: int = 100, time_window: int = 60):
self.max_requests = max_requests
self.time_window = time_window
self.requests = defaultdict(list)
def is_allowed(self, identifier: str) -> bool:
"""Check if request is allowed based on rate limit."""
now = time.time()
# Clean old requests
self.requests[identifier] = [
req_time for req_time in self.requests[identifier]
if now - req_time < self.time_window
]
# Check if under limit
if len(self.requests[identifier]) >= self.max_requests:
return False
# Add current request
self.requests[identifier].append(now)
return True
def validate_email(email: str) -> bool:
"""Validate email format using regex."""
if not email or not isinstance(email, str):
return False
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(email_pattern, email.strip()))
def validate_phone(phone: str) -> bool:
"""Validate phone number format."""
if not phone or not isinstance(phone, str):
return False
# Remove common separators
clean_phone = re.sub(r'[\s\-\(\)\+]', '', phone)
# Check if it's all digits and reasonable length
return clean_phone.isdigit() and 10 <= len(clean_phone) <= 15
def sanitize_string(text: str, max_length: int = 255) -> str:
"""Basic string sanitization."""
if not isinstance(text, str):
return ""
# Remove leading/trailing whitespace and limit length
sanitized = text.strip()[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in sanitized if ord(char) >= 32 or char in '\t\n\r')
return sanitized
def sanitize_html(text: str, allowed_tags: Optional[List[str]] = None) -> str:
"""Sanitize HTML content to prevent XSS attacks."""
if not isinstance(text, str):
return ""
if allowed_tags is None:
allowed_tags = ['b', 'i', 'u', 'em', 'strong', 'p', 'br']
# First, escape all HTML entities
sanitized = html.escape(text)
# If we have allowed tags, selectively unescape them
if allowed_tags:
for tag in allowed_tags:
# Allow opening and closing tags
sanitized = sanitized.replace(f'<{tag}>', f'<{tag}>')
sanitized = sanitized.replace(f'</{tag}>', f'</{tag}>')
return sanitized
def remove_dangerous_patterns(text: str) -> str:
"""Remove dangerous patterns that could lead to XSS."""
if not isinstance(text, str):
return ""
# Remove javascript: URLs
text = re.sub(r'javascript\s*:', '', text, flags=re.IGNORECASE)
# Remove data: URLs (can contain scripts)
text = re.sub(r'data\s*:', '', text, flags=re.IGNORECASE)
# Remove on* event handlers
text = re.sub(r'\bon\w+\s*=', '', text, flags=re.IGNORECASE)