2

Can I authenticate a local Unix users using C? If so does anyone have a code snippet?

3
  • 3
    Using just traditional passwd/shadow passwords? Or PAM? I would look at the BusyBox login utility or Dropbear sshd source for concise, easy-to-read source examples. The bigger-name (and bigger-footprint) products are full of so much legacy cruft you'll have a hard time finding the code that actually matters, and you'll have to wade through several layers of nonsensical abstractions. Commented Jun 30, 2011 at 15:31
  • 2
    As written this is very much underspecified. If you can explain the use case you have in mind people might be able to help. Commented Jun 30, 2011 at 16:44
  • i am thinking of creating a local unix id, and a program would autentcaite the user input userid and pwd against the local unix ix and pwd Commented Jul 1, 2011 at 21:02

1 Answer 1

4

Good old way to do that, using /etc/shadow:

int sys_auth_user (const char*username, const char*password)
{
  struct passwd*pw;
  struct spwd*sp;
  char*encrypted, *correct;

  pw = getpwnam (username);
  endpwent();

  if (!pw) return 1; //user doesn't really exist

  sp = getspnam (pw->pw_name);
  endspent();
  if (sp)
     correct = sp->sp_pwdp;
  else
     correct = pw->pw_passwd;

  encrypted = crypt (password, correct);
  return strcmp (encrypted, correct) ? 2 : 0;  // bad pw=2, success=0
}

You will also probably need to include <shadow.h> and <pwd.h>, and <unistd.h> for crypt. The whole process of calculations with hash&salt is certainly described somewhere in header's manual pages.

Sign up to request clarification or add additional context in comments.

2 Comments

this is not really a good idea because it only works for users in NIS or /etc/passwd. The more generalized solution is pam_authenticate
Yes, using PAM is adviseable. It will also avoid much other possible problems in my snippets, including eg 1] possibly swapping out the plaintext password (everyone should mlockall) and 2] unlikely but possible timing of strcmp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.