Project

General

Profile

Actions

Serving applications as TCP sockets » History » Revision 1

Revision 1/4 | Next »
manawyrm, 05/01/2022 11:36 PM


Serving applications as TCP sockets

systemd has become the standard init system on most Linux machines.
One lesser known feature is ability to serve TCP sockets and launch arbitrary services on connection.
This was usually done using inetd/xinetd in the past.

More information about inetd-replacement of systemd can be found at:
http://0pointer.de/blog/projects/inetd.html

Hello World example

/etc/systemd/system/octoi-helloworld.socket with the following content:
[Unit]
Description=OCTOI HelloWorld Socket for Per-Connection Servers

[Socket]
ListenStream=31337
Accept=yes

[Install]
WantedBy=sockets.target

ListenStream= is the TCP port on which the service should run.
Accept=yes causes systemd to accept() incoming connections directly. This could also be done by the service later on. /etc/systemd/system/octoi-helloworld@.service with the following content:
[Unit]
Description=OCTOI HelloWorld Socket Per-Connection Server

[Service]
ExecStart=-/opt/octoi-helloworld.sh
StandardInput=socket
StandardError=null
DynamicUser=true
ExecStart= is the program that will be executed. Notice the - at the beginning, which will get systemd to ignore any non-zero return codes.
StandardInput=socket will redirect any input from the socket to the program.
StandardError=null will redirect any error output to /dev/null.
DynamicUser=true is a very useful feature that will dynamically create a new system user and group, with a new PID/GID for each incoming connection. This is done internally without touching the /etc/passwd file.
If the application allows for this, it can be a powerful tool for security (by isolating the processes and minimizing permissions).
Warning: Applications with DynamicUser enabled run with their own private /tmp directories. Don't try to exchange files/sockets with other processes there.

systemd can also drop permissions in the usual way, by specifying a fixed user and group:

User=helloworld
Group=helloworld

Files (0)

Updated by manawyrm almost 2 years ago · 1 revisions

Add picture from clipboard (Maximum size: 48.8 MB)