# Check to make sure users password is correct programmatically



## kpedersen (Feb 2, 2011)

Hello,

Is there some sort of magic (preferably works on linux too) way to find if a users password matched what is given? E.g.


```
if(authPassword("letmein") == true)
{
  cout << "Correct" << endl;
}
else
{
  cout << "Incorrect" << endl;
}
```

I am trying to complete my clone of dtlogin (motif login manager) and this will really help 

If not I might have to spend some time understanding PAM (perhaps look at /sbin/login's source)

Best Regards,


----------



## anomie (Feb 3, 2011)

Do you need a conceptual understanding, or are you asking for a source code snippet? 

For the former, it's simple: hash the password, using the _same_ crypto function (e.g. MD5, Blowfish) and the _same_ salt (can be taken from /etc/master.passwd for that particular entry), then compare. 

Have a look at this entry, for instance: 

```
$1$mUUU8VFU$xr9tjANQI1jZ1AIywUao/.
```


 '1' == hash type (MD5 in this case) 
 'mUUU8VFU' == salt
 'xr9tjANQI1jZ1AIywUao/.' == salted hash

(Notice how everything is delimited by '$'?) 

Hope that helps. If it's source code you need, you're on the right track already. (Find source for a program that has already solved this problem.)


----------



## kpedersen (Feb 3, 2011)

Nice,

It is all working now.

I ran into a few snags but they were easy to sort.

crypt.h for freebsd is found at rpcsvc/crypt.h, so I needed a few #ifdefs to make it cross platform.

Also, when compiled with g++, it really hates to parse crypt.h, so I had to compile the .o with gcc, and then link it to the rest of my project separately (extern "C" the header)

Overall it was easier than I expected,

Much code from here worked http://www.linuxquestions.org/questions/programming-9/check-linux-password-from-etc-shadow-680104/

Thanks


----------



## expl (Feb 3, 2011)

The correct way to do system authentication is to use PAM and not parse password files yourself. PAM allows users to assign rules to different login services without the services needing to know that.


----------



## kpedersen (Feb 4, 2011)

It is complete.





@expl,

True. Looking at http://www.kernel.org/pub/linux/libs/pam/whereislinuxpam.html, the most popular linux distros also support it. I will look into making the parsing password files a fallback if pam is not available.

Thanks


----------



## expl (Feb 4, 2011)

PAM is current standard for authentication on most UNIX and UNIX like operating systems, however the daemons and API might and will differ so some work must be done to make it portable. Just keep in mind that OpenBSD does not use any flavor of PAM for its authentication.

Good authentication software should and will use native system for authentication or at least that would make most sense.


----------

