Tuesday, June 4, 2013

Add Authentication to Nginx

The plan is to expose certain web apps behind Basic HTTP Authentication.  This is why the web server is only available via HTTPS, we do not want LDAP user/passwords going over plaintext.  The way we have setup LDAP and PAM earlier, it is very easy to secure subdomains using it. Note: Basic HTTP Authentication has uses no session cookies or persistence, so the user remains logged in until they close their browser. Be warned!

Make sure that you have nginx-extras installed, and not nginx.  Extras includes the PAM module.
sudo apt-get install nginx-extras
The following is taken from this readme.  
To protect everything under /secure you will add the following to the nginx.conf file: This is secure enough for many purposes.
location /secure {
    auth_pam              "Secure Zone";
    auth_pam_service_name "nginx";
}
Note that the module runs as the web server user, so the PAM modules used must be able to authenticate the users without being root; that means that if you want to use the pam_unix.so module to authenticate users you need to let the web server user to read the /etc/shadow file if that does not scare you (on Debian like systems you can add the www-data user to the shadow group).

As an example, to authenticate users against an LDAP server (using the pam_ldap.so module) you will use an /etc/pam.d/nginx like the following:
auth    required pam_ldap.so
account required pam_ldap.so
If you also want to limit the users from LDAP that can authenticate you can use the pam_listfile.so module; to limit who can access resources under /restricted add the following to the nginx.conf file:
location /restricted {
    auth_pam              "Restricted Zone";
    auth_pam_service_name "nginx_restricted";
}
Use the following /etc/pam.d/nginx_restricted file:
auth    required pam_listfile.so onerr=fail item=user \
                 sense=allow file=/etc/nginx/restricted_users
auth    required pam_ldap.so
account required pam_ldap.so
And add the users allowed to authenticate to the /etc/nginx/restricted_users (remember that the web server user has to be able to read this file).

No comments:

Post a Comment