How can I sandbox Python in pure Python?












45















I'm developing a web game in pure Python, and want some simple scripting available to allow for more dynamic game content. Game content can be added live by privileged users.



It would be nice if the scripting language could be Python. However, it can't run with access to the environment the game runs on since a malicious user could wreak havoc which would be bad. Is it possible to run sandboxed Python in pure Python?



Update: In fact, since true Python support would be way overkill, a simple scripting language with Pythonic syntax would be perfect.



If there aren't any Pythonic script interpreters, are there any other open source script interpreters written in pure Python that I could use? The requirements are support for variables, basic conditionals and function calls (not definitions).










share|improve this question





























    45















    I'm developing a web game in pure Python, and want some simple scripting available to allow for more dynamic game content. Game content can be added live by privileged users.



    It would be nice if the scripting language could be Python. However, it can't run with access to the environment the game runs on since a malicious user could wreak havoc which would be bad. Is it possible to run sandboxed Python in pure Python?



    Update: In fact, since true Python support would be way overkill, a simple scripting language with Pythonic syntax would be perfect.



    If there aren't any Pythonic script interpreters, are there any other open source script interpreters written in pure Python that I could use? The requirements are support for variables, basic conditionals and function calls (not definitions).










    share|improve this question



























      45












      45








      45


      33






      I'm developing a web game in pure Python, and want some simple scripting available to allow for more dynamic game content. Game content can be added live by privileged users.



      It would be nice if the scripting language could be Python. However, it can't run with access to the environment the game runs on since a malicious user could wreak havoc which would be bad. Is it possible to run sandboxed Python in pure Python?



      Update: In fact, since true Python support would be way overkill, a simple scripting language with Pythonic syntax would be perfect.



      If there aren't any Pythonic script interpreters, are there any other open source script interpreters written in pure Python that I could use? The requirements are support for variables, basic conditionals and function calls (not definitions).










      share|improve this question
















      I'm developing a web game in pure Python, and want some simple scripting available to allow for more dynamic game content. Game content can be added live by privileged users.



      It would be nice if the scripting language could be Python. However, it can't run with access to the environment the game runs on since a malicious user could wreak havoc which would be bad. Is it possible to run sandboxed Python in pure Python?



      Update: In fact, since true Python support would be way overkill, a simple scripting language with Pythonic syntax would be perfect.



      If there aren't any Pythonic script interpreters, are there any other open source script interpreters written in pure Python that I could use? The requirements are support for variables, basic conditionals and function calls (not definitions).







      python scripting






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 18 '10 at 8:34







      Blixt

















      asked Jun 18 '10 at 8:28









      BlixtBlixt

      40k1095141




      40k1095141
























          8 Answers
          8






          active

          oldest

          votes


















          42














          This is really non-trivial.



          There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and exec your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thread about this on Python-dev a year ago or so in which people did things from catching exceptions and poking at internal state to break out to byte code manipulation. This is the way to go if you want a complete language.



          The other way is to parse the code and then use the ast module to kick out constructs you don't want (e.g. import statements, function calls etc.) and then to compile the rest. This is the way to go if you want to use Python as a config language etc.



          Another way (which might not work for you since you're using GAE), is the PyPy sandbox. While I haven't used it myself, word on the intertubes is that it's the only real sandboxed Python out there.



          Based on your description of the requirements (The requirements are support for variables, basic conditionals and function calls (not definitions)) , you might want to evaluate approach 2 and kick out everything else from the code. It's a little tricky but doable.






          share|improve this answer





















          • 1





            Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

            – Blixt
            Jun 18 '10 at 9:35






          • 1





            I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

            – Noufal Ibrahim
            Jun 18 '10 at 10:37






          • 1





            Do you think this code is a good start? code.activestate.com/recipes/496746

            – Blixt
            Jun 18 '10 at 11:51






          • 1





            Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

            – Noufal Ibrahim
            Jun 18 '10 at 15:49






          • 1





            @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

            – user2284570
            Sep 16 '16 at 20:49





















          6














          AFAIK it is possible to run a code in a completely isolated environment:



          exec somePythonCode in {'__builtins__': {}}, {}


          But in such environment you can do almost nothing :) (you can not even import a module; but still a malicious user can run an infinite recursion or cause running out of memory.) Probably you would want to add some modules that will be the interface to you game engine.






          share|improve this answer





















          • 1





            Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

            – Blixt
            Jun 18 '10 at 9:09











          • Does this actually work?

            – oneself
            Apr 24 '11 at 4:29











          • that's smart. Is this absolutely safe ?

            – Ali
            Feb 26 '12 at 6:47








          • 18





            not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

            – Michał Zieliński
            May 4 '12 at 21:18






          • 9





            @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

            – Hernan
            Jun 13 '12 at 15:14



















          4














          I'm not sure why nobody mentions this, but Zope 2 has a thing called Python Script, which is exactly that - restricted Python executed in a sandbox, without any access to filesystem, with access to other Zope objects controlled by Zope security machinery, with imports limited to a safe subset.



          Zope in general is pretty safe, so I would imagine there are no known or obvious ways to break out of the sandbox.



          I'm not sure how exactly Python Scripts are implemented, but the feature was around since like year 2000.



          And here's the magic behind PythonScripts, with detailed documentation: http://pypi.python.org/pypi/RestrictedPython - it even looks like it doesn't have any dependencies on Zope, so can be used standalone.



          Note that this is not for safely running arbitrary python code (most of the random scripts will fail on first import or file access), but rather for using Python for limited scripting within a Python application.



          This answer is from my comment to a question closed as a duplicate of this one: Python from Python: restricting functionality?






          share|improve this answer


























          • The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

            – colidyre
            Sep 2 '18 at 16:01



















          3














          I would look into a two server approach. The first server is the privileged web server where your code lives. The second server is a very tightly controlled server that only provides a web service or RPC service and runs the untrusted code. You provide your content creator with your custom interface. For example you if you allowed the end user to create items, you would have a look up that called the server with the code to execute and the set of parameters.



          Here's and abstract example for a healing potion.



          {function_id='healing potion', action='use', target='self', inventory_id='1234'}


          The response might be something like



          {hp='+5' action={destroy_inventory_item, inventory_id='1234'}}





          share|improve this answer
























          • Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

            – Blixt
            Jun 18 '10 at 9:38











          • You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

            – Philip Tinney
            Jun 18 '10 at 10:01











          • +1 for a new way of solving the problem.

            – Noufal Ibrahim
            Jun 21 '10 at 10:45











          • This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

            – Ali
            May 27 '12 at 20:08











          • This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

            – Glyph
            Aug 16 '12 at 23:02



















          2














          Hmm. This is a thought experiment, I don't know of it being done:



          You could use the compiler package to parse the script. You can then walk this tree, prefixing all identifiers - variables, method names e.t.c. (also has|get|setattr invocations and so on) - with a unique preamble so that they cannot possibly refer to your variables. You could also ensure that the compiler package itself was not invoked, and perhaps other blacklisted things such as opening files. You then emit the python code for this, and compiler.compile it.



          The docs note that the compiler package is not in Python 3.0, but does not mention what the 3.0 alternative is.



          In general, this is parallel to how forum software and such try to whitelist 'safe' Javascript or HTML e.t.c. And they historically have a bad record of stomping all the escapes. But you might have more luck with Python :)






          share|improve this answer



















          • 1





            Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

            – Lukas Boersma
            Feb 1 '18 at 15:23



















          2














          You'll probably be interested in the Python language services section of the libref for writing your own parser.






          share|improve this answer































            0














            I think your best bet is going to be a combination of the replies thus far.



            You'll want to parse and sanitise the input - removing any import statements for example.



            You can then use Messa's exec sample (or something similar) to allow the code execution against only the builtin variables of your choosing - most likely some sort of API defined by yourself that provides the programmer access to the functionality you deem relevant.






            share|improve this answer
























            • I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

              – Noufal Ibrahim
              Jun 18 '10 at 9:22











            • Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

              – Blixt
              Jun 18 '10 at 9:28











            • You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

              – Noufal Ibrahim
              Jun 18 '10 at 9:36



















            0














            You'll find some ideas in this wiki page, but it does not look like it can be done easily.






            share|improve this answer


























            • Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

              – Blixt
              Jun 18 '10 at 8:32











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3068139%2fhow-can-i-sandbox-python-in-pure-python%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            8 Answers
            8






            active

            oldest

            votes








            8 Answers
            8






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            42














            This is really non-trivial.



            There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and exec your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thread about this on Python-dev a year ago or so in which people did things from catching exceptions and poking at internal state to break out to byte code manipulation. This is the way to go if you want a complete language.



            The other way is to parse the code and then use the ast module to kick out constructs you don't want (e.g. import statements, function calls etc.) and then to compile the rest. This is the way to go if you want to use Python as a config language etc.



            Another way (which might not work for you since you're using GAE), is the PyPy sandbox. While I haven't used it myself, word on the intertubes is that it's the only real sandboxed Python out there.



            Based on your description of the requirements (The requirements are support for variables, basic conditionals and function calls (not definitions)) , you might want to evaluate approach 2 and kick out everything else from the code. It's a little tricky but doable.






            share|improve this answer





















            • 1





              Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

              – Blixt
              Jun 18 '10 at 9:35






            • 1





              I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

              – Noufal Ibrahim
              Jun 18 '10 at 10:37






            • 1





              Do you think this code is a good start? code.activestate.com/recipes/496746

              – Blixt
              Jun 18 '10 at 11:51






            • 1





              Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

              – Noufal Ibrahim
              Jun 18 '10 at 15:49






            • 1





              @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

              – user2284570
              Sep 16 '16 at 20:49


















            42














            This is really non-trivial.



            There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and exec your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thread about this on Python-dev a year ago or so in which people did things from catching exceptions and poking at internal state to break out to byte code manipulation. This is the way to go if you want a complete language.



            The other way is to parse the code and then use the ast module to kick out constructs you don't want (e.g. import statements, function calls etc.) and then to compile the rest. This is the way to go if you want to use Python as a config language etc.



            Another way (which might not work for you since you're using GAE), is the PyPy sandbox. While I haven't used it myself, word on the intertubes is that it's the only real sandboxed Python out there.



            Based on your description of the requirements (The requirements are support for variables, basic conditionals and function calls (not definitions)) , you might want to evaluate approach 2 and kick out everything else from the code. It's a little tricky but doable.






            share|improve this answer





















            • 1





              Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

              – Blixt
              Jun 18 '10 at 9:35






            • 1





              I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

              – Noufal Ibrahim
              Jun 18 '10 at 10:37






            • 1





              Do you think this code is a good start? code.activestate.com/recipes/496746

              – Blixt
              Jun 18 '10 at 11:51






            • 1





              Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

              – Noufal Ibrahim
              Jun 18 '10 at 15:49






            • 1





              @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

              – user2284570
              Sep 16 '16 at 20:49
















            42












            42








            42







            This is really non-trivial.



            There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and exec your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thread about this on Python-dev a year ago or so in which people did things from catching exceptions and poking at internal state to break out to byte code manipulation. This is the way to go if you want a complete language.



            The other way is to parse the code and then use the ast module to kick out constructs you don't want (e.g. import statements, function calls etc.) and then to compile the rest. This is the way to go if you want to use Python as a config language etc.



            Another way (which might not work for you since you're using GAE), is the PyPy sandbox. While I haven't used it myself, word on the intertubes is that it's the only real sandboxed Python out there.



            Based on your description of the requirements (The requirements are support for variables, basic conditionals and function calls (not definitions)) , you might want to evaluate approach 2 and kick out everything else from the code. It's a little tricky but doable.






            share|improve this answer















            This is really non-trivial.



            There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and exec your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thread about this on Python-dev a year ago or so in which people did things from catching exceptions and poking at internal state to break out to byte code manipulation. This is the way to go if you want a complete language.



            The other way is to parse the code and then use the ast module to kick out constructs you don't want (e.g. import statements, function calls etc.) and then to compile the rest. This is the way to go if you want to use Python as a config language etc.



            Another way (which might not work for you since you're using GAE), is the PyPy sandbox. While I haven't used it myself, word on the intertubes is that it's the only real sandboxed Python out there.



            Based on your description of the requirements (The requirements are support for variables, basic conditionals and function calls (not definitions)) , you might want to evaluate approach 2 and kick out everything else from the code. It's a little tricky but doable.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 4 '13 at 14:40









            Aaron Digulla

            245k83467686




            245k83467686










            answered Jun 18 '10 at 9:21









            Noufal IbrahimNoufal Ibrahim

            55.7k10105149




            55.7k10105149








            • 1





              Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

              – Blixt
              Jun 18 '10 at 9:35






            • 1





              I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

              – Noufal Ibrahim
              Jun 18 '10 at 10:37






            • 1





              Do you think this code is a good start? code.activestate.com/recipes/496746

              – Blixt
              Jun 18 '10 at 11:51






            • 1





              Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

              – Noufal Ibrahim
              Jun 18 '10 at 15:49






            • 1





              @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

              – user2284570
              Sep 16 '16 at 20:49
















            • 1





              Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

              – Blixt
              Jun 18 '10 at 9:35






            • 1





              I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

              – Noufal Ibrahim
              Jun 18 '10 at 10:37






            • 1





              Do you think this code is a good start? code.activestate.com/recipes/496746

              – Blixt
              Jun 18 '10 at 11:51






            • 1





              Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

              – Noufal Ibrahim
              Jun 18 '10 at 15:49






            • 1





              @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

              – user2284570
              Sep 16 '16 at 20:49










            1




            1





            Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

            – Blixt
            Jun 18 '10 at 9:35





            Hmm yeah I was thinking about what would happen if you start digging in code objects... I guess you can escape the exec that way... PyPy is what Google App Engine is using already though, isn't it? I wonder if the pure Python version of PyPy can run in GAE... I'll mess around with it a bit.

            – Blixt
            Jun 18 '10 at 9:35




            1




            1





            I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

            – Noufal Ibrahim
            Jun 18 '10 at 10:37





            I think GAE has a variant of unalden swallow. It's not PyPY AFAIK.

            – Noufal Ibrahim
            Jun 18 '10 at 10:37




            1




            1





            Do you think this code is a good start? code.activestate.com/recipes/496746

            – Blixt
            Jun 18 '10 at 11:51





            Do you think this code is a good start? code.activestate.com/recipes/496746

            – Blixt
            Jun 18 '10 at 11:51




            1




            1





            Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

            – Noufal Ibrahim
            Jun 18 '10 at 15:49





            Can't give you a total guarantee but a cursory look tells me that it's decent code. One place I know which does this in "production" is the Templetor templating engine used by web.py. You might want to take a look at that.

            – Noufal Ibrahim
            Jun 18 '10 at 15:49




            1




            1





            @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

            – user2284570
            Sep 16 '16 at 20:49







            @Blixt : they always used cpython. The mechanism for 2.5.2 was entirely done in pure python. For 2.7.5, they compiled python for ɴaᴄl‑glibc : a sandbox which runs at the C level.

            – user2284570
            Sep 16 '16 at 20:49















            6














            AFAIK it is possible to run a code in a completely isolated environment:



            exec somePythonCode in {'__builtins__': {}}, {}


            But in such environment you can do almost nothing :) (you can not even import a module; but still a malicious user can run an infinite recursion or cause running out of memory.) Probably you would want to add some modules that will be the interface to you game engine.






            share|improve this answer





















            • 1





              Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

              – Blixt
              Jun 18 '10 at 9:09











            • Does this actually work?

              – oneself
              Apr 24 '11 at 4:29











            • that's smart. Is this absolutely safe ?

              – Ali
              Feb 26 '12 at 6:47








            • 18





              not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

              – Michał Zieliński
              May 4 '12 at 21:18






            • 9





              @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

              – Hernan
              Jun 13 '12 at 15:14
















            6














            AFAIK it is possible to run a code in a completely isolated environment:



            exec somePythonCode in {'__builtins__': {}}, {}


            But in such environment you can do almost nothing :) (you can not even import a module; but still a malicious user can run an infinite recursion or cause running out of memory.) Probably you would want to add some modules that will be the interface to you game engine.






            share|improve this answer





















            • 1





              Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

              – Blixt
              Jun 18 '10 at 9:09











            • Does this actually work?

              – oneself
              Apr 24 '11 at 4:29











            • that's smart. Is this absolutely safe ?

              – Ali
              Feb 26 '12 at 6:47








            • 18





              not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

              – Michał Zieliński
              May 4 '12 at 21:18






            • 9





              @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

              – Hernan
              Jun 13 '12 at 15:14














            6












            6








            6







            AFAIK it is possible to run a code in a completely isolated environment:



            exec somePythonCode in {'__builtins__': {}}, {}


            But in such environment you can do almost nothing :) (you can not even import a module; but still a malicious user can run an infinite recursion or cause running out of memory.) Probably you would want to add some modules that will be the interface to you game engine.






            share|improve this answer















            AFAIK it is possible to run a code in a completely isolated environment:



            exec somePythonCode in {'__builtins__': {}}, {}


            But in such environment you can do almost nothing :) (you can not even import a module; but still a malicious user can run an infinite recursion or cause running out of memory.) Probably you would want to add some modules that will be the interface to you game engine.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jun 18 '10 at 8:58

























            answered Jun 18 '10 at 8:48









            MessaMessa

            16k22850




            16k22850








            • 1





              Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

              – Blixt
              Jun 18 '10 at 9:09











            • Does this actually work?

              – oneself
              Apr 24 '11 at 4:29











            • that's smart. Is this absolutely safe ?

              – Ali
              Feb 26 '12 at 6:47








            • 18





              not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

              – Michał Zieliński
              May 4 '12 at 21:18






            • 9





              @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

              – Hernan
              Jun 13 '12 at 15:14














            • 1





              Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

              – Blixt
              Jun 18 '10 at 9:09











            • Does this actually work?

              – oneself
              Apr 24 '11 at 4:29











            • that's smart. Is this absolutely safe ?

              – Ali
              Feb 26 '12 at 6:47








            • 18





              not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

              – Michał Zieliński
              May 4 '12 at 21:18






            • 9





              @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

              – Hernan
              Jun 13 '12 at 15:14








            1




            1





            Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

            – Blixt
            Jun 18 '10 at 9:09





            Hm, interesting. I'll try it out! Since all code is already sandboxed from the system (I'm developing on GAE), I can detect an infinite recursion/heavy memory usage and stop the script from being run again.

            – Blixt
            Jun 18 '10 at 9:09













            Does this actually work?

            – oneself
            Apr 24 '11 at 4:29





            Does this actually work?

            – oneself
            Apr 24 '11 at 4:29













            that's smart. Is this absolutely safe ?

            – Ali
            Feb 26 '12 at 6:47







            that's smart. Is this absolutely safe ?

            – Ali
            Feb 26 '12 at 6:47






            18




            18





            not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

            – Michał Zieliński
            May 4 '12 at 21:18





            not exactly, try running exec [ i for i in ().__class__.__base__.__subclasses__() if i.__name__ == 'code'][0](0, 5, 8, 0, 'hello world', (), (), (), '', '', 0, '')

            – Michał Zieliński
            May 4 '12 at 21:18




            9




            9





            @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

            – Hernan
            Jun 13 '12 at 15:14





            @ChristianOudard Take a look at nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

            – Hernan
            Jun 13 '12 at 15:14











            4














            I'm not sure why nobody mentions this, but Zope 2 has a thing called Python Script, which is exactly that - restricted Python executed in a sandbox, without any access to filesystem, with access to other Zope objects controlled by Zope security machinery, with imports limited to a safe subset.



            Zope in general is pretty safe, so I would imagine there are no known or obvious ways to break out of the sandbox.



            I'm not sure how exactly Python Scripts are implemented, but the feature was around since like year 2000.



            And here's the magic behind PythonScripts, with detailed documentation: http://pypi.python.org/pypi/RestrictedPython - it even looks like it doesn't have any dependencies on Zope, so can be used standalone.



            Note that this is not for safely running arbitrary python code (most of the random scripts will fail on first import or file access), but rather for using Python for limited scripting within a Python application.



            This answer is from my comment to a question closed as a duplicate of this one: Python from Python: restricting functionality?






            share|improve this answer


























            • The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

              – colidyre
              Sep 2 '18 at 16:01
















            4














            I'm not sure why nobody mentions this, but Zope 2 has a thing called Python Script, which is exactly that - restricted Python executed in a sandbox, without any access to filesystem, with access to other Zope objects controlled by Zope security machinery, with imports limited to a safe subset.



            Zope in general is pretty safe, so I would imagine there are no known or obvious ways to break out of the sandbox.



            I'm not sure how exactly Python Scripts are implemented, but the feature was around since like year 2000.



            And here's the magic behind PythonScripts, with detailed documentation: http://pypi.python.org/pypi/RestrictedPython - it even looks like it doesn't have any dependencies on Zope, so can be used standalone.



            Note that this is not for safely running arbitrary python code (most of the random scripts will fail on first import or file access), but rather for using Python for limited scripting within a Python application.



            This answer is from my comment to a question closed as a duplicate of this one: Python from Python: restricting functionality?






            share|improve this answer


























            • The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

              – colidyre
              Sep 2 '18 at 16:01














            4












            4








            4







            I'm not sure why nobody mentions this, but Zope 2 has a thing called Python Script, which is exactly that - restricted Python executed in a sandbox, without any access to filesystem, with access to other Zope objects controlled by Zope security machinery, with imports limited to a safe subset.



            Zope in general is pretty safe, so I would imagine there are no known or obvious ways to break out of the sandbox.



            I'm not sure how exactly Python Scripts are implemented, but the feature was around since like year 2000.



            And here's the magic behind PythonScripts, with detailed documentation: http://pypi.python.org/pypi/RestrictedPython - it even looks like it doesn't have any dependencies on Zope, so can be used standalone.



            Note that this is not for safely running arbitrary python code (most of the random scripts will fail on first import or file access), but rather for using Python for limited scripting within a Python application.



            This answer is from my comment to a question closed as a duplicate of this one: Python from Python: restricting functionality?






            share|improve this answer















            I'm not sure why nobody mentions this, but Zope 2 has a thing called Python Script, which is exactly that - restricted Python executed in a sandbox, without any access to filesystem, with access to other Zope objects controlled by Zope security machinery, with imports limited to a safe subset.



            Zope in general is pretty safe, so I would imagine there are no known or obvious ways to break out of the sandbox.



            I'm not sure how exactly Python Scripts are implemented, but the feature was around since like year 2000.



            And here's the magic behind PythonScripts, with detailed documentation: http://pypi.python.org/pypi/RestrictedPython - it even looks like it doesn't have any dependencies on Zope, so can be used standalone.



            Note that this is not for safely running arbitrary python code (most of the random scripts will fail on first import or file access), but rather for using Python for limited scripting within a Python application.



            This answer is from my comment to a question closed as a duplicate of this one: Python from Python: restricting functionality?







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 2 '17 at 14:50









            Aaron Hall

            170k50296250




            170k50296250










            answered Jul 6 '12 at 9:34









            SergeySergey

            7,3352035




            7,3352035













            • The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

              – colidyre
              Sep 2 '18 at 16:01



















            • The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

              – colidyre
              Sep 2 '18 at 16:01

















            The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

            – colidyre
            Sep 2 '18 at 16:01





            The latest release of RestrictedPython is only compatible with Python 2.3, 2.4, 2.5, 2.6, and 2.7. No support for Python 3, yet.

            – colidyre
            Sep 2 '18 at 16:01











            3














            I would look into a two server approach. The first server is the privileged web server where your code lives. The second server is a very tightly controlled server that only provides a web service or RPC service and runs the untrusted code. You provide your content creator with your custom interface. For example you if you allowed the end user to create items, you would have a look up that called the server with the code to execute and the set of parameters.



            Here's and abstract example for a healing potion.



            {function_id='healing potion', action='use', target='self', inventory_id='1234'}


            The response might be something like



            {hp='+5' action={destroy_inventory_item, inventory_id='1234'}}





            share|improve this answer
























            • Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

              – Blixt
              Jun 18 '10 at 9:38











            • You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

              – Philip Tinney
              Jun 18 '10 at 10:01











            • +1 for a new way of solving the problem.

              – Noufal Ibrahim
              Jun 21 '10 at 10:45











            • This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

              – Ali
              May 27 '12 at 20:08











            • This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

              – Glyph
              Aug 16 '12 at 23:02
















            3














            I would look into a two server approach. The first server is the privileged web server where your code lives. The second server is a very tightly controlled server that only provides a web service or RPC service and runs the untrusted code. You provide your content creator with your custom interface. For example you if you allowed the end user to create items, you would have a look up that called the server with the code to execute and the set of parameters.



            Here's and abstract example for a healing potion.



            {function_id='healing potion', action='use', target='self', inventory_id='1234'}


            The response might be something like



            {hp='+5' action={destroy_inventory_item, inventory_id='1234'}}





            share|improve this answer
























            • Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

              – Blixt
              Jun 18 '10 at 9:38











            • You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

              – Philip Tinney
              Jun 18 '10 at 10:01











            • +1 for a new way of solving the problem.

              – Noufal Ibrahim
              Jun 21 '10 at 10:45











            • This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

              – Ali
              May 27 '12 at 20:08











            • This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

              – Glyph
              Aug 16 '12 at 23:02














            3












            3








            3







            I would look into a two server approach. The first server is the privileged web server where your code lives. The second server is a very tightly controlled server that only provides a web service or RPC service and runs the untrusted code. You provide your content creator with your custom interface. For example you if you allowed the end user to create items, you would have a look up that called the server with the code to execute and the set of parameters.



            Here's and abstract example for a healing potion.



            {function_id='healing potion', action='use', target='self', inventory_id='1234'}


            The response might be something like



            {hp='+5' action={destroy_inventory_item, inventory_id='1234'}}





            share|improve this answer













            I would look into a two server approach. The first server is the privileged web server where your code lives. The second server is a very tightly controlled server that only provides a web service or RPC service and runs the untrusted code. You provide your content creator with your custom interface. For example you if you allowed the end user to create items, you would have a look up that called the server with the code to execute and the set of parameters.



            Here's and abstract example for a healing potion.



            {function_id='healing potion', action='use', target='self', inventory_id='1234'}


            The response might be something like



            {hp='+5' action={destroy_inventory_item, inventory_id='1234'}}






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jun 18 '10 at 9:30









            Philip TinneyPhilip Tinney

            1,8361719




            1,8361719













            • Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

              – Blixt
              Jun 18 '10 at 9:38











            • You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

              – Philip Tinney
              Jun 18 '10 at 10:01











            • +1 for a new way of solving the problem.

              – Noufal Ibrahim
              Jun 21 '10 at 10:45











            • This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

              – Ali
              May 27 '12 at 20:08











            • This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

              – Glyph
              Aug 16 '12 at 23:02



















            • Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

              – Blixt
              Jun 18 '10 at 9:38











            • You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

              – Philip Tinney
              Jun 18 '10 at 10:01











            • +1 for a new way of solving the problem.

              – Noufal Ibrahim
              Jun 21 '10 at 10:45











            • This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

              – Ali
              May 27 '12 at 20:08











            • This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

              – Glyph
              Aug 16 '12 at 23:02

















            Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

            – Blixt
            Jun 18 '10 at 9:38





            Yeah, my game already has an RPC API, I just want certain events, when a player is playing, to be more dynamic... So scripting feels like a natural choice :) I guess that worst case scenario is that I'll have to make a simple interpreter myself.

            – Blixt
            Jun 18 '10 at 9:38













            You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

            – Philip Tinney
            Jun 18 '10 at 10:01





            You wouldn't necessarily need to create a complex API. You could do something as simple as serializing a data structure passing it to the RPC server (Running Python), which would load the structure and run the end user code (Python). The end user modifies it and sends it back. Regardless, you are going to have to create guidelines as to how to access your data.

            – Philip Tinney
            Jun 18 '10 at 10:01













            +1 for a new way of solving the problem.

            – Noufal Ibrahim
            Jun 21 '10 at 10:45





            +1 for a new way of solving the problem.

            – Noufal Ibrahim
            Jun 21 '10 at 10:45













            This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

            – Ali
            May 27 '12 at 20:08





            This is in my opinion the best approach, since it is reducing the problem to the app engine's sandbox capibility: At worst, the code can mess up the data in the dummy application that just runs the python code. I don't even think you would need any persistent data for that app.

            – Ali
            May 27 '12 at 20:08













            This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

            – Glyph
            Aug 16 '12 at 23:02





            This is really a non-answer. What does "tightly controlled" mean? You have to choose a sandboxing technology to restrict access on that server.

            – Glyph
            Aug 16 '12 at 23:02











            2














            Hmm. This is a thought experiment, I don't know of it being done:



            You could use the compiler package to parse the script. You can then walk this tree, prefixing all identifiers - variables, method names e.t.c. (also has|get|setattr invocations and so on) - with a unique preamble so that they cannot possibly refer to your variables. You could also ensure that the compiler package itself was not invoked, and perhaps other blacklisted things such as opening files. You then emit the python code for this, and compiler.compile it.



            The docs note that the compiler package is not in Python 3.0, but does not mention what the 3.0 alternative is.



            In general, this is parallel to how forum software and such try to whitelist 'safe' Javascript or HTML e.t.c. And they historically have a bad record of stomping all the escapes. But you might have more luck with Python :)






            share|improve this answer



















            • 1





              Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

              – Lukas Boersma
              Feb 1 '18 at 15:23
















            2














            Hmm. This is a thought experiment, I don't know of it being done:



            You could use the compiler package to parse the script. You can then walk this tree, prefixing all identifiers - variables, method names e.t.c. (also has|get|setattr invocations and so on) - with a unique preamble so that they cannot possibly refer to your variables. You could also ensure that the compiler package itself was not invoked, and perhaps other blacklisted things such as opening files. You then emit the python code for this, and compiler.compile it.



            The docs note that the compiler package is not in Python 3.0, but does not mention what the 3.0 alternative is.



            In general, this is parallel to how forum software and such try to whitelist 'safe' Javascript or HTML e.t.c. And they historically have a bad record of stomping all the escapes. But you might have more luck with Python :)






            share|improve this answer



















            • 1





              Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

              – Lukas Boersma
              Feb 1 '18 at 15:23














            2












            2








            2







            Hmm. This is a thought experiment, I don't know of it being done:



            You could use the compiler package to parse the script. You can then walk this tree, prefixing all identifiers - variables, method names e.t.c. (also has|get|setattr invocations and so on) - with a unique preamble so that they cannot possibly refer to your variables. You could also ensure that the compiler package itself was not invoked, and perhaps other blacklisted things such as opening files. You then emit the python code for this, and compiler.compile it.



            The docs note that the compiler package is not in Python 3.0, but does not mention what the 3.0 alternative is.



            In general, this is parallel to how forum software and such try to whitelist 'safe' Javascript or HTML e.t.c. And they historically have a bad record of stomping all the escapes. But you might have more luck with Python :)






            share|improve this answer













            Hmm. This is a thought experiment, I don't know of it being done:



            You could use the compiler package to parse the script. You can then walk this tree, prefixing all identifiers - variables, method names e.t.c. (also has|get|setattr invocations and so on) - with a unique preamble so that they cannot possibly refer to your variables. You could also ensure that the compiler package itself was not invoked, and perhaps other blacklisted things such as opening files. You then emit the python code for this, and compiler.compile it.



            The docs note that the compiler package is not in Python 3.0, but does not mention what the 3.0 alternative is.



            In general, this is parallel to how forum software and such try to whitelist 'safe' Javascript or HTML e.t.c. And they historically have a bad record of stomping all the escapes. But you might have more luck with Python :)







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jun 18 '10 at 8:35









            WillWill

            47.8k32139207




            47.8k32139207








            • 1





              Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

              – Lukas Boersma
              Feb 1 '18 at 15:23














            • 1





              Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

              – Lukas Boersma
              Feb 1 '18 at 15:23








            1




            1





            Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

            – Lukas Boersma
            Feb 1 '18 at 15:23





            Please don't do that. There are many ways of executing arbitrary code without directly using the packages you want to check for. For example, you could walk over the entries of ().__class__.__base__.__subclasses__() and search for the "code" entry, which then can be used to run code from a string. If you take normal Python code and check it for malicious things, you can never be sure that you did not forget to check for something that can be exploited.

            – Lukas Boersma
            Feb 1 '18 at 15:23











            2














            You'll probably be interested in the Python language services section of the libref for writing your own parser.






            share|improve this answer




























              2














              You'll probably be interested in the Python language services section of the libref for writing your own parser.






              share|improve this answer


























                2












                2








                2







                You'll probably be interested in the Python language services section of the libref for writing your own parser.






                share|improve this answer













                You'll probably be interested in the Python language services section of the libref for writing your own parser.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 18 '10 at 8:35









                Ignacio Vazquez-AbramsIgnacio Vazquez-Abrams

                579k10210581159




                579k10210581159























                    0














                    I think your best bet is going to be a combination of the replies thus far.



                    You'll want to parse and sanitise the input - removing any import statements for example.



                    You can then use Messa's exec sample (or something similar) to allow the code execution against only the builtin variables of your choosing - most likely some sort of API defined by yourself that provides the programmer access to the functionality you deem relevant.






                    share|improve this answer
























                    • I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:22











                    • Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

                      – Blixt
                      Jun 18 '10 at 9:28











                    • You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:36
















                    0














                    I think your best bet is going to be a combination of the replies thus far.



                    You'll want to parse and sanitise the input - removing any import statements for example.



                    You can then use Messa's exec sample (or something similar) to allow the code execution against only the builtin variables of your choosing - most likely some sort of API defined by yourself that provides the programmer access to the functionality you deem relevant.






                    share|improve this answer
























                    • I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:22











                    • Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

                      – Blixt
                      Jun 18 '10 at 9:28











                    • You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:36














                    0












                    0








                    0







                    I think your best bet is going to be a combination of the replies thus far.



                    You'll want to parse and sanitise the input - removing any import statements for example.



                    You can then use Messa's exec sample (or something similar) to allow the code execution against only the builtin variables of your choosing - most likely some sort of API defined by yourself that provides the programmer access to the functionality you deem relevant.






                    share|improve this answer













                    I think your best bet is going to be a combination of the replies thus far.



                    You'll want to parse and sanitise the input - removing any import statements for example.



                    You can then use Messa's exec sample (or something similar) to allow the code execution against only the builtin variables of your choosing - most likely some sort of API defined by yourself that provides the programmer access to the functionality you deem relevant.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jun 18 '10 at 8:54









                    GlenjaminGlenjamin

                    3,13241723




                    3,13241723













                    • I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:22











                    • Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

                      – Blixt
                      Jun 18 '10 at 9:28











                    • You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:36



















                    • I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:22











                    • Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

                      – Blixt
                      Jun 18 '10 at 9:28











                    • You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

                      – Noufal Ibrahim
                      Jun 18 '10 at 9:36

















                    I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

                    – Noufal Ibrahim
                    Jun 18 '10 at 9:22





                    I totally concur. This does seem to be the right way to go. I'm sceptical about how much you can accomplish though.

                    – Noufal Ibrahim
                    Jun 18 '10 at 9:22













                    Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

                    – Blixt
                    Jun 18 '10 at 9:28





                    Hmm, which cases would I need to sanitize the input using Messa's method? I've tried to import modules or otherwise access external values, but it doesn't seem easy. Import statements etc. are already disabled since no built-in functions are available (the import statement calls the __import__ function).

                    – Blixt
                    Jun 18 '10 at 9:28













                    You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

                    – Noufal Ibrahim
                    Jun 18 '10 at 9:36





                    You should try to fish out the thread on Python-dev discussing this. It had everyone break the sandbox. Lots of ways there. I can't find it.

                    – Noufal Ibrahim
                    Jun 18 '10 at 9:36











                    0














                    You'll find some ideas in this wiki page, but it does not look like it can be done easily.






                    share|improve this answer


























                    • Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

                      – Blixt
                      Jun 18 '10 at 8:32
















                    0














                    You'll find some ideas in this wiki page, but it does not look like it can be done easily.






                    share|improve this answer


























                    • Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

                      – Blixt
                      Jun 18 '10 at 8:32














                    0












                    0








                    0







                    You'll find some ideas in this wiki page, but it does not look like it can be done easily.






                    share|improve this answer















                    You'll find some ideas in this wiki page, but it does not look like it can be done easily.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 27 '18 at 19:44









                    coelhudo

                    2,13262948




                    2,13262948










                    answered Jun 18 '10 at 8:31









                    Mad ScientistMad Scientist

                    11.1k96285




                    11.1k96285













                    • Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

                      – Blixt
                      Jun 18 '10 at 8:32



















                    • Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

                      – Blixt
                      Jun 18 '10 at 8:32

















                    Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

                    – Blixt
                    Jun 18 '10 at 8:32





                    Yup, I read that, but none of the solutions were pure Python. I guess running true Python sandboxed might be over-kill anyways, but I would like a Python-like scripting language.

                    – Blixt
                    Jun 18 '10 at 8:32


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f3068139%2fhow-can-i-sandbox-python-in-pure-python%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    Refactoring coordinates for Minecraft Pi buildings written in Python