Many programs need to access the user's home directory to look for files, specially configuration ones. To do that, they usually get the HOME environment variable's value and use it to construct the full path. However, if the application is security-sensible, this is probably inappropriate.
What happens if such application is run through sudo or with the setuid bit set? Let's see it:
[dawn jmmv] $ sudo /bin/sh -c 'id -un ; echo ${HOME}'
root
/home/jmmv
Oops! The application with extra privileges is getting the home directory of the unprivileged user! This is a serious problem, because the user could simply create a malicious configuration file (that exec's a third program, for example) and use it with more privileges than he has.
Fortunately, the user's home directory can be guessed using a safer method: that is, by reading its value from the /etc/passwd file. We only need to be careful to get the entry that matches the actual effective user (not the real one). How'd we do it?
struct passwd *p = getpwuid(geteuid());
(void)printf("Home directory is: n", p->pw_dir);
If we now put the above in a little test program and run it, we get:
[dawn tmp] $ ./a.out
Home directory is: /home/jmmv
[dawn tmp] $ sudo ./a.out
Home directory is: /root
Well, I'm not completely sure this is the best way to go (i.e., if there is any way to still get a value decided by the user), but so far I think this is safer than just reading HOME's value. If anybody knows of any drawbacks, please share!