Skip to content

Instantly share code, notes, and snippets.

@macrat
Created May 28, 2018 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macrat/7d838050227dfe71d2681e6d8e7f1bba to your computer and use it in GitHub Desktop.
Save macrat/7d838050227dfe71d2681e6d8e7f1bba to your computer and use it in GitHub Desktop.
C言語でPAMを使ってログイン認証
#include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <stdio.h>
#include <string.h>
#define USERNAME "this is username"
#define PASSWORD "this is password"
static int conv_func(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) {
int retval = PAM_CONV_ERR;
for (int i=0; i<num_msg; i++) {
if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF && strncmp(msg[i]->msg, "Password: ", 10) == 0) {
struct pam_response *resp_msg = malloc(sizeof(struct pam_response));
char *password = malloc(strlen(PASSWORD));
strcpy(password, PASSWORD);
resp_msg->resp_retcode = 0;
resp_msg->resp = password;
resp[i] = resp_msg;
retval = PAM_SUCCESS;
}
}
return retval;
}
const struct pam_conv conv = {
conv_func,
NULL
};
int main(int argc, char **argv) {
pam_handle_t* pamh = NULL;
int retval;
retval = pam_start("login", USERNAME, &conv, &pamh);
if (retval == PAM_SUCCESS) {
printf("credentials accepted.\n");
retval = pam_authenticate(pamh, 0);
}
if (retval == PAM_SUCCESS) {
printf("valid.\n");
retval = pam_acct_mgmt(pamh, 0);
}
if (retval == PAM_SUCCESS) {
printf("authenticated\n");
} else {
printf("not authenticated\n");
}
if (pam_end(pamh, retval) != PAM_SUCCESS) {
pamh = NULL;
printf("failed to release\n");
exit(1);
}
return retval == PAM_SUCCESS ? 0 : 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment