Skip to content

Instantly share code, notes, and snippets.

@alirezaarzehgar
Created October 27, 2022 08:29
Show Gist options
  • Select an option

  • Save alirezaarzehgar/8982b722277efecfd8e8f87a4ce5f325 to your computer and use it in GitHub Desktop.

Select an option

Save alirezaarzehgar/8982b722277efecfd8e8f87a4ce5f325 to your computer and use it in GitHub Desktop.
Minimal example to use PAM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <err.h>
#include <pwd.h>
#include <security/pam_appl.h>
int login_conv(int num_msg, const struct pam_message **msg,
struct pam_response **resp, void *appdata_ptr)
{
char *str = NULL;
*resp = calloc(sizeof(struct pam_response), num_msg);
for (size_t i = 0; i < num_msg; i++)
switch (msg[i]->msg_style)
{
case PAM_PROMPT_ECHO_ON:
case PAM_PROMPT_ECHO_OFF:
resp[i]->resp = getpass(msg[i]->msg);
break;
case PAM_ERROR_MSG:
case PAM_TEXT_INFO:
fprintf(stderr, "%s\n", msg[i]->msg);
}
return (PAM_SUCCESS);
}
int main(int argc, char const *argv[])
{
int status = EXIT_SUCCESS;
char *user = NULL;
struct pam_conv conv = {.conv = login_conv, .appdata_ptr = NULL};
pam_handle_t *pamh = {NULL};
if (argc != 2)
user = getpwuid(getuid())->pw_name;
else
user = (char *)argv[1];
if (pam_start("login", user, &conv, &pamh))
err(EXIT_FAILURE, "pam_start()");
if (pam_authenticate(pamh, 0))
{
fprintf(stderr, "Authentication failure!\n");
status = EXIT_FAILURE;
}
else
printf("Success!\n");
pam_end(pamh, status);
return (status);
}
@alirezaarzehgar
Copy link
Copy Markdown
Author

alirezaarzehgar commented Oct 27, 2022

Compile:

cc  auth.c -o auth -lpam

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment