Most services have some kind of authentication, but what if it gets compromised? Well, it depends on your setup, but generally it means that some part of the server is compromised. To counter that, we need additional authentication — that's where Nginx comes to a rescue. It allows us to configure a login:password pair that will be required to get access to the service.
It will act as a 2FA: first, you need to authenticate with Nginx, second you need to authenticate with the service credentials. Keeping logins and passwords unique and in a secure location is crucial.
Install apache2-utils
sudo apt update
sudo apt install apache2-utils
Create a user
# -c = create a new file
sudo htpasswd -c /etc/apache2/.htpasswd user1
It may fail due to AppArmor:
mkdir /etc/apache2
cd /etc/apache2
mkdir passwd
touch /etc/apache2/.htpasswd
# Try running again
Display hashed passwords for existing users
cat /etc/apache2/.htpasswd
Fun fact, I once had to manually reset my Matrix server admin's user password; in short I forgot the password, the token was invalid, and I only had access to the server and the database. I SSH-ed into the machine, looked into the DB, extracted the hashed password, generated a new one using the same ARGON setup, and updated the DB using it.
Enable authentication for a location
location ^~ /api {
auth_basic "Supply your credit card info ;)";
auth_basic_user_file /etc/apache2/.htpasswd;
}
Combine with VPN-only access
location ^~ /api {
satisfy all; # requires all requirements to be satisfied
allow 127.0.0.1/32;
deny all;
auth_basic "Supply your credit card info ;)";
auth_basic_user_file /etc/apache2/.htpasswd;
}
Verify config
nginx -t
Restart Nginx
sudo systemctl restart nginx
AppArmor
Don't forget to update the AppArmor profile:
sudo aa-genprof /usr/sbin/nginx
Or add this line to the profile:
/etc/apache2/.htpasswd r,
References
https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/