AdamIerymenko
AdamIerymenko

Reputation: 1329

Prevent a Unix domain socket file in the filesystem from being deleted while socket is bound

Is it possible on Linux or MacOSX to prevent a Unix domain socket file (e.g. in /tmp) that is currently bound from being deleted? I want a mode 0777 socket that users can connect to but that users cannot delete while the daemon is running.

Right now a normal user can 'rm' the socket, preventing anyone else from accessing it until the daemon is restarted. Seems like it should be 'busy' if it's bound.

Upvotes: 1

Views: 1628

Answers (2)

Kean
Kean

Reputation: 602

It depends entirely on the directory that contains the socket. /tmp is somewhat special in that it has the "sticky bit" set on the directory (if you execute ls -ld /tmp you will see the permissions field is usually: drwxrwxrwt or, more usefully, mode 1777. That sticky bit (the t at the end) is important when set on a directory. Quoting man chmod:

The restricted deletion flag or sticky bit is a single bit, whose interpretation depends on the file type. For directories, it prevents unprivileged users from removing or renaming a file in the directory unless they own the file or the directory; this is called the re‐ stricted deletion flag for the directory, and is commonly found on world-writable directories like /tmp. For regular files on some older systems, the bit saves the program's text image on the swap device so it will load more quickly when run; this is called the sticky bit.

This is exactly what you want - file-system level protection against a user removing the file. It is also 100% portable to all modern UNIX-like environments.

So, if you are creating your endpoint in /tmp you already have the protections you want. If you want to create the endpoint elsewhere, for example /opt/sockets, simply chmod 1777 /opt/sockets. The last part of the "trick" to getting the protections you want is to ensure that the root user is the actual owner of the endpoint. If the endpoint is owned by user fred then fred will always be able to delete the endpoint, which may well be a desirable thing. But if not, simply chown root:root /path/to/endpoint.

Upvotes: 0

6EQUJ5
6EQUJ5

Reputation: 3302

You could make a new subdirectory and set read only permissions on the directory after you make the socket:

mkdir /tmp/blah
cd /tmp/blah
# do stuff to create /tmp/blah/socket
chmod 555 /tmp/blah


rm /tmp/blah/socket

rm: cannot remove /tmp/blah/socket: Permission denied

(or the equivalent to that from C / your language of choice)

Upvotes: 2

Related Questions