编写基于PAM认证的应用程序

要求

课堂实验:
在教师讲解的基础上,阅读教师给出的参考文献编写一个程序,要求为:
1)使用Linux下的用户名及其密码实现对该程序的认证;(提示:只需完成应用程序的编写与认证策略的设定)
2)该用户认证完成后,重新设置改用户的密码

参考文献: http://www.linux-pam.org

代码

/etc/pam.d/check_user

#check authorization
auth       required     pam_unix.so
account    required     pam_unix.so
password required     pam_unix.so


#include 
#include 
#include 

static struct pam_conv conv = {
    misc_conv,
    NULL
};

int main(int argc, char *argv[])
{
    pam_handle_t *pamh=NULL;
    int retval;
    const char *user="nobody";

    if(argc == 2) {
        user = argv[1];
    }

    if(argc > 2) {
        fprintf(stderr, "Usage: check_user [username]\n");
        exit(1);
    }

    retval = pam_start("check_user", user, &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? */

    /* This is where we have been authorized or not. */

    if (retval == PAM_SUCCESS) {
        fprintf(stdout, "Authenticated\n");
		
		retval = pam_chauthtok(pamh,PAM_SILENT);
		if (retval == PAM_SUCCESS)
		{
			fprintf(stdout, "更改密码成功\n");
		}else {
			fprintf(stdout, "更改密码失败\n");		
		}
    } else {
        fprintf(stdout, "Not Authenticated\n");
    }

    if (pam_end(pamh,retval) != PAM_SUCCESS) {     /* close Linux-PAM */
        pamh = NULL;
        fprintf(stderr, "check_user: failed to release authenticator\n");
        exit(1);
    }

    return ( retval == PAM_SUCCESS ? 0:1 );       /* indicate success */
}

gcc check_user.c -o check_user -lpam -lpam_misc -ldl

你可能感兴趣的:(编写基于PAM认证的应用程序)