Securing communication between webserver and app

unix-sockets tmpfiles.d webserversysadmin

Webapps usually listen on a random tcp port and a web server forwards the requests to it. Webserver handles tls, static asset serving and sometimes authentication, bruteforce check etc., However any local user in the system can directly connect to the app’s listen port bypassing the web server and thus loose the protections offered by the webserver.

Unix sockets

Unix sockets are special files in filesystem that processes can use to communicate instead of tcp ports. Since they are files, filesytem ownership and permissions can be used to restrict which system-users can listen or connect to them

Caddy ↔ Gitea

I use Caddy web server which reverse-proxies to Gitea server. For caddy to connect to gitea and also disallow anyother user to connect, we want a socket like below

srw-rw---- 1 gitea caddy 0 Apr 17 21:24 /run/gitea.sock

Unfortunately neither user caddy nor user gitea, can create such socket. Regular users can only create files owned by themselves. Only root can create/change ownership of files and folders.

tmpfiles.d to rescue

tmpfiles.d provides a way to do it. Since it is run as root, it can create files and directories as any user.

❯ cat /etc/tmpfiles.d/caddy-run-unix.conf
d /run/gitea-caddy 0750 gitea caddy -

Above config creates below directory every time on startup.

❯ sudo ls -ld /run/gitea-caddy/
drwxr-x--- 2 gitea caddy 60 Apr 17 21:24 /run/gitea-caddy/

With those permissions and ownership, only user gitea can create the socket in /run/gitea-caddy and only user caddy can cd into that directory.

❯ sudo ls -l /run/gitea-caddy/web.sock
srw-rw-rw- 1 gitea gitea 0 Apr 17 21:24 /run/gitea-caddy/web.sock

The socket file permission can be more liberal as no other user can read into the /run/gitea-caddy directory


If your app does not connect to any external services, it can even be run in a private network.