Repository navigation
Expand file tree
/
Copy pathtest_poc_vulnerability.py
More file actions
1080 lines (819 loc) · 42 KB
/
Copy pathtest_poc_vulnerability.py
File metadata and controls
1080 lines (819 loc) · 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
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
"""
Test suite for CodeSafe security vulnerabilities.
Tests the fix for the sandbox escape vulnerability and other potential attack vectors.
"""
import unittest
import time
from pathlib import Path
from multiprocessing import active_children
from codesafe import safe_eval, UnsafeExpressionError, EvaluationTimeoutError
# Top-level helper function for multiprocessing pickling compatibility on Windows
def custom_func(x):
return x * 2
# Top-level helper that runs forever (used by the process-leak regression test)
def _busy_forever():
while True:
pass
# Top-level hostile object: module-level so it stays importable under the
# 'spawn' start method (a class defined inside a test method is not).
class ReduceBomb:
"""Records whether pickle ever reduces it; reduces to harmless data.
The payload is deliberately inert. On 'spawn' platforms multiprocessing
pickles the process arguments in the caller, and a side-effecting payload
here would execute inside the spawned child during bootstrap (before
CodeSafe's sandbox runs), which is a property of multiprocessing rather
than of the result boundary. What these tests are about is whether the
*result* of safe_eval is ever deserialized and whether __reduce__ runs at
all where the child inherits the object instead of receiving it by pickle.
"""
reduce_called = False
def __reduce__(self):
type(self).reduce_called = True
return (str, ("reduced",))
# Top-level raising functions (same spawn picklability requirement).
def _raiser_user_exception():
raise CustomTestError("nope")
def _raiser_assertion():
raise AssertionError("host callable was invoked from the sandbox")
class CustomTestError(Exception):
pass
class TestVulnerabilityFixes(unittest.TestCase):
"""Test cases for security vulnerabilities and their fixes."""
def setUp(self):
"""Set up test fixtures."""
self.marker_file = Path(__file__).parent / "codesafe_rce_marker.txt"
if self.marker_file.exists():
self.marker_file.unlink()
def tearDown(self):
"""Clean up test files."""
if self.marker_file.exists():
self.marker_file.unlink()
# ==================== MAIN VULNERABILITY TESTS ====================
def test_poc_direct_exec_blocked(self):
"""Test that direct exec() calls are blocked (negative control)."""
inner_code = (
"from pathlib import Path\n"
f"Path({str(self.marker_file)!r}).write_text("
"'codesafe-rce', encoding='utf-8')"
)
payload = f"exec({inner_code!r})"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
self.assertFalse(self.marker_file.exists())
print("[PASS] Direct exec is correctly blocked")
def test_poc_subscript_bypass_fixed(self):
"""Test the main PoC: __builtins__['exec']() bypass is now fixed."""
inner_code = (
"from pathlib import Path\n"
f"Path({str(self.marker_file)!r}).write_text("
"'codesafe-rce', encoding='utf-8')"
)
payload = f"__builtins__['exec']({inner_code!r})"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
self.assertFalse(self.marker_file.exists())
print("[PASS] Subscript bypass (__builtins__['exec']) is now blocked")
def test_poc_getattr_exec_blocked(self):
"""Test getattr(__builtins__, 'exec') bypass is blocked."""
inner_code = (
"from pathlib import Path\n"
f"Path({str(self.marker_file)!r}).write_text('getattr-rce')"
)
payload = f"getattr(__builtins__, 'exec')({inner_code!r})"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
self.assertFalse(self.marker_file.exists())
print("[PASS] getattr exec bypass is blocked")
def test_poc_eval_via_builtins_blocked(self):
"""Test __builtins__['eval']() is blocked."""
payload = "__builtins__['eval']('1 + 1')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] __builtins__['eval'] is blocked")
def test_poc_compile_via_builtins_blocked(self):
"""Test __builtins__['compile']() is blocked."""
payload = "__builtins__['compile']('1+1', '<string>', 'eval')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] __builtins__['compile'] is blocked")
def test_poc_import_via_builtins_blocked(self):
"""Test __builtins__['__import__']() is blocked."""
payload = "__builtins__['__import__']('os')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] __builtins__['__import__'] is blocked")
# ==================== INDIRECT CALL BYPASS TESTS ====================
def test_lambda_call_bypass_blocked(self):
"""Test lambda-based call bypass is blocked."""
payload = "(lambda: __import__('os'))()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Lambda call bypass is blocked")
def test_nested_subscript_bypass_blocked(self):
"""Test nested subscript access is blocked."""
payload = "__builtins__['dict']['keys']()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Nested subscript bypass is blocked")
def test_attribute_then_call_blocked(self):
"""Test attribute access followed by call is blocked."""
payload = "__builtins__.get('exec')('1+1')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Attribute-then-call bypass is blocked")
def test_list_comprehension_call_blocked(self):
"""Test list comprehension with function call is blocked."""
payload = "[__builtins__['exec']('1') for x in [1]]"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] List comprehension call bypass is blocked")
def test_generator_expression_call_blocked(self):
"""Test generator expression with function call is blocked."""
payload = "list(__builtins__['exec']('1') for x in [1])"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Generator expression call bypass is blocked")
# ==================== DUNDER METHOD ATTACKS ====================
def test_class_dunder_access_blocked(self):
"""Test __class__ attribute access is blocked."""
payload = "''.__class__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __class__ access is blocked")
def test_bases_dunder_access_blocked(self):
"""Test __bases__ attribute access is blocked."""
payload = "().__class__.__bases__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __bases__ access is blocked")
def test_subclasses_dunder_access_blocked(self):
"""Test __subclasses__ attribute access is blocked."""
payload = "''.__class__.__mro__[1].__subclasses__()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __subclasses__ access is blocked")
def test_globals_dunder_access_blocked(self):
"""Test __globals__ attribute access is blocked."""
payload = "(lambda: None).__globals__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __globals__ access is blocked")
def test_closure_dunder_access_blocked(self):
"""Test __closure__ attribute access is blocked."""
payload = "(lambda: None).__closure__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __closure__ access is blocked")
def test_code_dunder_access_blocked(self):
"""Test __code__ attribute access is blocked."""
payload = "(lambda: None).__code__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __code__ access is blocked")
# ==================== IMPORT AND MODULE ACCESS TESTS ====================
def test_direct_import_blocked(self):
"""Test direct import statements are blocked."""
payload = "import os"
try:
safe_eval(payload)
self.fail("Should have raised SyntaxError")
except SyntaxError:
pass
print("[PASS] Direct import is blocked (syntax error)")
def test_from_import_blocked(self):
"""Test from-import statements are blocked."""
payload = "from os import system"
try:
safe_eval(payload)
self.fail("Should have raised SyntaxError")
except SyntaxError:
pass
print("[PASS] From-import is blocked (syntax error)")
def test_os_system_via_builtins_blocked(self):
"""Test accessing os.system via builtins is blocked."""
payload = "__builtins__['__import__']('os').system('echo pwned')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] os.system via __import__ is blocked")
def test_subprocess_call_blocked(self):
"""Test subprocess module access is blocked."""
payload = "__builtins__['__import__']('subprocess').call(['ls'])"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] subprocess.call is blocked")
# ==================== FILE ACCESS TESTS ====================
def test_open_function_blocked_by_default(self):
"""Test open() is blocked when file_access=False."""
payload = "open('/etc/passwd').read()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, file_access=False)
print("[PASS] open() is blocked by default")
def test_pathlib_write_blocked(self):
"""Test pathlib.Path write operations are blocked."""
marker = Path(__file__).parent / "pathlib_test.txt"
if marker.exists():
marker.unlink()
payload = f"from pathlib import Path; Path({str(marker)!r}).write_text('test')"
try:
safe_eval(payload)
self.fail("Should have raised SyntaxError")
except SyntaxError:
pass
print("[PASS] pathlib write is blocked (syntax error)")
def test_io_module_blocked(self):
"""Test io module access is blocked."""
payload = "__builtins__['__import__']('io').open('/tmp/test')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] io.open is blocked")
# ==================== NETWORK ACCESS TESTS ====================
def test_socket_module_blocked(self):
"""Test socket module access is blocked."""
payload = "__builtins__['__import__']('socket').socket()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] socket module is blocked")
def test_requests_module_blocked(self):
"""Test requests module access is blocked."""
payload = "__builtins__['__import__']('requests').get('http://example.com')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] requests module is blocked")
def test_urllib_module_blocked(self):
"""Test urllib module access is blocked."""
payload = "__builtins__['__import__']('urllib.request').urlopen('http://example.com')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] urllib module is blocked")
# ==================== CODE EXECUTION PRIMITIVES ====================
def test_exec_function_blocked(self):
"""Test exec() function call is blocked."""
payload = "exec('print(1)')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] exec() is blocked")
def test_eval_function_blocked(self):
"""Test eval() function call is blocked."""
payload = "eval('1+1')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] eval() is blocked")
def test_compile_function_blocked(self):
"""Test compile() function call is blocked."""
payload = "compile('1+1', '<string>', 'eval')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] compile() is blocked")
def test_input_function_behavior(self):
"""Test input() behavior (should be blocked as it's not in safe builtins)."""
payload = "input()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] input() is blocked")
# ==================== METACLASS AND TYPE ATTACKS ====================
def test_type_subclasses_blocked(self):
"""Test type().subclasses() attack is blocked."""
payload = "type('')[0].__subclasses__()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] type subclasses attack is blocked")
def test_object_subclasses_blocked(self):
"""Test object.__subclasses__() attack is blocked."""
payload = "object().__subclasses__()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] object.__subclasses__ is blocked")
def test_mro_access_blocked(self):
"""Test __mro__ access is blocked."""
payload = "''.__class__.__mro__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __mro__ access is blocked")
# ==================== BUILTIN MODIFICATION TESTS ====================
def test_builtins_dict_modification_blocked(self):
"""Test modifying __builtins__ dict is blocked."""
payload = "__builtins__['malicious'] = lambda: 'pwned'"
try:
safe_eval(payload)
self.fail("Should have raised SyntaxError")
except SyntaxError:
pass
print("[PASS] __builtins__ modification is blocked (syntax error)")
def test_builtins_update_blocked(self):
"""Test __builtins__.update() is blocked."""
payload = "__builtins__.update({'evil': eval})"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] __builtins__.update() is blocked")
# ==================== SAFE OPERATIONS STILL WORK ====================
def test_safe_arithmetic_works(self):
"""Test that safe arithmetic operations still work."""
result = safe_eval("2 + 2 * 3")
self.assertEqual(result, 8)
print("[PASS] Safe arithmetic works")
def test_safe_string_operations_work(self):
"""Test that safe string operations still work."""
result = safe_eval("'hello'.upper()", allow_attributes=True)
self.assertEqual(result, "HELLO")
print("[PASS] Safe string operations work")
def test_safe_list_operations_work(self):
"""Test that safe list operations still work."""
result = safe_eval("[1, 2, 3][1]")
self.assertEqual(result, 2)
print("[PASS] Safe list operations work")
def test_safe_dict_operations_work(self):
"""Test that safe dict operations still work."""
result = safe_eval("{'a': 1}['a']")
self.assertEqual(result, 1)
print("[PASS] Safe dict operations work")
def test_safe_builtin_functions_work(self):
"""Test that safe builtin functions still work."""
result = safe_eval("max([1, 5, 3])")
self.assertEqual(result, 5)
result = safe_eval("abs(-5)")
self.assertEqual(result, 5)
result = safe_eval("len([1, 2, 3])")
self.assertEqual(result, 3)
print("[PASS] Safe builtin functions work")
def test_allowed_function_calls_work(self):
"""Test that explicitly allowed function calls work."""
result = safe_eval(
"custom_func(5)",
allowed_vars={"custom_func": custom_func},
allowed_function_calls=["custom_func"]
)
self.assertEqual(result, 10)
print("[PASS] Allowed function calls work")
class TestEdgeCases(unittest.TestCase):
"""Test edge cases and complex attack vectors."""
def test_multiple_indirect_lookups(self):
"""Test multiple levels of indirect lookup."""
payload = "__builtins__['dict']()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Multiple indirect lookups blocked")
def test_tuple_unpacking_call_blocked(self):
"""Test tuple unpacking with call is blocked."""
payload = "(*[__builtins__['exec']('1')],)"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Tuple unpacking call blocked")
def test_dict_comprehension_call_blocked(self):
"""Test dict comprehension with call is blocked."""
payload = "{x: __builtins__['exec']('1') for x in [1]}"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Dict comprehension call blocked")
def test_set_comprehension_call_blocked(self):
"""Test set comprehension with call is blocked."""
payload = "{__builtins__['exec']('1') for x in [1]}"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Set comprehension call blocked")
def test_ternary_with_call_blocked(self):
"""Test ternary operator with call is blocked."""
payload = "__builtins__['exec']('1') if True else None"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Ternary with call blocked")
def test_and_or_shortcircuit_call_blocked(self):
"""Test short-circuit evaluation with call is blocked."""
payload = "True and __builtins__['exec']('1')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Short-circuit call blocked")
def test_walrus_operator_call_blocked(self):
"""Test walrus operator with call is blocked."""
try:
payload = "(x := __builtins__['exec']('1'))"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload)
print("[PASS] Walrus operator call blocked")
except SyntaxError:
print("[SKIP] Walrus operator not available in this Python version")
class TestHardeningRegression(unittest.TestCase):
"""Regression tests for the v0.0.6 hardening and bug-fix release."""
# ==================== DUNDER ATTRIBUTE ESCAPES ====================
# A fixed blocklist of dunder names is not enough: dunders can be reached
# through string arguments that the AST checker never sees. All dunder
# attributes must be rejected.
def test_dunder_getattribute_class_blocked(self):
"""Reading __class__ via __getattribute__ string argument is blocked."""
payload = "().__getattribute__('__class__')"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __getattribute__('__class__') is blocked")
def test_dunder_getattribute_len_blocked(self):
"""Calling __getattribute__ at all is blocked."""
payload = "''.__getattribute__('__len__')()"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] __getattribute__('__len__')() is blocked")
def test_dunder_mro_blocked(self):
"""__mro__ attribute access is blocked."""
payload = "type('').__mro__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] type('').__mro__ is blocked")
def test_dunder_dict_blocked(self):
"""__dict__ attribute access is blocked."""
payload = "type('X', (), {}).__dict__"
with self.assertRaises(UnsafeExpressionError):
safe_eval(payload, allow_attributes=True)
print("[PASS] type('X').__dict__ is blocked")
def test_safe_non_dunder_attribute_calls_still_work(self):
"""Non-dunder method calls keep working with allow_attributes=True."""
result = safe_eval("'hello'.upper()", allow_attributes=True)
self.assertEqual(result, "HELLO")
print("[PASS] Safe non-dunder method calls still work")
# ==================== RESULT SERIALIZATION ====================
def test_lambda_result_is_rejected(self):
"""Lambdas are not returned: nothing callable crosses the boundary."""
with self.assertRaises(RuntimeError):
safe_eval("lambda: 40 + 2")
print("[PASS] Lambda result is rejected instead of pickled")
def test_dynamic_class_result_is_rejected(self):
"""Dynamically created classes are not returned to the parent."""
with self.assertRaises(RuntimeError):
safe_eval("type('Point', (), {'x': 10, 'y': 20})")
print("[PASS] Dynamic class result is rejected instead of pickled")
def test_plain_data_containers_require_opt_in(self):
"""Containers of plain data are returned only with allow_objects=True."""
with self.assertRaises(RuntimeError):
safe_eval("[1, 2, 3]")
self.assertEqual(safe_eval("[1, 2, 3]", allow_objects=True), [1, 2, 3])
self.assertEqual(safe_eval("(1, 'a')", allow_objects=True), (1, "a"))
self.assertEqual(safe_eval("{'a': [1]}", allow_objects=True), {"a": [1]})
print("[PASS] Plain-data containers are opt-in")
def test_unserializable_generator_raises_runtime_error(self):
"""A generator result (live frame state) raises a clear RuntimeError."""
with self.assertRaises(RuntimeError):
safe_eval("(x for x in range(3))")
print("[PASS] Unserializable generator result raises RuntimeError")
def test_decimal_and_fraction_round_trip(self):
"""Decimal and Fraction are plain data and round-trip losslessly."""
from decimal import Decimal
from fractions import Fraction
self.assertEqual(
safe_eval("Decimal('1.10')", allowed_vars={"Decimal": Decimal},
allowed_function_calls=["Decimal"]),
Decimal("1.10"))
self.assertEqual(
safe_eval("Fraction(1, 3)", allowed_vars={"Fraction": Fraction},
allowed_function_calls=["Fraction"]),
Fraction(1, 3))
print("[PASS] Decimal and Fraction round-trip")
# ==================== PROCESS CLEANUP ====================
def test_no_process_leak_on_timeout(self):
"""A timed-out evaluation never outlives the call, even with
immediate_termination=False (deprecated)."""
with self.assertRaises(EvaluationTimeoutError):
safe_eval(
"_busy_forever()",
allowed_vars={"_busy_forever": _busy_forever},
allowed_function_calls=["_busy_forever"],
timeout=0.2,
immediate_termination=False,
)
time.sleep(0.5)
self.assertEqual(active_children(), [])
print("[PASS] Timed-out child process is always terminated")
# ==================== INPUT VALIDATION ====================
def test_non_positive_timeout_rejected(self):
"""Zero and negative timeouts are rejected with ValueError."""
for invalid in (0, -5):
with self.assertRaises(ValueError):
safe_eval("1 + 1", timeout=invalid)
print("[PASS] Non-positive timeouts are rejected")
class TestResultBoundaryV007(unittest.TestCase):
"""Regression tests for the v0.0.7 fixes (parent-side deserialization).
CVE-2026-XXXXX (GHSA-XXXX-XXXX-XXXX): the v0.0.6 child serialized its result
with cloudpickle and the parent called cloudpickle.loads() on it. An
expression could build a value whose __reduce__ chain ran in the *parent*
process - outside the sandbox - using only AST nodes the checker allowed.
"""
def setUp(self):
self.marker_file = Path(__file__).parent / "codesafe_rce_marker.txt"
if self.marker_file.exists():
self.marker_file.unlink()
def tearDown(self):
if self.marker_file.exists():
self.marker_file.unlink()
def _rce_payload(self, marker):
"""The reported PoC: a __reduce__ gadget smuggled through the result."""
code = (
"__import__('pathlib').Path(" + repr(str(marker)) + ")"
".write_text(str(__import__('os').getpid()))"
)
mk = lambda c: f"list(zip(range(1),iter({c},None)))[0][1]"
y = ("type('Y',(),{'__call__':lambda s,*a:None,"
"'__reduce__':lambda s:(lambda:eval,())})")
x = f"type('X',(),{{'__reduce__':lambda s:({mk(y)},({code!r},))}})"
return mk(x)
# ==================== DIRECT RCE REGRESSION ====================
def test_reported_reduce_gadget_cannot_execute(self):
"""The reported PoC must not run code in the parent process."""
payload = self._rce_payload(self.marker_file)
with self.assertRaises((RuntimeError, UnsafeExpressionError)):
safe_eval(payload)
self.assertFalse(self.marker_file.exists())
def test_simpler_reduce_gadget_cannot_execute(self):
"""A minimal __reduce__ -> (eval, (code,)) gadget is also inert."""
code = "__import__('pathlib').Path(" + repr(str(self.marker_file)) + ").write_text('x')"
payload = ("list(iter(type('X',(),{'__reduce__':lambda s:(eval,(" + repr(code) + ",))}),None))")
with self.assertRaises((RuntimeError, UnsafeExpressionError)):
safe_eval(payload)
self.assertFalse(self.marker_file.exists())
def test_result_is_never_pickled(self):
"""A hostile object never executes, and never comes back as an object.
Two distinct guarantees are checked:
* Nothing in the result path executes attacker code - the marker file
must not appear - and the caller never receives a live object.
* Where the child inherits the caller's objects ('fork'), __reduce__
never runs at all.
A locally defined class cannot be pickled to a 'spawn' child (Windows,
macOS, or a host that pinned that method), so there the call fails
before the sandbox starts; that failure is still a safe outcome, which
is what this test asserts rather than the specific exception type.
"""
import multiprocessing
class Hostile:
reduce_called = False
def __reduce__(self):
Hostile.reduce_called = True
code = ("__import__('pathlib').Path("
+ repr(str(self.marker_file))
+ ").write_text(str(__import__('os').getpid()))")
return (eval, (code,))
forking = multiprocessing.get_start_method() == 'fork'
try:
outcome = safe_eval("o", allowed_vars={"o": Hostile()})
except (RuntimeError, EvaluationTimeoutError, UnsafeExpressionError):
outcome = None
else:
self.fail("a hostile object was returned to the caller")
self.assertIsNone(outcome)
self.assertFalse(self.marker_file.exists())
if forking:
self.assertFalse(Hostile.reduce_called)
def test_child_crash_is_not_reported_as_timeout(self):
"""A dead child is reported as a crash, not a 5-second timeout.
Regression: a child that died before sending a result left the parent
waiting for the full timeout and then claimed the evaluation had timed
out, which hid the real cause and stalled the call for seconds.
"""
import time
class DieAtOnce:
def __reduce__(self):
return (eval, ("raise SystemExit(1)",))
started = time.monotonic()
with self.assertRaises(RuntimeError):
safe_eval("o", allowed_vars={"o": DieAtOnce()})
elapsed = time.monotonic() - started
# Either the object cannot be pickled for the child (spawn) or the
# child dies; both must fail fast rather than after the full timeout.
self.assertLess(elapsed, 3.0)
def test_unpicklable_variable_raises_clear_error(self):
"""Passing a lambda through allowed_vars fails with a clear message.
Under 'spawn' the pickling happens in the caller and the raw failure
used to escape as an AttributeError from multiprocessing.
"""
try:
safe_eval("f()", allowed_vars={"f": lambda: 1},
allowed_function_calls=["f"])
except RuntimeError as exc:
self.assertIn("pickled", str(exc).lower())
# On fork platforms the object is inherited, and the call itself is
# still refused because callables cannot be returned - either way the
# caller never receives a function.
except Exception as exc: # noqa: BLE001
self.assertNotIsInstance(exc, AttributeError)
def test_plain_data_still_round_trips(self):
self.assertEqual(safe_eval("1 + 1"), 2)
self.assertEqual(safe_eval("'héllo'"), "héllo")
self.assertEqual(safe_eval("b'abc'"), b"abc")
self.assertEqual(safe_eval("1.5"), 1.5)
self.assertEqual(safe_eval("True"), True)
self.assertIsNone(safe_eval("None"))
self.assertEqual(safe_eval("[1, [2, {'a': (3,)}]]", allow_objects=True),
[1, [2, {"a": (3,)}]])
def test_int_digit_limit_restored(self):
import sys
if not hasattr(sys, "get_int_max_str_digits"):
self.skipTest("Python < 3.11")
before = sys.get_int_max_str_digits()
with self.assertRaises(RuntimeError):
safe_eval("10 ** 10 ** 6")
self.assertEqual(sys.get_int_max_str_digits(), before)
def test_undersized_results_rejected(self):
with self.assertRaises(RuntimeError):
safe_eval("'x' * 2_000_000")
# ==================== STRING-FORMAT ATTRIBUTE TRAVERSAL ====================
def test_format_string_dunder_traversal_blocked(self):
"""'{0.__class__}'.format(o) never makes an ast.Attribute node."""
class Host:
secret = "leaked"
for expr in (
"'{0.__class__}'.format(o)",
"'{0.__init__.__globals__}'.format(o)",
"'{0.__class__.__mro__}'.format(o)",
"'{a.__class__}'.format_map({'a': o})",
"'{0[secret]}'.format(o)",
):
with self.assertRaises(UnsafeExpressionError):
safe_eval(expr, allow_attributes=True, allowed_vars={"o": Host()})
def test_reported_format_field_globals_leak(self):
"""The reported PoC: a format field reads the helper's module globals.
Reported by email: on 0.0.3-0.0.6 dunder names inside a str.format
replacement field are string literals, so the AST checker never sees an
ast.Attribute node and the dunder block does not apply. Affected range
was verified against the published wheels for 0.0.3 through 0.0.6;
0.0.1/0.0.2 predate allow_attributes. The impact is disclosure, not
execution: a replacement field cannot contain a call, and the resolved
value is rendered to str.
"""
secret = "HOST_SECRET_s3cr3t_value_271"
def helper(x):
return x + 1
helper.__globals__["HOST_SECRET"] = secret
try:
for expr in (
"'{0.__globals__[HOST_SECRET]}'.format(h)",
"'{0.__globals__}'.format(h)",
"'{0.__class__}'.format('')",
"'{0.__class__.__base__.__subclasses__}'.format('')",
"'{0.__globals__[__builtins__]}'.format(h)",
"'{0.__globals__[__builtins__][__import__]}'.format(h)",
):
with self.assertRaises(UnsafeExpressionError):
safe_eval(expr, allow_attributes=True, allowed_vars={"h": helper})
finally:
helper.__globals__.pop("HOST_SECRET", None)
def test_format_templates_that_are_not_literals_are_blocked(self):
"""Computed templates are refused too - the check is name-independent.
A template assembled from pieces (concatenation, join, chr()) cannot be
resolved statically, so the call is rejected rather than guessed at.
"""
for expr in (
"('{0.' + '__class__' + '}').format('')",
"''.join(['{0.__class__', '}']).format('')",
"f'{chr(123)}0.__class__{chr(125)}'.format('')",
):
with self.assertRaises((UnsafeExpressionError, RuntimeError)):
safe_eval(expr, allow_attributes=True)
def test_format_map_plain_key_is_data_only(self):
"""format_map with a plain {name} field stays usable and stays local.
A named field only reads a key from the mapping the expression itself
passed in, so nothing outside the expression is reachable; anything
needing an attribute or a nested key expression is rejected.
"""
self.assertEqual(safe_eval("'{k}'.format_map({'k': 1})", allow_attributes=True), "1")
def helper(x):
return x
for expr in (
"'{0.__globals__}'.format_map({})",
"'{0[S]}'.format_map(h.__globals__)",
"'{__import__}'.format_map(h.__globals__['__builtins__'])",
):
with self.assertRaises(UnsafeExpressionError):
safe_eval(expr, allow_attributes=True, allowed_vars={"h": helper})
def test_format_string_leak_is_blocked_without_attributes(self):
with self.assertRaises(UnsafeExpressionError):
safe_eval("'{0.__class__}'.format(1)")
def test_plain_formatting_still_works(self):
self.assertEqual(safe_eval("'{} {}'.format(1, 2)", allow_attributes=True), "1 2")
self.assertEqual(safe_eval("'{0:>3}'.format(5)", allow_attributes=True), " 5")
self.assertEqual(safe_eval("'{name}'.format(name='x')", allow_attributes=True), "x")
# ==================== SHADOWING BYPASSES ====================
def test_walrus_shadowing_safe_builtin_blocked(self):
class Host:
def __call__(self, *a):
return "called"
with self.assertRaises(UnsafeExpressionError):
safe_eval("((len := o), len())", allowed_vars={"o": Host()})
def test_comprehension_shadowing_safe_builtin_blocked(self):
class Host:
def __call__(self, *a):
return "called"
with self.assertRaises(UnsafeExpressionError):
safe_eval("[len() for len in [o]]", allowed_vars={"o": Host()})
def test_lambda_param_shadowing_safe_builtin_blocked(self):
class Host:
def __call__(self, *a):
return "called"
with self.assertRaises(UnsafeExpressionError):
safe_eval("(lambda len: len())(o)", allowed_vars={"o": Host()})
def test_shadowed_name_allowed_when_explicitly_allowlisted(self):
"""Explicitly allowlisting a rebound name keeps the call working."""
import ast
from codesafe import _check_ast
parsed = ast.parse("((len := f), len(4))", mode="eval")
# Without the allowlist the shadowed call is rejected...
with self.assertRaises(UnsafeExpressionError):
_check_ast(parsed, [], False, allowed_vars={"f": len})
# ...with it, the AST check passes (the returned function is then
# rejected by the result policy, which is what RuntimeError reports).
_check_ast(parsed, ["len"], False, allowed_vars={"f": len})
def test_callable_zombie_via_sorted_key_blocked(self):
def boom(x):
boom.called = True
return x
boom.called = False
with self.assertRaises((UnsafeExpressionError, RuntimeError)):
safe_eval("sorted(['a'], key=o)", allowed_vars={"o": boom})
self.assertFalse(boom.called)
def test_callable_zombie_via_iter_blocked(self):
with self.assertRaises((UnsafeExpressionError, RuntimeError)):
safe_eval("list(iter(o, None))", allowed_vars={"o": _raiser_assertion})
def test_callable_zombie_via_max_key_blocked(self):
def boom(x):
boom.called = True
return x
boom.called = False
with self.assertRaises((UnsafeExpressionError, RuntimeError)):
safe_eval("max([1], key=o)", allowed_vars={"o": boom})
self.assertFalse(boom.called)
def test_safe_callables_as_builtin_arguments_still_work(self):
# Builtin callables (types, allowlisted builtins) remain usable as
# arguments to builtins that invoke them.
self.assertEqual(safe_eval("max([1, 5, 3], key=str)"), 5)
self.assertEqual(safe_eval("min([1, 5, 3], key=abs)"), 1)
# ==================== __builtins__ PRESENCE ====================
def test_builtins_name_not_readable(self):
with self.assertRaises(UnsafeExpressionError):
safe_eval("__builtins__")
with self.assertRaises(UnsafeExpressionError):
safe_eval("__builtins__['len'](1)")
with self.assertRaises(UnsafeExpressionError):
safe_eval("__builtins__.get('len')", allow_attributes=True)
def test_builtins_rebinding_blocked(self):
with self.assertRaises(UnsafeExpressionError):
safe_eval("(__builtins__.update({'x': 1}))", allow_attributes=True)
# ==================== EXCEPTION BOUNDARY ====================
def test_control_flow_exceptions_do_not_escape(self):