-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10-code-injection-prevention.py
More file actions
1617 lines (1249 loc) · 58 KB
/
10-code-injection-prevention.py
File metadata and controls
1617 lines (1249 loc) · 58 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 code injection prevention techniques.
Create a secure code execution system that prevents various types of code injection attacks
including command injection, SQL injection, and eval injection.
Requirements:
1. Create a secure command executor that validates input
2. Create a secure SQL query builder with parameterized queries
3. Create a secure expression evaluator that prevents eval injection
4. Create input validation and sanitization utilities
5. Demonstrate safe and unsafe practices with examples
Example usage:
executor = SecureCommandExecutor()
result = executor.execute_command("ls", ["-la", "/home"])
query_builder = SecureQueryBuilder()
query = query_builder.select("users").where("id", user_id).build()
"""
# 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 classes and methods you need
# - Start with a simple implementation
# - 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 the different types of code injection attacks?
# - How can you validate and sanitize user input?
# - What makes command execution safe vs unsafe?
# - How do parameterized queries prevent SQL injection?
# - What are safe alternatives to eval()?
#
# 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 security utilities
# ===============================================================================
# Explanation:
# Code injection prevention starts with proper input validation and sanitization.
# We'll create utilities to validate different types of input safely.
import re
import subprocess
import shlex
import sqlite3
import ast
import operator
from typing import List, Dict, Any, Optional, Union
from pathlib import Path
class SecurityError(Exception):
"""Custom exception for security-related errors."""
pass
class InputValidator:
"""Utility class for validating and sanitizing user input."""
# Safe characters for different contexts
SAFE_FILENAME_CHARS = re.compile(r'^[a-zA-Z0-9._-]+$')
SAFE_COMMAND_CHARS = re.compile(r'^[a-zA-Z0-9._/-]+$')
SAFE_SQL_IDENTIFIER = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
@staticmethod
def validate_filename(filename: str) -> bool:
"""Validate that filename contains only safe characters."""
if not filename or len(filename) > 255:
return False
return bool(InputValidator.SAFE_FILENAME_CHARS.match(filename))
@staticmethod
def validate_command_name(command: str) -> bool:
"""Validate that command name is safe."""
if not command or len(command) > 100:
return False
return bool(InputValidator.SAFE_COMMAND_CHARS.match(command))
@staticmethod
def validate_sql_identifier(identifier: str) -> bool:
"""Validate SQL identifier (table/column name)."""
if not identifier or len(identifier) > 64:
return False
return bool(InputValidator.SAFE_SQL_IDENTIFIER.match(identifier))
@staticmethod
def sanitize_string(input_str: str, max_length: int = 1000) -> str:
"""Sanitize string input by removing dangerous characters."""
if not isinstance(input_str, str):
raise SecurityError("Input must be a string")
# Truncate if too long
if len(input_str) > max_length:
input_str = input_str[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in input_str if ord(char) >= 32 or char in '\t\n\r')
return sanitized
# What we accomplished in this step:
# - Created custom security exception
# - Created input validator with regex patterns for safe characters
# - Added validation methods for filenames, commands, and SQL identifiers
# - Added string sanitization to remove dangerous characters
# Step 2: Create secure command executor
# ===============================================================================
# Explanation:
# Command injection occurs when user input is passed directly to system commands.
# We'll create a secure executor that validates commands and uses safe execution methods.
import re
import subprocess
import shlex
import sqlite3
import ast
import operator
from typing import List, Dict, Any, Optional, Union
from pathlib import Path
class SecurityError(Exception):
"""Custom exception for security-related errors."""
pass
class InputValidator:
"""Utility class for validating and sanitizing user input."""
# Safe characters for different contexts
SAFE_FILENAME_CHARS = re.compile(r'^[a-zA-Z0-9._-]+$')
SAFE_COMMAND_CHARS = re.compile(r'^[a-zA-Z0-9._/-]+$')
SAFE_SQL_IDENTIFIER = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
@staticmethod
def validate_filename(filename: str) -> bool:
"""Validate that filename contains only safe characters."""
if not filename or len(filename) > 255:
return False
return bool(InputValidator.SAFE_FILENAME_CHARS.match(filename))
@staticmethod
def validate_command_name(command: str) -> bool:
"""Validate that command name is safe."""
if not command or len(command) > 100:
return False
return bool(InputValidator.SAFE_COMMAND_CHARS.match(command))
@staticmethod
def validate_sql_identifier(identifier: str) -> bool:
"""Validate SQL identifier (table/column name)."""
if not identifier or len(identifier) > 64:
return False
return bool(InputValidator.SAFE_SQL_IDENTIFIER.match(identifier))
@staticmethod
def sanitize_string(input_str: str, max_length: int = 1000) -> str:
"""Sanitize string input by removing dangerous characters."""
if not isinstance(input_str, str):
raise SecurityError("Input must be a string")
# Truncate if too long
if len(input_str) > max_length:
input_str = input_str[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in input_str if ord(char) >= 32 or char in '\t\n\r')
return sanitized
class SecureCommandExecutor:
"""Secure command executor that prevents command injection."""
# Whitelist of allowed commands
ALLOWED_COMMANDS = {
'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc', 'sort', 'uniq',
'date', 'whoami', 'pwd', 'echo', 'mkdir', 'rmdir', 'cp', 'mv'
}
# Dangerous characters that should never appear in arguments
DANGEROUS_CHARS = {'&', '|', ';', '`', '$', '(', ')', '<', '>', '\n', '\r'}
def __init__(self, allowed_commands: Optional[set] = None):
"""Initialize with optional custom command whitelist."""
self.allowed_commands = allowed_commands or self.ALLOWED_COMMANDS.copy()
def validate_command(self, command: str) -> bool:
"""Validate that command is in whitelist and safe."""
if not InputValidator.validate_command_name(command):
return False
# Check if command is in whitelist
command_base = Path(command).name # Get just the command name, not full path
return command_base in self.allowed_commands
def validate_arguments(self, args: List[str]) -> bool:
"""Validate command arguments for dangerous characters."""
for arg in args:
if not isinstance(arg, str):
return False
# Check for dangerous characters
if any(char in arg for char in self.DANGEROUS_CHARS):
return False
# Check length
if len(arg) > 1000:
return False
return True
def execute_command(self, command: str, args: List[str] = None,
timeout: int = 30) -> Dict[str, Any]:
"""Safely execute a command with validation."""
args = args or []
# Validate command
if not self.validate_command(command):
raise SecurityError(f"Command '{command}' is not allowed")
# Validate arguments
if not self.validate_arguments(args):
raise SecurityError("Invalid or dangerous arguments detected")
try:
# Use subprocess with shell=False to prevent shell injection
cmd_list = [command] + args
result = subprocess.run(
cmd_list,
capture_output=True,
text=True,
timeout=timeout,
shell=False # Critical: never use shell=True with user input
)
return {
'success': True,
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode
}
except subprocess.TimeoutExpired:
raise SecurityError(f"Command timed out after {timeout} seconds")
except subprocess.CalledProcessError as e:
return {
'success': False,
'stdout': e.stdout,
'stderr': e.stderr,
'returncode': e.returncode
}
except Exception as e:
raise SecurityError(f"Command execution failed: {str(e)}")
# What we accomplished in this step:
# - Created secure command executor with command whitelist
# - Added validation for commands and arguments
# - Used subprocess with shell=False to prevent injection
# - Added timeout protection and proper error handling
# Step 3: Create secure SQL query builder
# ===============================================================================
# Explanation:
# SQL injection occurs when user input is concatenated directly into SQL queries.
# We'll create a query builder that uses parameterized queries to prevent injection.
import re
import subprocess
import shlex
import sqlite3
import ast
import operator
from typing import List, Dict, Any, Optional, Union
from pathlib import Path
class SecurityError(Exception):
"""Custom exception for security-related errors."""
pass
class InputValidator:
"""Utility class for validating and sanitizing user input."""
# Safe characters for different contexts
SAFE_FILENAME_CHARS = re.compile(r'^[a-zA-Z0-9._-]+$')
SAFE_COMMAND_CHARS = re.compile(r'^[a-zA-Z0-9._/-]+$')
SAFE_SQL_IDENTIFIER = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
@staticmethod
def validate_filename(filename: str) -> bool:
"""Validate that filename contains only safe characters."""
if not filename or len(filename) > 255:
return False
return bool(InputValidator.SAFE_FILENAME_CHARS.match(filename))
@staticmethod
def validate_command_name(command: str) -> bool:
"""Validate that command name is safe."""
if not command or len(command) > 100:
return False
return bool(InputValidator.SAFE_COMMAND_CHARS.match(command))
@staticmethod
def validate_sql_identifier(identifier: str) -> bool:
"""Validate SQL identifier (table/column name)."""
if not identifier or len(identifier) > 64:
return False
return bool(InputValidator.SAFE_SQL_IDENTIFIER.match(identifier))
@staticmethod
def sanitize_string(input_str: str, max_length: int = 1000) -> str:
"""Sanitize string input by removing dangerous characters."""
if not isinstance(input_str, str):
raise SecurityError("Input must be a string")
# Truncate if too long
if len(input_str) > max_length:
input_str = input_str[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in input_str if ord(char) >= 32 or char in '\t\n\r')
return sanitized
class SecureCommandExecutor:
"""Secure command executor that prevents command injection."""
# Whitelist of allowed commands
ALLOWED_COMMANDS = {
'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc', 'sort', 'uniq',
'date', 'whoami', 'pwd', 'echo', 'mkdir', 'rmdir', 'cp', 'mv'
}
# Dangerous characters that should never appear in arguments
DANGEROUS_CHARS = {'&', '|', ';', '`', '$', '(', ')', '<', '>', '\n', '\r'}
def __init__(self, allowed_commands: Optional[set] = None):
"""Initialize with optional custom command whitelist."""
self.allowed_commands = allowed_commands or self.ALLOWED_COMMANDS.copy()
def validate_command(self, command: str) -> bool:
"""Validate that command is in whitelist and safe."""
if not InputValidator.validate_command_name(command):
return False
# Check if command is in whitelist
command_base = Path(command).name # Get just the command name, not full path
return command_base in self.allowed_commands
def validate_arguments(self, args: List[str]) -> bool:
"""Validate command arguments for dangerous characters."""
for arg in args:
if not isinstance(arg, str):
return False
# Check for dangerous characters
if any(char in arg for char in self.DANGEROUS_CHARS):
return False
# Check length
if len(arg) > 1000:
return False
return True
def execute_command(self, command: str, args: List[str] = None,
timeout: int = 30) -> Dict[str, Any]:
"""Safely execute a command with validation."""
args = args or []
# Validate command
if not self.validate_command(command):
raise SecurityError(f"Command '{command}' is not allowed")
# Validate arguments
if not self.validate_arguments(args):
raise SecurityError("Invalid or dangerous arguments detected")
try:
# Use subprocess with shell=False to prevent shell injection
cmd_list = [command] + args
result = subprocess.run(
cmd_list,
capture_output=True,
text=True,
timeout=timeout,
shell=False # Critical: never use shell=True with user input
)
return {
'success': True,
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode
}
except subprocess.TimeoutExpired:
raise SecurityError(f"Command timed out after {timeout} seconds")
except subprocess.CalledProcessError as e:
return {
'success': False,
'stdout': e.stdout,
'stderr': e.stderr,
'returncode': e.returncode
}
except Exception as e:
raise SecurityError(f"Command execution failed: {str(e)}")
class SecureQueryBuilder:
"""Secure SQL query builder that prevents SQL injection."""
def __init__(self):
"""Initialize query builder."""
self.reset()
def reset(self):
"""Reset the query builder for a new query."""
self._select_fields = []
self._from_table = None
self._where_conditions = []
self._where_params = []
self._order_by = []
self._limit_value = None
self._offset_value = None
def select(self, *fields: str) -> 'SecureQueryBuilder':
"""Add SELECT fields with validation."""
for field in fields:
if field == '*':
self._select_fields.append('*')
elif InputValidator.validate_sql_identifier(field):
self._select_fields.append(field)
else:
raise SecurityError(f"Invalid field name: {field}")
return self
def from_table(self, table: str) -> 'SecureQueryBuilder':
"""Set FROM table with validation."""
if not InputValidator.validate_sql_identifier(table):
raise SecurityError(f"Invalid table name: {table}")
self._from_table = table
return self
def where(self, column: str, value: Any, operator: str = '=') -> 'SecureQueryBuilder':
"""Add WHERE condition with parameterized values."""
# Validate column name
if not InputValidator.validate_sql_identifier(column):
raise SecurityError(f"Invalid column name: {column}")
# Validate operator
allowed_operators = {'=', '!=', '<', '>', '<=', '>=', 'LIKE', 'IN'}
if operator.upper() not in allowed_operators:
raise SecurityError(f"Invalid operator: {operator}")
# Add parameterized condition
self._where_conditions.append(f"{column} {operator} ?")
self._where_params.append(value)
return self
def where_in(self, column: str, values: List[Any]) -> 'SecureQueryBuilder':
"""Add WHERE IN condition with parameterized values."""
if not InputValidator.validate_sql_identifier(column):
raise SecurityError(f"Invalid column name: {column}")
if not values:
raise SecurityError("WHERE IN requires at least one value")
placeholders = ','.join(['?'] * len(values))
self._where_conditions.append(f"{column} IN ({placeholders})")
self._where_params.extend(values)
return self
def order_by(self, column: str, direction: str = 'ASC') -> 'SecureQueryBuilder':
"""Add ORDER BY clause with validation."""
if not InputValidator.validate_sql_identifier(column):
raise SecurityError(f"Invalid column name: {column}")
if direction.upper() not in ['ASC', 'DESC']:
raise SecurityError(f"Invalid sort direction: {direction}")
self._order_by.append(f"{column} {direction.upper()}")
return self
def limit(self, count: int, offset: int = 0) -> 'SecureQueryBuilder':
"""Add LIMIT clause with validation."""
if not isinstance(count, int) or count < 0:
raise SecurityError("LIMIT count must be a non-negative integer")
if not isinstance(offset, int) or offset < 0:
raise SecurityError("OFFSET must be a non-negative integer")
self._limit_value = count
self._offset_value = offset
return self
def build(self) -> tuple[str, List[Any]]:
"""Build the final SQL query with parameters."""
if not self._select_fields:
raise SecurityError("SELECT fields are required")
if not self._from_table:
raise SecurityError("FROM table is required")
# Build SELECT clause
fields_str = ', '.join(self._select_fields)
query = f"SELECT {fields_str} FROM {self._from_table}"
# Build WHERE clause
if self._where_conditions:
where_str = ' AND '.join(self._where_conditions)
query += f" WHERE {where_str}"
# Build ORDER BY clause
if self._order_by:
order_str = ', '.join(self._order_by)
query += f" ORDER BY {order_str}"
# Build LIMIT clause
if self._limit_value is not None:
query += f" LIMIT {self._limit_value}"
if self._offset_value:
query += f" OFFSET {self._offset_value}"
return query, self._where_params.copy()
# What we accomplished in this step:
# - Created secure SQL query builder with parameterized queries
# - Added validation for table names, column names, and operators
# - Used parameter placeholders (?) to prevent SQL injection
# - Added support for common SQL operations (SELECT, WHERE, ORDER BY, LIMIT)
# Step 4: Create secure expression evaluator
# ===============================================================================
# Explanation:
# Using eval() with user input is extremely dangerous as it can execute arbitrary code.
# We'll create a safe expression evaluator using AST parsing with restricted operations.
import re
import subprocess
import shlex
import sqlite3
import ast
import operator
from typing import List, Dict, Any, Optional, Union
from pathlib import Path
class SecurityError(Exception):
"""Custom exception for security-related errors."""
pass
class InputValidator:
"""Utility class for validating and sanitizing user input."""
# Safe characters for different contexts
SAFE_FILENAME_CHARS = re.compile(r'^[a-zA-Z0-9._-]+$')
SAFE_COMMAND_CHARS = re.compile(r'^[a-zA-Z0-9._/-]+$')
SAFE_SQL_IDENTIFIER = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
@staticmethod
def validate_filename(filename: str) -> bool:
"""Validate that filename contains only safe characters."""
if not filename or len(filename) > 255:
return False
return bool(InputValidator.SAFE_FILENAME_CHARS.match(filename))
@staticmethod
def validate_command_name(command: str) -> bool:
"""Validate that command name is safe."""
if not command or len(command) > 100:
return False
return bool(InputValidator.SAFE_COMMAND_CHARS.match(command))
@staticmethod
def validate_sql_identifier(identifier: str) -> bool:
"""Validate SQL identifier (table/column name)."""
if not identifier or len(identifier) > 64:
return False
return bool(InputValidator.SAFE_SQL_IDENTIFIER.match(identifier))
@staticmethod
def sanitize_string(input_str: str, max_length: int = 1000) -> str:
"""Sanitize string input by removing dangerous characters."""
if not isinstance(input_str, str):
raise SecurityError("Input must be a string")
# Truncate if too long
if len(input_str) > max_length:
input_str = input_str[:max_length]
# Remove null bytes and control characters
sanitized = ''.join(char for char in input_str if ord(char) >= 32 or char in '\t\n\r')
return sanitized
class SecureCommandExecutor:
"""Secure command executor that prevents command injection."""
# Whitelist of allowed commands
ALLOWED_COMMANDS = {
'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc', 'sort', 'uniq',
'date', 'whoami', 'pwd', 'echo', 'mkdir', 'rmdir', 'cp', 'mv'
}
# Dangerous characters that should never appear in arguments
DANGEROUS_CHARS = {'&', '|', ';', '`', '$', '(', ')', '<', '>', '\n', '\r'}
def __init__(self, allowed_commands: Optional[set] = None):
"""Initialize with optional custom command whitelist."""
self.allowed_commands = allowed_commands or self.ALLOWED_COMMANDS.copy()
def validate_command(self, command: str) -> bool:
"""Validate that command is in whitelist and safe."""
if not InputValidator.validate_command_name(command):
return False
# Check if command is in whitelist
command_base = Path(command).name # Get just the command name, not full path
return command_base in self.allowed_commands
def validate_arguments(self, args: List[str]) -> bool:
"""Validate command arguments for dangerous characters."""
for arg in args:
if not isinstance(arg, str):
return False
# Check for dangerous characters
if any(char in arg for char in self.DANGEROUS_CHARS):
return False
# Check length
if len(arg) > 1000:
return False
return True
def execute_command(self, command: str, args: List[str] = None,
timeout: int = 30) -> Dict[str, Any]:
"""Safely execute a command with validation."""
args = args or []
# Validate command
if not self.validate_command(command):
raise SecurityError(f"Command '{command}' is not allowed")
# Validate arguments
if not self.validate_arguments(args):
raise SecurityError("Invalid or dangerous arguments detected")
try:
# Use subprocess with shell=False to prevent shell injection
cmd_list = [command] + args
result = subprocess.run(
cmd_list,
capture_output=True,
text=True,
timeout=timeout,
shell=False # Critical: never use shell=True with user input
)
return {
'success': True,
'stdout': result.stdout,
'stderr': result.stderr,
'returncode': result.returncode
}
except subprocess.TimeoutExpired:
raise SecurityError(f"Command timed out after {timeout} seconds")
except subprocess.CalledProcessError as e:
return {
'success': False,
'stdout': e.stdout,
'stderr': e.stderr,
'returncode': e.returncode
}
except Exception as e:
raise SecurityError(f"Command execution failed: {str(e)}")
class SecureQueryBuilder:
"""Secure SQL query builder that prevents SQL injection."""
def __init__(self):
"""Initialize query builder."""
self.reset()
def reset(self):
"""Reset the query builder for a new query."""
self._select_fields = []
self._from_table = None
self._where_conditions = []
self._where_params = []
self._order_by = []
self._limit_value = None
self._offset_value = None
def select(self, *fields: str) -> 'SecureQueryBuilder':
"""Add SELECT fields with validation."""
for field in fields:
if field == '*':
self._select_fields.append('*')
elif InputValidator.validate_sql_identifier(field):
self._select_fields.append(field)
else:
raise SecurityError(f"Invalid field name: {field}")
return self
def from_table(self, table: str) -> 'SecureQueryBuilder':
"""Set FROM table with validation."""
if not InputValidator.validate_sql_identifier(table):
raise SecurityError(f"Invalid table name: {table}")
self._from_table = table
return self
def where(self, column: str, value: Any, operator: str = '=') -> 'SecureQueryBuilder':
"""Add WHERE condition with parameterized values."""
# Validate column name
if not InputValidator.validate_sql_identifier(column):
raise SecurityError(f"Invalid column name: {column}")
# Validate operator
allowed_operators = {'=', '!=', '<', '>', '<=', '>=', 'LIKE', 'IN'}
if operator.upper() not in allowed_operators:
raise SecurityError(f"Invalid operator: {operator}")
# Add parameterized condition
self._where_conditions.append(f"{column} {operator} ?")
self._where_params.append(value)
return self
def where_in(self, column: str, values: List[Any]) -> 'SecureQueryBuilder':
"""Add WHERE IN condition with parameterized values."""
if not InputValidator.validate_sql_identifier(column):
raise SecurityError(f"Invalid column name: {column}")
if not values:
raise SecurityError("WHERE IN requires at least one value")
placeholders = ','.join(['?'] * len(values))
self._where_conditions.append(f"{column} IN ({placeholders})")
self._where_params.extend(values)
return self
def order_by(self, column: str, direction: str = 'ASC') -> 'SecureQueryBuilder':
"""Add ORDER BY clause with validation."""
if not InputValidator.validate_sql_identifier(column):
raise SecurityError(f"Invalid column name: {column}")
if direction.upper() not in ['ASC', 'DESC']:
raise SecurityError(f"Invalid sort direction: {direction}")
self._order_by.append(f"{column} {direction.upper()}")
return self
def limit(self, count: int, offset: int = 0) -> 'SecureQueryBuilder':
"""Add LIMIT clause with validation."""
if not isinstance(count, int) or count < 0:
raise SecurityError("LIMIT count must be a non-negative integer")
if not isinstance(offset, int) or offset < 0:
raise SecurityError("OFFSET must be a non-negative integer")
self._limit_value = count
self._offset_value = offset
return self
def build(self) -> tuple[str, List[Any]]:
"""Build the final SQL query with parameters."""
if not self._select_fields:
raise SecurityError("SELECT fields are required")
if not self._from_table:
raise SecurityError("FROM table is required")
# Build SELECT clause
fields_str = ', '.join(self._select_fields)
query = f"SELECT {fields_str} FROM {self._from_table}"
# Build WHERE clause
if self._where_conditions:
where_str = ' AND '.join(self._where_conditions)
query += f" WHERE {where_str}"
# Build ORDER BY clause
if self._order_by:
order_str = ', '.join(self._order_by)
query += f" ORDER BY {order_str}"
# Build LIMIT clause
if self._limit_value is not None:
query += f" LIMIT {self._limit_value}"
if self._offset_value:
query += f" OFFSET {self._offset_value}"
return query, self._where_params.copy()
class SecureExpressionEvaluator:
"""Secure expression evaluator that prevents code injection via eval()."""
# Allowed operators for mathematical expressions
ALLOWED_OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
# Allowed comparison operators
ALLOWED_COMPARISONS = {
ast.Eq: operator.eq,
ast.NotEq: operator.ne,
ast.Lt: operator.lt,
ast.LtE: operator.le,
ast.Gt: operator.gt,
ast.GtE: operator.ge,
}
# Allowed boolean operators
ALLOWED_BOOLEAN = {
ast.And: lambda x, y: x and y,
ast.Or: lambda x, y: x or y,
ast.Not: lambda x: not x,
}
def __init__(self, allowed_names: Optional[Dict[str, Any]] = None):
"""Initialize with optional allowed variable names."""
self.allowed_names = allowed_names or {}
def _validate_node(self, node: ast.AST) -> bool:
"""Validate that AST node contains only safe operations."""
if isinstance(node, ast.Expression):
return self._validate_node(node.body)
elif isinstance(node, ast.Constant):
# Allow constants (numbers, strings, booleans)
return isinstance(node.value, (int, float, str, bool, type(None)))
elif isinstance(node, ast.Name):
# Only allow whitelisted variable names
return node.id in self.allowed_names
elif isinstance(node, ast.BinOp):
# Allow binary operations with safe operators
return (type(node.op) in self.ALLOWED_OPERATORS and
self._validate_node(node.left) and
self._validate_node(node.right))
elif isinstance(node, ast.UnaryOp):
# Allow unary operations with safe operators
return (type(node.op) in self.ALLOWED_OPERATORS and
self._validate_node(node.operand))
elif isinstance(node, ast.Compare):
# Allow comparisons with safe operators
return (all(type(op) in self.ALLOWED_COMPARISONS for op in node.ops) and
self._validate_node(node.left) and
all(self._validate_node(comp) for comp in node.comparators))
elif isinstance(node, ast.BoolOp):
# Allow boolean operations
return (type(node.op) in self.ALLOWED_BOOLEAN and
all(self._validate_node(value) for value in node.values))
else:
# Reject all other node types (function calls, imports, etc.)
return False
def _evaluate_node(self, node: ast.AST) -> Any:
"""Safely evaluate an AST node."""
if isinstance(node, ast.Expression):
return self._evaluate_node(node.body)
elif isinstance(node, ast.Constant):
return node.value
elif isinstance(node, ast.Name):
return self.allowed_names[node.id]
elif isinstance(node, ast.BinOp):
left = self._evaluate_node(node.left)
right = self._evaluate_node(node.right)
op_func = self.ALLOWED_OPERATORS[type(node.op)]
return op_func(left, right)
elif isinstance(node, ast.UnaryOp):
operand = self._evaluate_node(node.operand)
op_func = self.ALLOWED_OPERATORS[type(node.op)]
return op_func(operand)
elif isinstance(node, ast.Compare):
left = self._evaluate_node(node.left)
result = True
for op, comparator in zip(node.ops, node.comparators):
right = self._evaluate_node(comparator)
op_func = self.ALLOWED_COMPARISONS[type(op)]
result = result and op_func(left, right)
left = right # For chained comparisons
return result
elif isinstance(node, ast.BoolOp):
op_func = self.ALLOWED_BOOLEAN[type(node.op)]
values = [self._evaluate_node(value) for value in node.values]
if isinstance(node.op, ast.And):
return all(values)
elif isinstance(node.op, ast.Or):
return any(values)
else:
raise SecurityError(f"Unsupported node type: {type(node)}")