chkpwd.c:
#include <config.h>
#include <sys/types.h>
#include <pwd.h>
#include "system.h"
#include <shadow.h>
#define DEFAULT_SHELL "/bin/sh"
char *crypt ();
static bool correct_password (char *unencrypted, const struct passwd *pw)
{
char *encrypted, *correct;
#if HAVE_GETSPNAM && HAVE_STRUCT_SPWD_SP_PWDP
struct spwd *sp = getspnam (pw->pw_name);
endspent ();
if (sp) correct = sp->sp_pwdp;
else
#endif
correct = pw->pw_passwd;
if (!correct || correct[0] == '\0') return true;
if(!unencrypted) return false;
encrypted = crypt (unencrypted, correct);
memset (unencrypted, 0, strlen (unencrypted));
return STREQ (encrypted, correct);
}
static struct passwd *getpws (char *username)
{
struct passwd *pw;
pw = getpwnam (username);
if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0] && pw->pw_passwd)) return NULL;
endpwent ();
return pw;
}
bool chkpwd (char *username, char *password)
{
struct passwd *pw;
struct passwd pw_copy;
pw = getpws(username);
if(!pw) return false;
pw_copy = *pw;
pw = &pw_copy;
pw->pw_name = xstrdup (pw->pw_name);
pw->pw_passwd = xstrdup (pw->pw_passwd);
pw->pw_dir = xstrdup (pw->pw_dir);
pw->pw_shell = xstrdup (pw->pw_shell && pw->pw_shell[0] ? pw->pw_shell : DEFAULT_SHELL);
return correct_password (password, pw);
}
__uid_t userid (char *username)
{
struct passwd *pw;
pw = getpws(username);
if(!pw) return -1;
return pw->pw_uid;
}
export.map:
{
global:chkpwd; userid;
local:*;
};
编译命令:
# gcc -c -Iinclude -o chkpwd.o chkpwd.c
# gcc -shared -fPIC -Wl,--version-script=export.map -Llib -o libchk.so chkpwd.o -lcoreutils -lcrypt
编译成libchk.so,其中函数
bool chkpwd (char *username, char *password)
可用于验证Linux用户的密码是否正确。
将libchk.so拷至/usr/lib/目录下,以便调用它的程序能找到。
修改/usr/lib/libchk.so的安全上下文,否则将遭SELinux拦截:
# chcon -t shlib_t /usr/lib/libchk.so