flaskbandit

What is the issue with binding to all interfaces and what are the alternatives?


I've recently seen bandit complaining about B104:

Binding to all network interfaces can potentially open up a service to traffic on unintended interfaces, that may not be properly documented or secured. This plugin test looks for a string pattern “0.0.0.0” that may indicate a hardcoded binding to all network interfaces.

>> Issue: Possible binding to all interfaces.
   Severity: Medium   Confidence: Medium
   Location: ./examples/binding.py:4
3   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
4   s.bind(('0.0.0.0', 31137))
5   s.bind(('192.168.0.1', 8080))

What does it mean to "open up a service to traffic on unintended interfaces"?

I've seen this for a Flask application with app.run(host="0.0.0.0"). What should one write instead?

(As a sidenote: This is not used in production. This is mainly for simply testing during development. But I'm uncertain if gunicorn might have the same issue with a similar configuration)


Solution

  • When binding to '0.0.0.0' you accept incoming connections from anywhere. This is something you would do in production when your code is tested and your project is "secured" (for example against SQL injections or other such nasty attacks).

    Whenever you're not ready for production or when you're not intentionally accepting incoming connections from anywhere, there should be a safe default. Usually this is '127.0.0.1' or 'localhost', thus only accepting incoming connections from your local machine. This doesn't secure your code from SQL injections but it prevents others from targeting your code and executing SQL injections against your project.

    Please note that the test doesn't complain about binding to 0.0.0.0 in general but instead complains about unintendedly binding to 0.0.0.0 (and therefore probably the entire world). Thus, any hardcoded reference of 0.0.0.0 should be avoided (to create the above-mentioned safe defaults).

    As for the alternatives you can use 127.0.0.1 or localhost while you develop or you can use local network interfaces to enable access from other machines on your local network. Using your network interface would allow you to build and host a web application on your computer and testing the results on your phone if they are connected to the same WiFi.