473,574 Members | 2,459 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 1044

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

Similar topics

3
2155
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
2566
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...
3
2281
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...
2
1237
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...
188
7135
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
1906
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
3460
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...
7
1189
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...
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...
0
7797
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...
0
8041
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. ...
0
8225
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7806
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...
0
6440
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...
1
5611
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5296
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...
0
3748
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2233
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.