Double free in System.DirectoryServices.LdapConnection
the try/finally block in LdapConnection.ConstructEntry here is not hardened to Thread.Abort causing a double free of the underlying LDAP memory. The code needs to be refactored to use a pattern similar to SafeHandle to prevent this.
try
{
// …
// get attributes
attribute = Wldap32.ldap_first_attribute(ldapHandle, entryMessage, ref address);
int tempcount = 0;
while(attribute != (IntPtr)0)
{
// after this line attribute is freed but attribute != 0
Wldap32.ldap_memfree(attribute);
tempcount++;
// Thread.Abort can happen here when we enter the runtime to make this pinvoke, but before before attribute is assigned.
// This leads to a double free in the finally block, because attribute != 0, but the underlying attribute is already freed
attribute = Wldap32.ldap_next_attribute(ldapHandle, entryMessage, address);
}
if(address != (IntPtr)0)
{
Wldap32.ber_free(address, 0);
address = (IntPtr)0;
}
return resultEntry;
}
finally
{
// attribute will now make its way out to ldap_memfree even though it’s already been freed
if(attribute != (IntPtr)0)
Wldap32.ldap_memfree(attribute);
}
@tquerec Thread.Abort is not supported on .NETCore. Agree that we can improve this code using SafeHandle.
@GrabYourPitchforks any opinions on moving this to 7.0?
This package is built for netstandard2.0, which runs on platforms that support Thread.Abort (like Full Framework). Agree that we should use SafeHandle or CERs here for such platforms, and also agree that it's a minor enough problem that there's no rush to get it in for 6.0.