[ILUG] finding user name from inside a C program

Braun Brelin bbrelin at gmail.com
Tue Sep 20 13:54:15 IST 2005


#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>

int main(void) {
uid_t uid;

struct passwd *pw;
uid = getuid();

pw = getpwuid(uid);
printf("User name is %s\n",pw->pw_name);
}


This is in C, but this code should work (with obvious modifications) with 
Perl as well...

Braun





On 9/20/05, Joseph Manning <manning at cs.ucc.ie> wrote:
> 
> Hi,
> 
> Does anyone know how to safely and easily determine the user name
> of someone running a C program?
> 
> I tried doing:
> 
> getenv( "USER" )
> 
> and this works, but it can easily be tricked by a malicious user
> simply setting USER=someone-else before running the program.
> 
> The "whoami" command seems to be independent of any tampering
> with the USER environment variable, but doing:
> 
> system( "whoami" )
> 
> will output the user name, rather than returning it. (Yes, it's
> possible to send its output to a file, and then read in that file,
> but this is an awful hack, there must be a neater solution).
> 
> Thanks! -- Joseph
> 
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Joseph Manning / Computer Science / UCC Cork Ireland / manning at cs.ucc.ie
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> --
> Irish Linux Users' Group
> http://www.linux.ie/mailman/listinfo/ilug/
> 
>



More information about the ILUG mailing list