Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <security/pam_appl.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- struct pam_response *reply;
- // //function used to get user input
- int function_conversation(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr)
- {
- *resp = reply;
- //resp_retcode must always be 0
- reply[0].resp_retcode = 0;
- return PAM_SUCCESS;
- }
- int authenticate_sftp(const char *username, const char *password)
- {
- const struct pam_conv local_conversation = { function_conversation, NULL };
- pam_handle_t *local_auth_handle = NULL; // this gets set by pam_start
- int retval;
- int pam_result;
- retval = pam_start("sftp", username, &local_conversation, &local_auth_handle);
- if (retval != PAM_SUCCESS)
- {
- printf("pam_start returned: %d\n ", retval);
- return 1;
- }
- // for some reason, we have to allocate the pam_response ourselves
- // but pam_end frees it ???
- reply = (struct pam_response *)malloc(sizeof(struct pam_response));
- //fake password entry by pre-setting the field in the response struct
- //this might be a bit fragile - it assumes num_msg will always be 1
- reply[0].resp = strdup(password);
- retval = pam_authenticate(local_auth_handle, PAM_DISALLOW_NULL_AUTHTOK);
- if (retval == PAM_SUCCESS)
- {
- printf("Authenticated.\n");
- pam_result = 0;
- }
- else
- {
- if (retval == PAM_AUTH_ERR)
- {
- printf("Authentication failure.\n");
- pam_result = -1;
- }
- else
- {
- printf("pam_authenticate returned %d\n", retval);
- pam_result = 1;
- }
- }
- retval = pam_end(local_auth_handle, retval);
- if (retval != PAM_SUCCESS)
- {
- printf("pam_end returned %d\n", retval);
- pam_result = 1;
- }
- return pam_result;
- }
- int main(int argc, char** argv)
- {
- char* password;
- char* username;
- char readword[100];
- switch (argc) {
- case 2:
- // arbitrarily limit the size read from stdin
- password = fgets(readword, sizeof(readword), stdin);
- if (!password)
- {
- printf("No password provided\n");
- return 2;
- }
- // trim trailing newline
- size_t c = strlen(password) - 1;
- if (0<c && password[c] == 10) password[c] = 0;
- username = argv[1];
- break;
- case 3:
- username = argv[1];
- password = argv[2];
- break;
- default:
- {
- printf("Usage:\n\t%s <username> [<password>]\n",argv[0]);
- printf("\t\tPassword will be read from stdin if not provided on the command line\n");
- printf("\n\tExit codes:\n");
- printf("\t\t0 - success\n");
- printf("\t\t255(-1) - authentication failed\n");
- printf("\t\t1 - PAM error\n");
- printf("\t\t2 - argument error\n");
- printf("\n");
- return 2;
- }
- };
- return authenticate_sftp(username, password);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement