I have a program that is best suited to run as a (systemd) service in Linux. But the program has no checks to prevent it from the direct invocation (by the users). On the internet, some suggest checking for the environmental variable $INVOCATION_ID. This is from the man page of systemd.exec
$INVOCATION_ID
Contains a randomized, unique 128bit ID identifying each runtime cycle of the unit, formatted as 32 character hexadecimal string. A new ID is assigned each time the unit changes from an inactive state into an activating or active state, and may be used to identify this specific runtime cycle, in particular in data stored offline, such as the journal. The same ID is passed to all processes run as part of the unit.
But the environment variable $INVOCATION_ID doesn't seem to be something like a password which we can compute and verify that systemd is the one who started our program. If we are pessimistic about the scenario, a user can set the $INVOCATION_ID and pretend to be systemd. So what is the apt way of identifying whether systemd started our program or someone else?
Template-Code
int main(int argc, char** argv, char** envp)
{
if (/*program is not invoked by systemd*/) {
fprintf(stderr, "this program is intended to be run as a service");
exit(1);
}
}