On Thu, 21 Jul 2005 03:53 am, Sami Hangaslammi wrote: > On 7/20/05, Andre Roberge <andre.roberge@xxxxxxxxx> wrote: > > How about doing something like the following: > > > > def isFileSafe(file_to_import): > > ....unsafe = "".join(contents) > > ....unsafe = unsafe.replace("(", " (") > > ....unsafe = unsafe.split() > > ....bad_keywords = ["chr", "exec", "eval", "input", "raw_input", > > "import", "file", "open"] > > ....for word in bad_keywords: > > ........if word in safe_list: > > ............return False > > ....return True > > > > [add in a regular expression search for any "magic" python "word" of the > > form __aName__, i.e. lead and followed by two underscores -- something I > > can't do on the spot :-(] > > > > and only allow importing levels (through execfile()) if it's deemed to be > > safe? > > I still wouldn't trust string analysis, since there are so many sneaky > ways to write something. E.g. > > getattr(getattr(globals()["\x5f\x5f\x62\x75\x69\x6c\x74\x69\x6e\x73\x5f\x5f >"], "\x5f\x5f\x69\x6d\x70\x6f\x72\x74\x5f\x5f")("\x6f\x73"), > "\x73\x79\x73\x74\x65\x6d")("oops") > > While the above is reliant on __builtins__ and would be stopped by the > word in safe_list check, I'm pretty sure that someone who knows all > the tricks could get past string tests. The bytecodes aren't that much > more difficult to analyze and they are, IMHO, easier to make > foolproof. Restricting the namespace is an easy option: exec "bad code" in {'__builtins__': {}} Zope has a working restricted execution environment. Richard
Attachment:
pgpZTO1JQZo5H.pgp
Description: PGP signature