ulfben

checkuser.c

Jul 29th, 2020
1,138
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.   Based on source code from http://linux-pam.org/Linux-PAM-html/adg-example.html
  3.  
  4.   Requires a PAM configuration file in /etc/pam.d/checkuser
  5.   # Authenticate the user
  6.     auth       required   pam_unix.so
  7.   # Ensure users account and password are still active
  8.     account    required   pam_unix.so
  9.  */
  10.  
  11. #include <security/pam_appl.h>
  12. #include <security/pam_misc.h>
  13. #include <stdio.h>
  14. #include <stdbool.h>
  15. static const bool DEBUG = false;
  16.  
  17. static struct pam_conv conv = {
  18.     misc_conv, //defined in pam_misc.h
  19.     NULL
  20. };  
  21.  
  22. int printError(char* msg, const int retval, pam_handle_t* handle){
  23.     if(DEBUG){
  24.         fprintf(stderr, msg, pam_strerror(handle, retval));
  25.     }else{
  26.         fprintf(stderr, "%s\n", pam_strerror(handle, retval));
  27.     }
  28.     return 1;
  29. }
  30.  
  31. int main(int argc, char *argv[]){
  32.     if(argc != 2) {
  33.         fprintf(stderr, "Usage: checkuser [username]\n");
  34.         exit(1);
  35.     }
  36.     pam_handle_t* handle=NULL;    
  37.     const char* user = argv[1];
  38.     const char* service_name = "checkuser";    
  39.  
  40.     int retval = pam_start(service_name, user, &conv, &handle);
  41.     if (retval != PAM_SUCCESS) {
  42.         return printError("Failure in pam initialization: %s\n", retval, handle);
  43.     }
  44.    
  45.     retval = pam_authenticate(handle, 0);  //ask user for passwd
  46.     if (retval == PAM_SUCCESS) {       
  47.         retval = pam_acct_mgmt(handle, 0);   //is this account allowed access?     
  48.     }  
  49.    
  50.     if (retval == PAM_SUCCESS) {
  51.         fprintf(stdout, "Auth success!\n");
  52.     } else {
  53.         fprintf(stdout, "Auth failure\n");
  54.     }
  55.  
  56.     retval = pam_end(handle, retval);   //terminate the pam transaction        
  57.     handle = NULL;
  58.     return (retval == PAM_SUCCESS ? 0 : 1);    //  indicate success
  59. }
  60.  
RAW Paste Data