How to set up IP whitelist based on nginx ingress

  • 本文有使用到 Kubernetes, nginx ingressCloudflare

Installation

使用 helm 3 安裝 nginx ingress, 這裡就直接演示 Makefile 了。

1
2
3
4
5
6
7
# Makefile
NS=ingress-nginx
APP_NAME=ingress-nginx

.PHONY: install
install:
@helm upgrade --install --namespace=$(NS) $(APP_NAME) ingress-nginx/ingress-nginx -f values.yaml

Configuration

兩個重要的設定

1
2
3
4
5
6
7
8
9
10
11
12
13
controller:
config:
# 設定 Cloudflare 的 IPs
proxy-real-ip-cidr: "173.245.48.0/20,103.21.244.0/22,103.22.200.0/22,103.31.4.0/22,141.101.64.0/18,108.162.192.0/18,190.93.240.0/20,188.114.96.0/20,197.234.240.0/22,198.41.128.0/17,162.158.0.0/15,104.16.0.0/12,172.64.0.0/13,131.0.72.0/22,2400:cb00::/32,2606:4700::/32,2803:f800::/32,2405:b500::/32,2405:8100::/32,2a06:98c0::/29,2c0f:f248::/32,10.0.0.0/8"
enable-real-ip: "true"
# forward headers
use-forwarded-headers: "true"
# 告訴 nginx real ip 是 CF-Connecting-IP
server-snippet: |
real_ip_header CF-Connecting-IP;
service:
# 很重要
externalTrafficPolicy: "Local"

How to use

Cloudflare 中就可以開啟 proxy mode,透過 CF-Connecting-IP 拿到 client 的真實 IP 進行過濾。
設定 ingress 參考 whitelist-source-range

1
2
3
4
ingress:
enable: true
annotations:
nginx.ingress.kubernetes.io/whitelist-source-range: ${YOUR_REAL_IP}