Hacker News new | ask | show | jobs
by wahern 3220 days ago
That's cool, though FWIW the idea of using a random UID isn't original; it's how some well-written daemons achieve privilege separation, preventing unprivileged slaves from being able to interact with each other without having to resort to unportable (and often non-existent) capability extensions. You don't need init to do this for you; you can literally just do setuid(arc4random_uniform(5000) + 60000), perhaps after doing the common startup tasks that often require privileges. (The problem with the systemd approach is that you're already unprivileged when you're invoked, which can be a major hurdle for non-trivial services which require unnecessarily complex workarounds--e.g. resorting to D-Bus machinations for otherwise simple privileged operations that you only needed in the first 30 lines of main().)

And a far simpler solution than bind mounts for achieving persistent files is to use the traditional setgid bit on the shared directory with a persistent group[1]. For example,

  mkdir /var/foo
  chown root:somegroup /var/foo
  chmod u=rwx,g=rwxs,o=rx /var/foo
You then either make that group the service process's GID or its supplementary GID if want to randomize the GID. And make sure process umasks are set correctly so newly created files are group writeable.

Altogether this is like three or four lines of code: 1) setgid or setgid + setgroup, 2) setuid, and 3) umask.

You can do all of this, today, on any Unix, with any init system. You end up with files owned by random UIDs, but systemd has no better solution than just periodically chown'ing them.

[1] If you want persistent files then there's really no burden in having a persistent group. It just makes sense.

2 comments

> setuid(arc4random_uniform(5000) + 60000)

You really want something to keep track of that UID, and not re-use it, especially with that small a random space to work with. Better to allocate than just choose at random and hope for no collision.

Unless you need two such programs on the same machine, in which case they need to coordinate somehow. Perhaps by having a third service which hands out the ids as needed.
... or by having a shared-memory account database in a tmpfs at /run/systemd/dynamic-uid/ . (-:

That idea, by the way, was invented more fully and more generally about a decade and a half ago by Daniel Rench, who named it "userdir".