Skip to content

Instantly share code, notes, and snippets.

@iolate
Created March 5, 2019 19:15
Show Gist options
  • Save iolate/a58b73a023b35d5f181814de2f4ffccd to your computer and use it in GitHub Desktop.
Save iolate/a58b73a023b35d5f181814de2f4ffccd to your computer and use it in GitHub Desktop.
PAM Authentication for OpenVPN auth-user-pass-verify
// gcc -o pam_auth pam_auth.c -lpam
#include <security/pam_appl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int custom_converation(int num_msg, const struct pam_message** msg, struct pam_response** resp, void* appdata_ptr) {
// Provide password for the PAM conversation response that was passed into appdata_ptr
struct pam_response* reply = (struct pam_response* )malloc(sizeof(struct pam_response));
reply[0].resp = (char*)appdata_ptr;
reply[0].resp_retcode = 0;
*resp = reply;
return PAM_SUCCESS;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s [filepath]\n", argv[0]);
exit(1);
}
FILE* fp;
char* username = NULL;
char* password = NULL;
size_t len = 0;
ssize_t read;
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "%s: Cannot open '%s'\n", argv[0], argv[1]);
return 1;
}
read = getline(&username, &len, fp);
if (read == -1) {
fclose(fp);
return 1;
}
username[strlen(username)-1] = '\0'; // remove LF
read = getline(&password, &len, fp);
if (read == -1) {
fclose(fp);
return 1;
}
password[strlen(password)-1] = '\0'; // remove LF
fclose(fp);
// PAM Authentication
struct pam_conv conv = {custom_converation, password};
pam_handle_t* pamh = NULL;
int retval = pam_start("whoami", username, &conv, &pamh);
if (retval == PAM_SUCCESS)
retval = pam_authenticate(pamh, 0); // is user really user?
//if (retval == PAM_SUCCESS)
// retval = pam_acct_mgmt(pamh, 0); // permitted access?
if (retval == PAM_SUCCESS) {
fprintf(stdout, "Authenticated - %s\n", username);
} else {
fprintf(stdout, "Not Authenticated - %s\n", username);
}
pam_end(pamh, 0);
return retval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment