runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Double free in System.DirectoryServices.LdapConnection

Open tquerec opened this issue 6 years ago • 3 comments

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 avatar Apr 20 '20 04:04 tquerec

@tquerec Thread.Abort is not supported on .NETCore. Agree that we can improve this code using SafeHandle.

ericstj avatar Jul 09 '20 17:07 ericstj

@GrabYourPitchforks any opinions on moving this to 7.0?

krwq avatar Jul 08 '21 17:07 krwq

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.

GrabYourPitchforks avatar Jul 08 '21 20:07 GrabYourPitchforks