How to limit access to Flask for a single IP address? - python

I'm developing a website using the Python Flask framework and I now do some devving, pushing my changes to a remote dev server. I set this remote dev server up to serve the website publically using app.run(host='0.0.0.0').
This works fine, but I just don't want other people to view my website yet. For this reason I somehow want to whitelist my ip so that the dev server only serves the website to my own ip address, giving no response, 404's or some other non-useful response to other ip addresses. I can of course set up the server to use apache or nginx to actually serve the website, but I like the automatic reloading of the website on code changes for devving my website
So does anybody know of a way to do this using the built in Flask dev server? All tips are welcome!

Using just the features of Flask, you could use a before_request() hook testing the request.remote_addr attribute:
from flask import abort, request
#app.before_request
def limit_remote_addr():
if request.remote_addr != '10.20.30.40':
abort(403) # Forbidden
but using a firewall rule on the server is probably the safer and more robust option.
Note that the Remote_Addr can be masked if there is a reverse proxy in between the browser and your server; be careful how you limit this and don't lock yourself out. If the proxy lives close to the server itself (like a load balancer or front-end cache), you can inspect the request.access_route list to access the actual IP address. Do this only if remote_addr itself is a trusted IP address too:
trusted_proxies = ('42.42.42.42', '82.42.82.42', '127.0.0.1')
def limit_remote_addr():
remote = request.remote_addr
route = list(request.access_route)
while remote in trusted_proxies:
remote = route.pop()
if remote != '10.20.30.40':
abort(403) # Forbidden

