C#在Windows XP专业版上调整了CredWrite问题

时间:2012-04-06 03:41:11

标签: c# pinvoke credentials

我目前有一个用c#调用CredRead/CredWrite from Advapi32.dll编写的程序,以方便未加入域的用户保存终端服务器/ 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;
    }

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

由于

1 个答案:

答案 0 :(得分: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。