How It Works
Toggle navigation
How It Works
Home
About Me
Archives
Tags
pam简单例子
linux
2016-03-07 00:47:18
791
0
0
ochapman
linux
本文代码涉及所有文件存放在 https://github.com/ochapman/passwd_demo.git ##引 熟悉linux的人应该用过修改用户密码工具passwd,如下所示: ochapman@ubuntu14:~/code/pam$ passwd Changing password for ochapman. (current) UNIX password: 提示了修改谁的密码,并要求输入当前的密码。 一般情况下,读取当前密码,校验当前密码是否正确,再去更新shadow/passwd文件... linux下,这类工作主要由PAM承包 ![图片标题](https://mua.io/api/file/getImage?fileId=56dda1292fa1ec184a7e51a4) PAM能抽象到什么程度呢,本文将用一个简单的例子展示PAM的威力。 ![图片标题](https://mua.io/api/file/getImage?fileId=56dda3812fa1ec184a7e51a5) ##简单例子 下面是一个简单的例子,实现了passwd的基本功能 /* * passwd_demo * a simple passwd utility for showing PAM usage * derived from shadow */ #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <stdbool.h> #include <stdlib.h> #include <security/pam_appl.h> #include <security/pam_misc.h> #define SHADOW_PAM_CONVERSATION misc_conv static struct pam_conv conv = { SHADOW_PAM_CONVERSATION, NULL }; void do_pam_passwd (const char *user, bool silent, bool change_expired) { pam_handle_t *pamh = NULL; int flags = 0, ret; if (silent) flags |= PAM_SILENT; if (change_expired) flags |= PAM_CHANGE_EXPIRED_AUTHTOK; ret = pam_start ("passwd", user, &conv, &pamh); if (ret != PAM_SUCCESS) { fprintf (stderr, "passwd: pam_start() failed, error %d\n", ret); exit (10); /* XXX */ } ret = pam_chauthtok (pamh, flags); if (ret != PAM_SUCCESS) { fprintf (stderr, "passwd: %s\n", pam_strerror (pamh, ret)); fputs ("passwd: password unchanged\n", stderr); pam_end (pamh, ret); exit (10); /* XXX */ } fputs ("passwd: password updated successfully\n", stderr); (void) pam_end (pamh, PAM_SUCCESS); } int main(int argc, char *argv[]) { if (argc !=2 ) { fprintf(stderr, "usage: %s user\n", argv[0]); return -1; } char *user = argv[1]; do_pam_passwd(user, false, false); return 0; } 编译后(github仓库中有Makefile,直接运行make即可),运行 ochapman@ubuntu14:~/code/pam$ sudo ./passwd_demo mua Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully 从上看到提示的“Enter new UNIX password:”等交互,并没有在例子中实现 切换到mua,看刚才输入的密码是否真的正常更新 ochapman@ubuntu14:~/code/pam$ su mua Password: mua@ubuntu14:/home/ochapman/code/pam$ 能正常切换到mua用户上,说明刚才修改的密码能正常更新。 ![图片标题](https://mua.io/api/file/getImage?fileId=56dbb7422fa1ec43100661e6) 从本例看,没有直接操作实现操作shadow/passwd相关文件,实现了密码更新功能。 ##结 例子中调用了PAM库相关功能,这些功能把密码更新交互,校验,保存都处理(显然主要是pam_chauthtok)。问题来了 pam内部是怎么实现这些功能?待续... ![图片标题](https://mua.io/api/file/getImage?fileId=56dbb8632fa1ec43100661e7)
Pre:
进程只有一个
Next:
dup2小析
0
likes
791
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Table of content