Solution
Separate the login code from the rest.
- Put it in a separate, small program: ~100 lines.
Activate your strong security measures (chroot, setuid) in the login module.
The remaining thousands of lines of code can run unprivileged.
- (Let the OS do access control – it’s good at it.)