Advertisement
Guest User

pamauth.cpp

a guest
Feb 7th, 2014
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <security/pam_appl.h>
  5. #include <unistd.h>
  6.  
  7. // To build this:
  8. // g++ test.cpp -lpam -o test
  9.  
  10. struct pam_response *reply;
  11.  
  12. //function used to get user input
  13. int function_conversation(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
  14. {
  15.   *resp = reply;
  16.   return PAM_SUCCESS;
  17. }
  18.  
  19. int main(int argc, char** argv)
  20. {
  21.   /*if(argc != 2) {
  22.       fprintf(stderr, "Usage: check_user <username>\n");
  23.       exit(1);
  24.   }*/
  25.   const char *username;
  26.   //username = argv[1];
  27.   username = getpass("");
  28.   const struct pam_conv local_conversation = { function_conversation, NULL };
  29.   pam_handle_t *local_auth_handle = NULL; // this gets set by pam_start
  30.  
  31.   int retval;
  32.  
  33.   // local_auth_handle gets set based on the service
  34.   retval = pam_start("common-auth", username, &local_conversation, &local_auth_handle);
  35.  
  36.  
  37.   if (retval != PAM_SUCCESS)
  38.   {
  39.     std::cout << "pam_start returned " << retval << std::endl;
  40.     exit(retval);
  41.   }
  42.  
  43.   reply = (struct pam_response *)malloc(sizeof(struct pam_response));
  44.  
  45.   // *** Get the password by any method, or maybe it was passed into this function.
  46.   reply[0].resp = getpass("");
  47.   reply[0].resp_retcode = 0;
  48.   pam_set_item( local_auth_handle, PAM_AUTHTOK, reply[0].resp);
  49.   retval = pam_authenticate(local_auth_handle, 0);
  50.  
  51.   if (retval != PAM_SUCCESS)
  52.   {
  53.     if (retval == PAM_AUTH_ERR)
  54.     {
  55.       //std::cout << "Authentication failure." << std::endl;
  56.       exit(1);
  57.     }
  58.     else
  59.     {
  60.       std::cout << "pam_authenticate returned " << retval << std::endl;
  61.     }
  62.     exit(retval);
  63.   }
  64.  
  65.   //std::cout << "Authenticated." << std::endl;
  66.   exit(0);
  67.  
  68.   retval = pam_end(local_auth_handle, retval);
  69.  
  70.   if (retval != PAM_SUCCESS)
  71.   {
  72.     std::cout << "pam_end returned " << retval << std::endl;
  73.     exit(retval);
  74.   }
  75.  
  76.   return retval;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement