473,786 Members | 2,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Safe eval critique (homework done)

Hi guys!

I know this subject has been beaten to death and I am not going to
whine about lacking features for proper restricted execution in the
Python runtime. It's the OS job, I get it.

Anyways, I thought about using a restricted *subset* of the language
for simple configuration scripts and storing data in a user-friendly
way. I'm fully aware about the dangers of introducing "eval" into the
picture so I took different route and hacked together the following
module:

http://www.zafar.se/dump/safe.py

Could some of you perhaps give some feedback on the implementation?

By default the module imposes the following restrictions:

* importing modules is disabled
* unsafe builtins are disabled
* timeout limit ('while 1:pass' can't block forever)
* getattr, setattr, delattr are disabled
* lowlevel attributes like __subclasses__ are disabled
* enviroment passed to 'exec' can't contain modules or builtins

Is there some obvious security hole I'm missing?
How easily could one compromise the restricted enviroment?

Thanks,
Babar K. Zafar

PS. Here are some simple unittests to give you a feel for the module:

class TestSafeEval(un ittest.TestCase ):
def test_builtin(se lf):
# attempt to access a unsafe builtin
self.assertRais es(SafeEvalExce ption,
safe_eval, "open('test.txt ', 'w')")

def test_getattr(se lf):
# attempt to get arround direct attr access
self.assertRais es(SafeEvalExce ption, \
safe_eval, "getattr(in t, '__abs__')")

def test_func_globa ls(self):
# attempt to access global enviroment where fun was defined
self.assertRais es(SafeEvalExce ption, \
safe_eval, "def x(): pass; print x.func_globals" )

def test_lowlevel(s elf):
# lowlevel tricks to access 'object'
self.assertRais es(SafeEvalExce ption, \
safe_eval, "().__class__.m ro()[1].__subclasses__ ()")

def test_timeout_ok (self):
# attempt to exectute slow code which finishes within timelimit
def test(): time.sleep(2)
env = {'test':test}
safe_eval("test ()", env, timeout_secs = 5)

def test_timeout_ex ceed(self):
# attempt to exectute code which never teminates
self.assertRais es(SafeEvalExce ption, \
safe_eval, "while 1: pass")

def test_invalid_co ntext(self):
# can't pass an enviroment with modules or builtins
env = {'f' : __builtins__.op en, 'g' : time}
self.assertRais es(SafeEvalExce ption, \
safe_eval, "print 1", env)

def test_callback(s elf):
# modify local variable via callback
self.value = 0
def test(): self.value = 1
env = {'test':test}
safe_eval("test ()", env)
self.assertEqua l(self.value, 1)

May 27 '06 #1
0 1056

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2165
by: Erwin Moller | last post by:
Hi all, Situation: I need arbitrary calculations to be done on certain columns in a table. The formula's are dynamical. I will replace certain values in the formulastring with their current values in the colums. So I'll end up with a formula like: (col2*col4)/10 * (cos(col5) / sin(col6))
42
2603
by: Irmen de Jong | last post by:
Pickle and marshal are not safe. They can do harmful things if fed maliciously constructed data. That is a pity, because marshal is fast. I need a fast and safe (secure) marshaler. Is xdrlib the only option? I would expect that it is fast and safe because it (the xdr spec) has been around for so long. Or are there better options (perhaps 3rd party libraries)?
3
2302
by: Rv5 | last post by:
I have an assignment due mid next week that I have completed. I was hoping someone could take a look at the code and tell me what they think of the style. Id like to know if this is good code that I can be proud of or if my technique still needs some work. What can be improved? I created an htm page that first lists the assignment, and under that is my code. I think the code is good, but Ive thought that before... ...
2
1245
by: Adrian | last post by:
Hi all, A while ago while I was doing a part time c++ course at uni and we where asked to write a code solution to a little problem. The idea being that you can type in either a name or a mark and return all results that match what you typed. The code had to include a doubly linked binary tree. (sorry dont have the original problem description to hand). My result is below, I know it is way over engineered for the problem at hand (but...
188
7255
by: christopher diggins | last post by:
I have posted a C# critique at http://www.heron-language.com/c-sharp-critique.html. To summarize I bring up the following issues : - unsafe code - attributes - garbage collection - non-deterministic destructors - Objects can't exist on the stack - Type / Reference Types
39
1942
by: Eric | last post by:
There is a VB.NET critique on the following page: http://www.vb7-critique.741.com/ for those who are interested. Feel free to take a look and share your thoughts. Cheers, Eric. Ps: for those on comp.programming, this may be off topic, but I've posted there because the critique was part of a discussion in that group.
2
3474
by: Philipp Lenssen | last post by:
The question in short: how do I make eval() safe? The background: At questml.com I'm offering a way to create choose- your-own-adventures in a special XML dialect. There's a several-years- old Windows-based editor for QML but I'm pondering offering a web application for this as well. Part of QML are programming constructs which evaluate states like e.g. <if check=" or ">...</if><else>...</else> These support certain functions,...
7
1196
by: bvdp | last post by:
Is there a simple/safe expression evaluator I can use in a python program. I just want to pass along a string in the form "1 + 44 / 3" or perhaps "1 + (-4.3*5)" and get a numeric result. I can do this with eval() but I really don't want to subject my users to the problems with that method. In this use I don't need python to worry about complex numbers, variables or anything else. Just do the math on a set of values. Would eval() with...
7
242
by: bvdp | last post by:
I'm finding my quest for a safe eval() quite frustrating :) Any comments on this: Just forget about getting python to do this and, instead, grab my set of values (from a user supplied text file) and call an external program like 'bc' to do the dirty work. I think that this would avoid someone from embedding os.system("rm ...") in what I thought would be a math expression and having it maybe do damage? Perhaps I'm getting too paranoid in...
0
9650
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8992
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6748
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.