Help with CredEnumerate

As a follow-up to this question, I hope someone can help with the CredEnumerate API.

As I understand from the documentation, the PCREDENTIALS out parameter is "a pointer to an array of pointers to credentials." I can successfully call the CredEnumerate API using C #, but I'm not sure how to convert PCREDENTIALS to something useful (like a list of credentials).

Edit: Here is the code I'm using:

        int count = 0;
        IntPtr pCredentials = IntPtr.Zero;
        bool ret = false;
        ret = CredEnumerate(null, 0, out count, out pCredentials);
        if (ret != false)
        {
            IntPtr[] credentials = new IntPtr[count];
            IntPtr p = pCredentials;
            for (int i = 0; i < count; i++)
            {
                p = new IntPtr(p.ToInt32() + i);
                credentials[i] = Marshal.ReadIntPtr(p);
            }
            List<Credential> creds = new List<Credential>(credentials.Length);
            foreach (IntPtr ptr in credentials)
            {
                creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
            }
        }

Unfortunately, while this works for the first credentials in the array - it is generated and added to the list of correctly following elements of the bomb array in Marshal.PtrToStructure with the following error:

Attempted to read or write protected memory. This often indicates that another memory is corrupted.

? ? Bueller?

+3
2

, , , PCREDENTIALS.

, :

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

...

int count = 0;
IntPtr pCredentials = IntPtr.Zero;
IntPtr[] credentials = null;
bool ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
    credentials = new IntPtr[count];
    IntPtr p = pCredentials;
    for (int n = 0; n < count; n++)
    {
        credentials[n] = Marshal.ReadIntPtr(pCredentials,
           n * Marshal.SizeOf(typeof(IntPtr)));
    }
} 
else
// failed....

Marshal.PtrToStructure PCREDENTIALS (, typedef PCREDENTIALS , , ), MarshalAs StructLayout, ):

// assuming you have declared struct PCREDENTIALS
var creds = new List<PCREDENTIALS>(credentials.Length);
foreach (var ptr in credentials)
{
    creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));
}

, PtrToStructure , .

+5

"IntPtr p", , 1- .

Th 'IntPtr pCredentials'

int count;
IntPtr pCredentials;

if (CredEnumerate(filter, 0, out count, out pCredentials) != 0)
{
    m_list = new List<PCREDENTIALS >(count);
    int sz = Marshal.SizeOf(pCredentials);

    for (int index = 0; index < count; index++)
    {
        IntPtr p = new IntPtr((sz == 4 ? pCredentials.ToInt32() : pCredentials.ToInt64()) + index * sz);
        m_list.Add((PCREDENTIALS)Marshal.PtrToStructure(p, typeof(PCREDENTIALS)));
    }
}
+1

Source: https://habr.com/ru/post/1698991/


All Articles