|
56 | 56 |
|
57 | 57 |
|
58 | 58 | # simple sandboxing scheme: |
| 59 | +# |
| 60 | +# - use resource.setrlimit to deprive this process of ANY file descriptors |
| 61 | +# (which will cause file read/write and subprocess shell launches to fail) |
| 62 | +# - restrict user builtins and module imports |
| 63 | +# (beware that this is NOT foolproof at all ... there are known flaws!) |
| 64 | +# |
| 65 | +# ALWAYS use defense-in-depth and don't just rely on these simple mechanisms |
| 66 | +import resource |
59 | 67 |
|
60 | 68 |
|
61 | 69 | # ugh, I can't figure out why in Python 2, __builtins__ seems to |
@@ -646,6 +654,19 @@ def _runscript(self, script_str): |
646 | 654 | "__user_stdout__" : user_stdout} |
647 | 655 |
|
648 | 656 | try: |
| 657 | + # enforce resource limits RIGHT BEFORE running script_str |
| 658 | + |
| 659 | + # set ~200MB virtual memory limit AND a 5-second CPU time |
| 660 | + # limit (tuned for Webfaction shared hosting) to protect against |
| 661 | + # memory bombs such as: |
| 662 | + # x = 2 |
| 663 | + # while True: x = x*x |
| 664 | + resource.setrlimit(resource.RLIMIT_AS, (200000000, 200000000)) |
| 665 | + resource.setrlimit(resource.RLIMIT_CPU, (5, 5)) |
| 666 | + |
| 667 | + # protect against unauthorized filesystem accesses ... |
| 668 | + resource.setrlimit(resource.RLIMIT_NOFILE, (0, 0)) # no opened files allowed |
| 669 | + resource.setrlimit(resource.RLIMIT_FSIZE, (0, 0)) # (redundancy for paranoia) |
649 | 670 | self.run(script_str, user_globals, user_globals) |
650 | 671 | # sys.exit ... |
651 | 672 | except SystemExit: |
|
0 commit comments