vendredi 7 août 2015

Speeding a bytes pattern scanning c++

I coded a program that scan for bad code injected in my process and i would like to speed it up if possible. I changed the code to scan by 4 bytes at a time instead of 1 byte and using mask AND for hazzard bytes, but its still slow. AntiCheats and especially Anti Virus have a super fast algorithm. Can someone point me in the right direction of scanning fast?

AddSignatureToDB("75??83FB5375??81FE890000000F84????????E9????????83FB4F75", ERROR_SIGID_1);

void AddSignatureToDB(char* szSig, DWORD dwSigID)
{
    char szHex[]        = "0x00";
    int iSigLen = lstrlenA(szSig) / 2;
    int iPadding = iSigLen % 4;

    BYTE* mSigData = new BYTE[iSigLen+iPadding];
    BYTE* mSigMask = new BYTE[iSigLen+iPadding];

    for (int i = 0; i < iSigLen; i++)
    {
        mSigData[i] = 0x00;
        mSigMask[i] = 0x00;

        if (szSig[i * 2] != '?')
        {
            szHex[3] = szSig[i * 2];
            mSigData[i] |= (strtoul(szHex, NULL, 0) << 4 & 0xF0);
            mSigMask[i] |= 0xF0;
        }

        if (szSig[i * 2 + 1] != '?')
        {
            szHex[3] = szSig[i * 2 + 1];
            mSigData[i] |= (strtoul(szHex, NULL, 0) & 0x0F);
            mSigMask[i] |= 0x0F;
        }
    }

    if (iPadding > 0)
    {
        for (int i = 0; i < iPadding; i++)
        {
            mSigData[iSigLen+i] = 0x00;
            mSigMask[iSigLen+i] = 0x00;
        }
    }

    this->SigDB[this->iNumSig].mSigBytes = mSigData;
    this->SigDB[this->iNumSig].mSigMasks = mSigMask;
    this->SigDB[this->iNumSig].iNumBytes = iSigLen+iPadding;
    this->SigDB[this->iNumSig].dwSigID = dwSigID;
    this->iNumSig++;
}

bool ScanBlockForSig(BYTE* pBuffer, int iBufSize, T_SigHolder* Sig)
{
    bool bFound = true;
    bool bFound2 = false;

    for (int i = (DWORD)pBuffer; i < ((DWORD)pBuffer + iBufSize - Sig->iNumBytes); i++)
    {
        bFound = true;

        int iStepped = 0;

        while (iStepped < Sig->iNumBytes)
        {
            DWORD dwMask = *(DWORD*)&Sig->mSigMasks[iStepped];
            DWORD dwPart1 = *(DWORD*)&Sig->mSigBytes[iStepped];
            DWORD dwPart2 = *(DWORD*)(i + iStepped) & dwMask;

            if (dwPart1 != dwPart2)
            {
                bFound = false;
                break;
            }

            iStepped += 4;
        }

        if (bFound == true)
        {
            dwAddressFound = (DWORD)i;
            bFound2 = true;
            break;
        }

    }

    return bFound2;
}

Aucun commentaire:

Enregistrer un commentaire