This IPTABLES/Netfilter rule will attend your need, dropping all incoming traffic, EXCEPT the traffic originated from your_ip_address to port 80:
$ /sbin/iptables -A INPUT -s ! your_ip_address --dport 80 -j DROP
Here's something presented on many forums, which allows localhost traffic + external access to your Flask app from your_ip_address, but reject all traffic from other IP address:
$ /sbin/iptables -A INPUT -i lo -j ACCEPT
$ /sbin/iptables -A INPUT -s your_ip_address --dport 80 -j DROP
$ /sbin/iptables -A INPUT --dport 80 -j REJECT
Although you can easily achieve the expected result via Flask (as pointed out on the elected answer), this kind of issue should be treated at the Network Layer of the Operating System. Considering that you're using a Nix-like OS, you can deny/allow incoming connections using Netfilter via IPTABLES, with rules like these.
Incoming traffic/packets, firstly, they pass through the analysis of the Kernel of your Operating System. To deny/allow traffic, from any source to specific ports, it's a job for the Firewall of the Operating System, on the Network Layer of its Kernel. If you don't have a Firewall running on your server, you should configure it.
Here's a takeaway:
Traffic must be treated at the Network Layer of your Operating System. Do not let application handle this task, at least on a Production environment. No one will do a best job regarding this task, than the Kernel of you Operating System (hoping that you're using a Nix-like OS). The Linux Kernel and its modules (Netfilter) are much more reliable, competent and effective to treat these kind of tasks.

I found this very helpful, but there is an easier way to do this if you have multiple ip address.
trusted_ips = ['42.42.42.42', '82.42.82.42', '127.0.0.1']
#app.before_request
def limit_remote_addr():
if request.remote_addr not in trusted_ips:
abort(404) # Not Found
This will check your trusted ip list and return "404 - Not Found" if the remote ip is not in the list.
You can also block specific ip by changing a few things
bad_ips = ['42.42.42.42', '82.42.82.42', '127.0.0.1']
#app.before_request
def limit_remote_addr():
if request.remote_addr in bad_ips:
abort(404) # Not Found
Same thing but blocks the ips in your bad_ips list

Related

How to expose Docker terminal to the internet?

I am creating an online IDE for different languages. So my approach to the same is to spin up a docker container from my DJango app once a user runs his code, but the problem is how do I expose the terminal of the docker container to the internet and make it accessible via the browser? I am planning to use xterm.js for the frontend of the terminal but am unable to connect to it.
Any form of insight is appreciable.
You can you an reverse-proxy with NGINX to point to your localIP:<container_port>, and then modify with your domain name.
As this exemple below:
location /some/path/ {
proxy_pass http://www.example.com/link/;
}
Adding some links to help you.
enter link description here
Also you can use 'Nginx Proxy Manager'
Short answer:
Your application uses a port to access it (for example, you use 127.0.0.1:8080 or 192.168.1.100:3000).
127.0.0.1 means the computer you are using right now, 192.168.1.100 is a computer inside the 192.168.1.0 network. (Your LAN)
You must create (on your router) access from the internet to your application.
For exemple, if your public IP address is 123.245.123.245, you need to use an external port (ex: 80), and map it to your internal address and port (ex: 192.168.1.100:3000)
the URL 123.245.123.245:80 will redirect to the website on 192.168.1.100:3000.
On the short term, this is the easiest solution.
For the long term, you should try using a Reverse Proxy.
It's a program that will (depending on the domain) redirect to sites inside your network and adding encryption in the requests (if possible).
Check this link : doc

Locally hosted Django project for long-term use in local network

I am currently implementing a Django web application, which will be used only locally but long-term. I already managed to start the Django server on my local machine using python manage 0.0.0.0:myport and I am able to connect from any mobile device using MyLocalIPv4:myport.
In best case I only want to start the Django server once, establish a connection between a mobile device and the web app and let the web app run for an undefined long time on that mobile device
Now my assumption is, that MyLocalIPv4 will be changing over time as it is a dynamic IP address, which will force the user (or even worse myself) to look up the new IP address and re-establish the connection.
My question are: Do you know any mechanisms on how I can avoid this type of behaviour using another (maybe static) referral to the web app ? What do you think about this web application in term of security issues ?
DNS is the way to go. What you want is a (internal) domain that would map to your computer IP address.
There are many ways you can achieve that but I suggest going with whatever tools you have available. I assume that for your home network you're using some sort of a consumer-grade home router with wireless access point. Very often this type of hardware offers some way to "map" the hostname of a machine to its internal-network IP address.
For example, at home I'm using a RT-AC1200G+ router, which runs an internal DNS server and maps hostnames of clients of my network to their IP:
$ dig +short #192.168.1.2 samu-pc
192.168.1.70
$ ifconfig |grep 192.168.1.70
inet 192.168.1.70 netmask 255.255.255.0 broadcast 192.168.1.255
Alternatively, one of the easier solutions would be to ensure your IP does not change. You could assign a static IP to your django-server machine, OR if you want to continue using DHCP - use your routers functions to make a static assignment to a specific, static IP address using your network card's MAC address.
Disclaimer: There are other, more "professional" ways of solving service discovery within a network, but I would consider them overkill to your home network setup. Also, if you care about security, you should consider running the django app behind a reverse proxy with HTTPs on the front, just to ensure nobody in your internal network is trying to do something nasty.

Why host http server needs to specify the IP on which it is hosting?

I am hosting a http server on Python using BaseHTTPServer module.
I want to understand why it's required to specify the IP on which you are hosting the http server, like 127.0.0.1/192.168.0.1 or whatever. [might be a general http server concept, and not specific to Python]
Why can't it be like anybody who knows the IP of the machine could connect to the http server?
I face problems in case when my http server is connected to two networks at the same time, and I want to serve the http server on both the networks. And often my IP changes on-the-fly when I switch from hotspot mode on the http server machine, to connecting to another wifi router.
You must specify the IP address of the server, mainly because the underlying system calls for listening on a socket requires it. At a lower level you declare what pair (IP address, port) you want to use, listen on it and accept incoming connexions.
Another reason is that professional grade server often have multiple network interfaces and multiple IP addresses, and some services only need to listen on some interface addresses.
Hopefully, there are special addresses:
localhost or 127.0.0.1 is the loopback address, only accessible from local machine. It is currently used for tests of local services
0.0.0.0 (any) is a special address used to declare that you want to listen to all the local interfaces. I think that it is what you want here.
Try running it on 0.0.0.0, this accepts connections from all interfaces. Explicitly specifying the IP is a good practice in general (load balancing, caching servers, security, internal netwrok-only micro services, etc), but judging by your story this is not a production server, but some internal LAN application.

Django runserver bound to 0.0.0.0, how can I get which IP took the request?

I'm running a temporary Django app on a host that has lots of IP addresses. When using manage.py runserver 0.0.0.0:5000, how can the code see which of the many IP addresses of the machine was the one actually hit by the request, if this is even possible?
Or to put it another way:
My host has IP addresses 10.0.0.1 and 10.0.0.2. When runserver is listening on 0.0.0.0, how can my application know whether the user hit http://10.0.0.1/app/path/etc or http://10.0.0.2/app/path/etc?
I understand that if I was doing it with Apache I could use the Apache environment variables like SERVER_ADDR, but I'm not using Apache.
Any thoughts?
EDIT
More information:
I'm testing a load balancer using a small Django app. This app is listening on a number of different IPs and I need to know which IP address is hit for a request coming through the load balancer, so I can ensure it is balancing properly.
I cannot use request.get_host() or the request.META options, as they return what the user typed to hit the load balancer.
For example: the user hits http://10.10.10.10/foo and that will forward the request to either http://10.0.0.1/foo or http://10.0.0.2/foo - but request.get_host() will return 10.10.10.10, not the actual IPs the server is listening on.
Thanks,
Ben
request.get_host()
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.get_host
but be aware this can be cheated so don't relay your security on it.
If users are seeing your machine under same address I am not sure if this is possible via runserver (it is supposed to be simple development tool).
Maybe you could use nginx?
Or if this is only for testing do something like:
for i in 1 2 3 4 5; do manage.py runserver 10.0.0.$i:5000; done
and then sys.args[2] is your address
If your goal is to ensure the load balancer is working correctly, I suppose it's not an absolute requirement to do this in the application code. You can use a network packet analyzer that can listen on a specific interface (say, tcpdump -i <interface>) and look at the output.

Redirecting traffic to other webserver

Here is my setup: I have a Python webserver (written myself) that listens on port 80 and also have the Transmission-daemon (bittorrent client) that provides a webUI on port 9101. (running on Linux)
I can access both webservers locally without problems, but now would like to access them externally also. My issue is that I would prefer not to have to open extra ports on my firewall to access the Transmission webUI. Is it possible to within the python webserver to redirect some traffic to the appropriate port.
So for example:
http: //mywebserver/index.html -> served by the Python webserver
http: //mywebserver/transmission.html -> redirected to transmission (which is currently http: //localhost:9101)
Thanks
I found my answer: a reverse proxy. It will take care of the routing to the correct port based on the URL. I now just have to select the right one there are so many (NginX, pound, lighttd etc...)
Thanks anyway.
Return an http response with status code 300, see this

Categories