Question: We recently had issues with people messing around inside our system. To prevent code injections within my python code, I implemented the following `if` block:

```
#! /usr/bin/python3
#-*- coding:utf-8 -*-
def main():
    print("Your interactive Python shell!")
    text = input('>>> ')
    for keyword in ['eval', 'exec', 'import', 'open', 'os', 'read', 'system', 'write']:
        if keyword in text:
            print("You are not allowed to do this!")
            return;
    else:
        exec(text)
        print('Executed your code!')
if __name__ == "__main__":
    main()

```

A few (user) people can run this python file with sudo rights inside our Ubuntu system. I know this sounds like a security hole, but I don't see any possibility to escape from this. Is there any possibility to inject inside my code block? Do you have any tips to prevent code injections?

Answer: 
The problem I see with your blacklist is that in Python, one could write Python code that generates additional Python code, and then run the additional code. So one could generate the word 'eval' from inside of a program that itself doesn't contain the word. Part of the problem is the dynamism of Python itself, whereas a more strongly typed, static language might be safer.

The Computer Science Theory way of accepting a valid string is by constructing a grammar, and then using a grammar parser.

<https://en.wikipedia.org/wiki/Formal_grammar>

You'd need to understand how grammar parsers work in order to construct one.
However, in this case your grammar parser would be a subset of python's grammar parser itself, so it would be a lot of work, if you had unlimited resources I'd go for it but otherwise don't pick this solution.
I wanted to suggest the approach to set `__builtins__` to `{}` but **even this is not safe**

```

def myfunc(a, b):
    return a + b

global_namespace = {"__builtins__": {}, "myfunc": myfunc}
exec(yourstring, global_namespace, {})

```

This disables all builtin keywords, allows only the explicitly passed globals (in this example `myfunc`) and no locals.

You have to declare explicitly all builtin, global, local functions / objects that you want to allow.

**However**

in above example one could escape with
`object.__globals__["__builtins__"].print("I escaped")` (Thanks @user236968 for pointing this out)

So the only thing that seems to be safe is to disable all builtins, globals and locals with

```
global_namespace = {"__builtins__": {}}
exec(yourstring, global_namespace, {})

```

But perhaps even there could be a loop hole.

As others pointeds out. Probably the only safe way is to not use
`exec` and `eval` but to implement a parser and then use `eval` (but your `parse` must be watertight) or to use you rown parser and own interpreter