【问题标题】:How to check password in Linux by using C or shell?如何使用 C 或 shell 在 Linux 中检查密码?
【发布时间】:2013-07-04 03:55:39
【问题描述】:

我有一个用 C 编写的程序在嵌入式 Linux 上运行,有时它想检查系统用户的密码。

  1. 如果我能得到/etc/passwd的crypt salt,我可以使用crypt()来检查用户密码的正确性。
  2. 有没有shell的脚本可以帮我查密码?比如check_passwd username 密码,那么它返回的值是正确还是不正确? 谢谢!

【问题讨论】:

  • 看看login程序的源代码。
  • 感谢您的回答!我发现busybox的libbb/correct_password.c中的代码对解决方案有很大帮助。还是谢谢~
  • 很高兴您找到了解决方案。通常你不想这样做 - 用户真的不应该将他们的密码提供给任何东西,除了登录或 sudo。
  • 我也这么认为。这个程序是从网页登录系统,因为之前的设计有些问题,我们把密码放在/etc/passwd中,导致了这个问题。现在我把所有密码都移到数据库里了,就OK了。

标签: linux embedded-linux


【解决方案1】:

我最近一直在解决同样的任务。这是 C 函数的示例(与 -lcrypt 链接)。请注意,您需要对文件 /etc/passwd 和 /etc/shadow 具有读取权限。

#include <sys/types.h>
#include <pwd.h>
#include <shadow.h>
#include <crypt.h>
#include <string.h>
#include <stdio.h>

/// @return 0 - password is correct, otherwise no
int CheckPassword( const char* user, const char* password )
{
    struct passwd* passwdEntry = getpwnam( user );
    if ( !passwdEntry )
    {
        printf( "User '%s' doesn't exist\n", user );
        return 1;
    }

    if ( 0 != strcmp( passwdEntry->pw_passwd, "x" ) )
    {
        return strcmp( passwdEntry->pw_passwd, crypt( password, passwdEntry->pw_passwd ) );
    }
    else
    {
        // password is in shadow file
        struct spwd* shadowEntry = getspnam( user );
        if ( !shadowEntry )
        {
            printf( "Failed to read shadow entry for user '%s'\n", user );
            return 1;
        }

        return strcmp( shadowEntry->sp_pwdp, crypt( password, shadowEntry->sp_pwdp ) );
    }
}

【讨论】:

    【解决方案2】:

    如上所述,处理此问题的正确方法是使用可插入的身份验证模块。您必须将 libpam 添加到您正在使用的任何嵌入式 linux 中,但这通常很容易(例如,buildroot 提供了一个 linux-pam 包)。

    【讨论】:

      【解决方案3】:

      请参阅Given a linux username and a password how can I test if it is a valid account?,了解如何检查用户提供的密码是否对该用户有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-14
        • 2018-07-04
        相关资源
        最近更新 更多