Search code examples
pythonsecurityflaskcode-injectionkeyword-argument

Is it possible to inject python code in Kwargs and how could I prevent this user input


I'm at the moment in the middle of writing my Bachelor thesis and for it creating a database system with Postgres and Flask. To ensure the safety of my data, I was working on a file to prevent SQL injections, since a user should be able to submit a string via Http request. Since most of my functions which I use to analyze the Http request use Kwargs and a dict based on JSON in the request I was wondering if it is possible to inject python code into those kwargs. And If so If there are ways to prevent that.

To make it easier to understand what I mean, here are some example requests and code:

def calc_sum(a, b):
    c = a + b
    return c


@app.route(/<target:string>/<value:string>)
def handle_request(target,value):
    if target == 'calc_sum':
        cmd = json.loads(value)
        calc_sum(**cmd)

example Request:

Normal   : localhost:5000/calc_sum/{"a":1, "b":2}
Injected : localhost:5000/calc_sum/{"a":1, "b:2 ): print("ham") def new_sum(a=1, b=2):return a+b":2 }

Since I'm not near my work, where all my code is I'm unable to test it out. And to be honest that my code example would work. But I hope this can convey what I meant.

I hope you can help me, or at least nudge me in the right direction. I've searched for it, but all I can find are tutorials on "who to use kwargs".

Best regards.


Solution

  • Yes you, but not in URL, try to use arguments like these localhost:5000/calc_sum?func=a+b&a=1&b=2

    and to get these arguments you need to do this in flask

    @app.route(/<target:string>)
    def handle_request(target):
       if target == 'calc_sum':
           func= request.args.get('func')
           a = request.args.get('a')
           b = request.args.get('b')
           result = exec(func)
    

    exec is used to execute python code in strings