HavocFramework / Havoc

The Havoc Framework.
GNU General Public License v3.0
6.31k stars 903 forks source link

Fix HashEx() to calculate correctly hash from wide char string #431

Closed youngifif closed 7 months ago

youngifif commented 7 months ago

I find that the Value of H_MODULE_NTDLL in Defines.h is 0x70e61753, and the Value of python ./hash_func.py ntdll.dll is 0x1edab0ed. So i do some debug, it turns out that

ULONG HashEx(
    IN PVOID String,
    IN ULONG Length,
    IN BOOL  Upper
)

does not work correctly when String is passed as wide-char string.

In Windows OS,

const wchar* wstr = L"ntdll.dll";
//is equal to 
char characters[]{0x6e, 0x00, 0x74, 0x00, 0x64, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x2e, 0x00, 0x64, 0x00, 0x6c, 0x00, 0x6c, 0x00};

We need to calculate the Hash from the element of characters which is greater than 0.

The bug is detailed in comment as follows:

ULONG HashEx(
    IN PVOID String,
    IN ULONG Length,
    IN BOOL  Upper
) {
    ULONG  Hash = HASH_KEY;
    PUCHAR Ptr  = String;

    if ( ! String ) {
        return 0;
    }

    do {
        UCHAR character = *Ptr;

        if ( ! Length ) {
            if ( ! * Ptr ) {
                break;
            }
        } else {
            if ( ( ULONG ) ( C_PTR( Ptr ) - String ) >= Length ) {
                break;
            }

            if ( !*Ptr ) { // Here we encouter the  `*Ptr == 0`  situation. it means character  == 0 at the same time.
                ++Ptr;  //So We should skip this character,and move Ptr to next character.
                // Forgot to reassign character  to *Ptr.  Now character  is still equal to 0.
                //  character = *Ptr; //Reassign to fix it.
            }
        }

        if ( Upper ) {
            if ( character >= 'a' ) {
                character -= 0x20;
            }
        }

        Hash = ( ( Hash << 5 ) + Hash ) + character;

        ++Ptr;
    } while ( TRUE );

    return Hash;
}

It will be a plenty of macros to fix in Defines.h,which is not mentiond in this pull request.

Cracked5pider commented 7 months ago

hash_func.py is script that converst a ANSI string into a hash while for modules you would need a scipt that converts a unicode into an hash. i am going to upload one soon, but this is function works as expected.