Kubernetes nginx ingress - block requests with bad host headers

3/13/2019

I've a Django application running behind Nginx ingress on Kubernetes. I wish to block requests that are sent with bad host headers (that are looking to do a host header exploit/cache poisoning).

To block these requests at the Nginx layer, I know I can add a server block with the default_server parameter as described here.

However, I am not sure how to do that in Kubernetes via the externalingress yaml. I came across this PR which seemed relevant, but could not figure it out.

-- jeffreyveon
kubernetes
nginx

1 Answer

3/13/2019

You can do that in two ways: via server-snippet annotation or by overriding existing Nginx Ingress Controller's ConfigMap.

Example from documentation, how to update server configuration block in related nginx.conf file for underlying nginx-ingress-controller Pod via server-snippet annotation:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
        set $agentflag 0;

        if ($http_user_agent ~* "(Mobile)" ){
          set $agentflag 1;
        }

        if ( $agentflag = 1 ) {
          return 301 https://m.example.com;
        }

ConfigMap requires also server-snippet parameter in order to propagate configuration to nginx-ingress-controller Pod:

kind: ConfigMap
apiVersion: v1
metadata:
  name: ingress-nginx-ingress-controller
  namespace: ingress-nginx
data:
  server-snippet: |
    set $agentflag 0;

        if ($http_user_agent ~* "(Mobile)" ){
          set $agentflag 1;
        }

        if ( $agentflag = 1 ) {
          return 301 https://m.example.com;
        }
-- mk_sta
Source: StackOverflow