Nginx – Rejecting Connections Based on a Pattern

httpsnginx

in the nginx.conf I have added an if clause to filter the ssl connections based on the cn.

For example

map  $ssl_client_s_dn  $ssl_client_s_dn_cn {
    default "";
    ~/CN=(?<CN>[^/]+) $CN;
}

server {
    listen 80 default_server;
    server_name nginx-server;
    return 301 https://$server_name$request_uri;

    listen 443 ssl;
    listen [::]:443 ssl;
    
    server_name nginx-server;
    
    ssl_certificate /path/to/server/cert.pem
    ssl_certificate_key /path/to/nginx-server/privatekey.pem

    location / {

        if ($ssl_client_s_dn_cn !~ "client") {
            return 403;
        }
        root /usr/share/nginx/html;
        index index.html index.htm;
    }
}

Now from the command line I am trying to curl by providing a cert which has a DN similar to C=GB,ST=London,L=City,O=MyOrg,OU=myOU,CN=client I get 403 error.

I tried with other certs also, regardless of the certificate DN/CN, I noticed that Nginx returns 403.
In the access logs I tried to log the $ssl_client_s_dn value in the logs, but it comes a blank.

I took the reference from http://nginx.org/en/docs/http/ngx_http_ssl_module.html

What am I missing here?

update:

If I hardcode the value in the following function to return client it works well:

map  $ssl_client_s_dn  $ssl_client_s_dn_cn {
default "client";

}

I notice that the value of ssl_client_s_dn could be blank according to nginx logs. Has it got something to do with enabling ngx_http_ssl_module module?

I checked $ nginx V I think the module is listed.

Output is attached in an image
enter image description here

Not sure what am I missing! Any help please?

Thanks,
JE

Best Answer

I managed to fix it. Posting solution here just in case it could aid someone in same boat.

In my configurations missing bit was ssl_verify_client optional; until we specify I learnt that unless we mention ssl_verify_client on or optional, the $ssl_client_s_dn variable is not set. It will keep printing blank.

Hindsight it makes sense that without enabling client verification, what server will do with the client client subject DN. However, I would be happier if nginx logs would mention the missing directive. I had to figure it out by trial and error. But glad finally it worked.