Sub topic 14
Service users, file permissions, and blocking hidden files
This chapter assumes you can read ls -l output, use chown and chmod, and write the Nginx and systemd configuration from the earlier chapters. The goal is to limit what a compromised web process can read, write, and execute. If an attacker finds a bug in your PHP or Python code, the damage should stop at the application's own files.
Who runs what
Three kinds of processes handle a request, and each should run as a different account with different rights.
- Nginx master process. It runs as
rootso it can bind ports 80 and 443 and read certificates. It does no request handling. - Nginx workers. They run as
www-dataon Debian and Ubuntu (set by theuserdirective innginx.conf). They read static files and talk to the application socket. - The application. PHP-FPM workers or Gunicorn run as a dedicated service user. This user should own nothing outside its application, have no login shell, and have no sudo rights.
Create the service user as a system account:
sudo useradd --system --user-group --no-create-home \
--shell /usr/sbin/nologin myappA separate account keeps the application from reading other apps' files. It also keeps Nginx and the application apart, so a bug in one does not give full rights over the other.
Ownership and modes for application files
The principle is that the service user can read the code but cannot change it, and it can write only to the few directories that need it, such as uploads, cache, and sessions. If the code is not writable by the service user, an attacker who finds an upload flaw cannot easily plant a backdoor in your application files.
This layout uses a deployment account deploy that owns the code, and the group www-data as the shared group for Nginx and the application:
sudo chown -R deploy:www-data /srv/myapp
sudo chmod -R u=rwX,g=rX,o= /srv/myapp
sudo mkdir -p /srv/myapp/var
sudo chown -R myapp:www-data /srv/myapp/var
sudo chmod -R u=rwX,g=rX,o= /srv/myapp/varThe capital X sets the execute bit only on directories and on files that already have it. Plain chmod 640 on every file would strip the execute bit from venv/bin/gunicorn, and the service would fail to start. The o= removes all access for other users.
The traversal rule is a common source of 403 errors. To open /srv/myapp/public/index.php, a process needs the execute bit (x) on every directory in the path, not only on the last one. Check a path as a given user:
namei -l /srv/myapp/public/index.php
sudo -u www-data test -r /srv/myapp/public/index.php && echo readablenamei -l prints the owner, group, and mode of each path component, so you can see which directory blocks access.
Socket permissions
A Unix socket is a file, so file permissions decide who can connect to it. Nginx needs read and write access to the socket, and nobody else should have it.
For PHP-FPM, the pool file sets the user the workers run as and the socket's owner, group, and mode:
[myapp]
user = myapp
group = www-data
listen = /run/php/myapp.sock
listen.owner = myapp
listen.group = www-data
listen.mode = 0660
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3Save this as /etc/php/8.3/fpm/pool.d/myapp.conf (the version number depends on your install), then point fastcgi_pass at unix:/run/php/myapp.sock.
For Gunicorn, systemd creates the socket directory, and Gunicorn creates the socket inside it. The socket's group is the process's primary group, and its mode comes from the umask. The unit below extends the one from the systemd chapter:
[Unit]
Description=Gunicorn for myapp
After=network.target
[Service]
User=myapp
Group=www-data
WorkingDirectory=/srv/myapp
RuntimeDirectory=gunicorn
RuntimeDirectoryMode=0750
ExecStart=/srv/myapp/venv/bin/gunicorn --workers 3 --umask 007 --bind unix:/run/gunicorn/app.sock app:application
Restart=on-failure
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/srv/myapp/var
[Install]
WantedBy=multi-user.targetThe relevant lines are these:
--umask 007gives the socket mode0770, so members ofwww-datacan connect and other users cannot.RuntimeDirectoryMode=0750lets the group traverse/run/gunicornbut keeps other users out.NoNewPrivileges=yesstops the process and its children from gaining privileges through setuid binaries.PrivateTmp=yesgives the service its own/tmp.ProtectSystem=strictmakes the whole filesystem read-only for the service, except whatReadWritePathsandRuntimeDirectoryname.
After you change a unit file, run sudo systemctl daemon-reload and then sudo systemctl restart gunicorn.
Blocking hidden files
Dotfiles often hold secrets or history: .env, .git/, .htpasswd, .DS_Store. The best defense is to keep them out of the document root entirely. Set root to the public directory, as in the Nginx example in this tutorial's plan, so that .env in the project root is never reachable by URL. Add a deny rule as a second layer, in case a file ends up in public by mistake:
location ~ /\.(?!well-known) {
deny all;
}The regular expression matches any path containing a slash followed by a dot. The negative lookahead (?!well-known) makes an exception for /.well-known/, which certificate authorities use to validate domains during HTTPS certificate issuance. Without that exception, certificate renewal breaks.
Location order matters here. Nginx checks regex locations in the order they appear in the file, and the first match wins. A request for /.config.php matches both \.php$ and the hidden-file rule, so put the deny block before the PHP block. Prefix locations marked ^~, for example location ^~ /static/, skip the regex check altogether. Hidden files under such a prefix are then served unless you add a separate rule inside it.
Hidden files are not the only risk. Editors and admins leave backups and dumps in web roots. Block them as well:
location ~* \.(?:bak|old|orig|swp|sql|log)$ {
deny all;
}Uploads need extra care. If users can upload files into a directory under public, an uploaded shell.php would be handed to PHP-FPM and executed. Stop that with a rule placed before the general PHP location:
location ~* ^/uploads/.*\.php$ {
deny all;
}Better still, store uploads outside the document root and serve them through the application.
Verifying the result
Test as an outsider and as the service accounts:
sudo nginx -t && sudo systemctl reload nginx
curl -I http://example.com/.env
curl -I http://example.com/.git/config
curl -I http://example.com/.well-known/acme-challenge/test
ls -l /run/gunicorn/app.sock
sudo -u myapp touch /srv/myapp/app.pyThe first two requests should return 403. The .well-known request should return 404 (the file does not exist) and not 403, which shows the exception works. The socket listing should show the mode and group you set. The last command should fail with "Permission denied" (or "Read-only file system" under ProtectSystem=strict), which proves the service cannot modify its own code. If curl returns 200 for .env, check the order of your location blocks first.
Exercise
Nginx returns 502 and the error log says "connect() to unix:/run/gunicorn/app.sock failed (13: Permission denied)". Gunicorn is running as myapp with Group=www-data, and Nginx workers run as www-data. Name two things you would check and the commands you would use.
Show answer
Permission denied (errno 13) means Nginx found the socket but is not allowed to use it. First, run ls -l /run/gunicorn/app.sock and confirm the group is www-data and the group has read and write (rw), for example mode srwxrwx---. If the mode is 0755, Gunicorn's umask is too restrictive, so add --umask 007. Second, run namei -l /run/gunicorn/app.sock and confirm every directory in the path, including /run/gunicorn, has the execute bit for the group. A RuntimeDirectoryMode that excludes the group would cause this. You can also confirm directly with sudo -u www-data test -w /run/gunicorn/app.sock.
Exercise
Why does chmod -R 640 /srv/myapp break a Gunicorn deployment, and what mode string avoids the problem while still denying access to other users?
Show answer
It removes the execute bit from every file, including venv/bin/gunicorn and the directories, so the service cannot start and nobody can traverse into directories. Use chmod -R u=rwX,g=rX,o= /srv/myapp. The capital X adds execute only to directories and to files that already have an execute bit, and o= removes all access for other users.
Exercise
A request for /.git/HEAD returns 403, but a request for /.well-known/acme-challenge/token also returns 403 and certificate renewal fails. What is wrong with the hidden-file rule, and how should it be written?
Show answer
The rule is missing the exception for .well-known. It should read location ~ /\.(?!well-known) { deny all; }. The negative lookahead lets paths starting with /.well-known pass through while every other dot-path is denied.