Finding or building a python security profiler

Viewed 200

I want a security profiler for python. Specifically, I want something that will take as input a python program and tell me if the program tries to make system calls, read files, or import libraries. If such a security profiler exists, where can I find it? If no such thing exists and I were to write one myself, where could I have my profiler 'checked' (that is, verified that it works).

If you don't find this question appropriate for SO, let me know if there is another SE site I can post this on, or if possible, how I can change/rephrase my question. Thanks

2 Answers

Usually, python uses an interpreter called CPython. It is hard to say for python code by itself if it opens files or does something special, due a lot of python libraries and interpreter itself are written in C, and system calls/libc calls can happen only from there. Also python syntax by itself can be very obscure.

So, by answering your suspect: I suspect this would need specific knowledge of the python programming language, it does not look like that, due it is about C language.

You can think it is possible to patch CPython itself. Well it is not correct too as I guess. A lot of shared libraries use C/C++ code as CPython itself. Tensorflow, for example.

Going further, I guess it is possible to do following things:

  • patch the compiler which compiles C/C++ code for CPython/modules, which is hard I guess.
  • just use an usual profiler, and trace which files, directories and calls are used by python itself for operation, and whitelist them, due they are needed, which is the best option by my opinion (AppArmor for example).
  • maybe you can be interested in the patching of CPython itself, where it is possible to hook needed functions and calls to external C libraries, but it can be annoying due you will have to revise every added library to your project, and also C code is often used for performance (e.g. json module), which doesn't open too much things.

Python is not an easy language to be sandboxed. Example:

x = [x for x in [].__class__.__base__.__subclasses__() if x.__name__ == 'ca'+'tch_warnings'][0].__init__

x.__getattribute__("__globals__")['__builtins__']['eval']("__import__('os').system('ls')")

For every N regexes/patterns there are N+1 ways to bypass it. Not to mention people could also create functions from raw python bytecode using types.FunctionType. The easiest way might be running the script inside nsjail and seing if it attempts to perform any suspicious activity.

EDIT: In theory there is PEP 578 with audit hooks, but in reality they are trivially bypassed.

Related