As @Celada pointed out, both
getlogin() depend on
/var/run/utmp, which puts them at mid-level trustworthiness (it's a regular file instead of something that necessarily gets regenerated with reboots, unlike kernel structures, so there's a slight possibility of contamination if they can boot from CD or something, then again what couldn't they compromise if they did that?). There is hope hiding in plain sight though. I had been intentionally ignoring
/proc/$$/loginuid up to this point because it was owned by the invoking user and the writable bit was set for owner, so I figured it was mostly just a convenience and not a security mechanism. It appears this assumption was incorrect. Here is the descriptive text for a kernel patch submitted towards the end of 2011:
At the moment we allow tasks to set their loginuid if they have
CAP_AUDIT_CONTROL. In reality we want tasks to set the loginuid when
they log in and it be impossible to ever reset. We had to make it
mutable even after it was once set (with the CAP) because on update
and admin might have to restart sshd. Now sshd would get his loginuid
and the next user which logged in using ssh would not be able to set
Systemd has changed how userspace works and allowed us to make the
kernel work the way it should. With systemd users (even admins) are
not supposed to restart services directly. The system will restart
the service for them. Thus since systemd is going to loginuid==-1,
sshd would get -1, and sshd would be allowed to set a new loginuid
without special permissions.
If an admin in this system were to manually start an sshd he is
inserting himself into the system chain of trust and thus, logically,
it's his loginuid that should be used!
So is it listed as writable by the user? Yes. Can the user actually change it? Only if they're root or have CAP_AUDIT_CONTROL (which is probably not a lot of people). The most secure solution I can find is to actually pull this from
/proc/$$/loginuid (if writing a shell script or on the command line) or
audit_getloginuid() from a program.