Skip to content

Commit 30710ae

Browse files
author
Philip Guo
committed
slightly less crappy job of sandboxing by restricting file accesses
1 parent 2ea03d9 commit 30710ae

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

‎v3/pg_logger.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@
5656

5757

5858
# 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
5967

6068

6169
# ugh, I can't figure out why in Python 2, __builtins__ seems to
@@ -646,6 +654,19 @@ def _runscript(self, script_str):
646654
"__user_stdout__" : user_stdout}
647655

648656
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)
649670
self.run(script_str, user_globals, user_globals)
650671
# sys.exit ...
651672
except SystemExit:

0 commit comments

Comments
 (0)