1

我目前有一个用 c# 编写的程序,它从 Advapi32.dll 调用 CredRead/CredWrite,以便未加入域的用户轻松保存终端服务器/WebDAV 服务器凭据。(http://msdn.microsoft.com/en-us/library/aa374788%28v=vs.85%29.aspx获取凭证结构信息)

这一切都很好,但前几天我遇到了一个在所有 XP 操作系统上都存在的问题;我无法保存终端服务器凭据。本机 CredWrite 方法返回错误代码 87 (ERROR_INVALID_PARAMETER)。

在尝试了许多不同的凭据持久性和类型组合之后,我意识到问题出在 TargetName 本身。要将终端服务器保存在 Windows 密钥环中,TargetName 是 TERMSRV/server.domain.com。在 Windows Vista 或更高版本上,这适用于我的代码,但在 Windows XP 上却不行。

奇怪的是,当您在 Windows XP 上运行远程桌面应用程序并让它保存凭据时,它不会大惊小怪。当我在使用 RDP 后创建了一种枚举已保存凭据的方法时(显然没有返回密码 blob),我可以看到目标与我的程序尝试编写的目标相同。

为了确认问题出在 TargetName 中,我删除了“/”,它工作正常。

以下是我的代码的相关部分:

var writeInt = NativeCredMan.WriteCred("TERMSRV/host.server.com", samAccountName, password, CRED_TYPE.DOMAIN_PASSWORD, CRED_PERSIST.LOCAL_MACHINE);

……

public enum CRED_TYPE : uint
{
    GENERIC = 1,
    DOMAIN_PASSWORD = 2,
    DOMAIN_CERTIFICATE = 3,
    DOMAIN_VISIBLE_PASSWORD = 4,
    GENERIC_CERTIFICATE = 5,
    DOMAIN_EXTENDED = 6,
    MAXIMUM = 7,      // Maximum supported cred type
    MAXIMUM_EX = (MAXIMUM + 1000),  // Allow new applications to run on old OSes
}

public enum CRED_PERSIST : uint
{
    SESSION = 1,
    LOCAL_MACHINE = 2,
    ENTERPRISE = 3,
}

……

    [DllImport("Advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern bool CredRead(string target, CRED_TYPE type, int reservedFlag, out IntPtr CredentialPtr);

    [DllImport("Advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]
    static extern bool CredWrite([In] ref NativeCredential userCredential, [In] UInt32 flags);

    [DllImport("Advapi32.dll", EntryPoint = "CredFree", SetLastError = true)]
    static extern bool CredFree([In] IntPtr cred);

    [DllImport("Advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode)]
    static extern bool CredDelete(string target, CRED_TYPE type, int flags);

    //[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
    //static extern bool CredEnumerateold(string filter, int flag, out int count, out IntPtr pCredentials);

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool CredEnumerate(string filter, uint flag, out uint count, out IntPtr pCredentials);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct NativeCredential
    {
        public UInt32 Flags;
        public CRED_TYPE Type;
        public IntPtr TargetName;
        public IntPtr Comment;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
        public UInt32 CredentialBlobSize;
        public IntPtr CredentialBlob;
        public UInt32 Persist;
        public UInt32 AttributeCount;
        public IntPtr Attributes;
        public IntPtr TargetAlias;
        public IntPtr UserName;

        internal static NativeCredential GetNativeCredential(Credential cred)
        {
            var ncred = new NativeCredential
                            {
                                AttributeCount = 0,
                                Attributes = IntPtr.Zero,
                                Comment = IntPtr.Zero,
                                TargetAlias = IntPtr.Zero,
                                Type = CRED_TYPE.DOMAIN_PASSWORD,
                                Persist = (UInt32) cred.Persist,
                                CredentialBlobSize = (UInt32) cred.CredentialBlobSize,
                                TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName),
                                CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
                                UserName = Marshal.StringToCoTaskMemUni(cred.UserName)
                            };
            return ncred;
        }
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public struct Credential
    {
        public UInt32 Flags;
        public CRED_TYPE Type;
        public string TargetName;
        public string Comment;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
        public UInt32 CredentialBlobSize;
        public string CredentialBlob;
        public CRED_PERSIST Persist;
        public UInt32 AttributeCount;
        public IntPtr Attributes;
        public string TargetAlias;
        public string UserName;
    }

……

        public static int WriteCred(string key, string userName, string secret, CRED_TYPE type, CRED_PERSIST credPersist)
    {

        var byteArray = Encoding.Unicode.GetBytes(secret);
        if (byteArray.Length > 512)
            throw new ArgumentOutOfRangeException("The secret message has exceeded 512 bytes.");

        var cred = new Credential
                       {
                           TargetName = key,
                           CredentialBlob = secret,
                           CredentialBlobSize = (UInt32) Encoding.Unicode.GetBytes(secret).Length,
                           AttributeCount = 0,
                           Attributes = IntPtr.Zero,
                           UserName = userName,
                           Comment = null,
                           TargetAlias = null,
                           Type = type,
                           Persist = credPersist
                       };
        var ncred = NativeCredential.GetNativeCredential(cred);

        var written = CredWrite(ref ncred, 0);
        var lastError = Marshal.GetLastWin32Error();
        if (written)
        {
            return 0;
        }
        var message = "";
        if (lastError == 1312)
        {
            message = (string.Format("Failed to save " + key + " with error code {0}.", lastError) + "  This error typically occurrs on home editions of Windows XP and Vista.  Verify the version of Windows is Pro/Business or higher.");
        }
        else
        {
            message = string.Format("Failed to save " + key + " with error code {0}.", lastError);
        }
        MessageBox.Show(message);
        return 1;
    }

关于如何获得这些类型的凭据来保存,任何一点都可以指向正确的方向吗?

谢谢

4

1 回答 1

1

没关系。我发现了问题。在查看我的问题后,我注意到托管凭证计数器部分:

internal static NativeCredential GetNativeCredential(Credential cred)
    {
        var ncred = new NativeCredential
                        {
                            AttributeCount = 0,
                            Attributes = IntPtr.Zero,
                            Comment = IntPtr.Zero,
                            TargetAlias = IntPtr.Zero,
                            Type = CRED_TYPE.DOMAIN_PASSWORD,
                            Persist = (UInt32) cred.Persist,
                            CredentialBlobSize = (UInt32) cred.CredentialBlobSize,
                            TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName),
                            CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
                            UserName = Marshal.StringToCoTaskMemUni(cred.UserName)
                        };
        return ncred;
    }

将 TYPE 预定义为 CRED.TYPE.DOMAIN_PASSWORD 而不仅仅是贴花类型。

更改为:

internal static NativeCredential GetNativeCredential(Credential cred)
    {
        var ncred = new NativeCredential
                        {
                            AttributeCount = 0,
                            Attributes = IntPtr.Zero,
                            Comment = IntPtr.Zero,
                            TargetAlias = IntPtr.Zero,
                            Type = cred.type,
                            Persist = (UInt32) cred.Persist,
                            CredentialBlobSize = (UInt32) cred.CredentialBlobSize,
                            TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName),
                            CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
                            UserName = Marshal.StringToCoTaskMemUni(cred.UserName)
                        };
        return ncred;
    }

并将凭证作为 GENERIC 发送解决了问题。显然,Windows Vista/7 允许在 DOMAIN_PASSWORD 和 GENERIC 持久性密码上使用“/”,但 XP 只允许 GENERIC 使用。

于 2012-04-06T13:42:32.777 回答