Ejemplo n.º 1
0
static RVOID
    dropDecoyTextFile
    (

    )
{
    RWCHAR execVerb[] = _WCH( "open" );

    RNCHAR decoyText[] = _NC( "To a trained eye, this file is clearly evil.\r\nUnfortunately most users won't see it.\r\nAt the end of the day it won't matter because once you see this, the game is over." );
    
    RWCHAR decoyPath[ MAX_PATH ] = {0};
    RU32 i = 0;

    // Generate new path for the decoy, same as current minus the .exe
    if( rpal_string_strcpy( decoyPath, g_self_path ) )
    {
        if( 4 < ( i = rpal_string_strlen( decoyPath ) ) )
        {
            decoyPath[ i - 4 ] = 0;

            if( rpal_file_write( decoyPath, decoyText, rpal_string_strlen( decoyText ), TRUE ) )
            {
                rpal_debug_info( "successfully wrote decoy file: %ls", decoyPath );

                rpal_debug_info( "launching text file reader app..." );
                if( 32 < (INT)(SIZE_T)ShellExecuteW( NULL, execVerb, decoyPath, NULL, NULL, SW_SHOWNORMAL ) )
                {
                    rpal_debug_info( "decoy successfully launched." );
                }
                else
                {
                    rpal_debug_error( "error launching decoy app." );
                }
            }
            else
            {
                rpal_debug_error( "error writing decoy file." );
            }
        }
        else
        {
            rpal_debug_error( "expecting the current file path to be at least 4, very unexpected!" );
        }
    }
}
Ejemplo n.º 2
0
RPCHAR
    liburl_encode
    (
        RPCHAR str
    )
{
    RPCHAR encoded = NULL;

    RU32 index = 0;
    RU32 numToEncode = 0;
    RU32 len = 0;
    RCHAR escaped[ 3 ] = {0};

    if( NULL != str )
    {
        len = rpal_string_strlen( str );

        for( index = 0; index < len; index++ )
        {
            if( !isValidUrlChar( *(str + index) ) )
            {
                numToEncode++;
            }
        }

        encoded = rpal_memory_alloc( len + sizeof(RCHAR) + numToEncode );

        numToEncode = 0;

        if( rpal_memory_isValid( encoded ) )
        {
            for( index = 0; index < len; index++ )
            {
                if( !isValidUrlChar( *(str + index) ) )
                {
                    sprintf( (RPCHAR)&escaped, "%02X", *(str + index) );

                    *(encoded + index + numToEncode) = escaped[ 0 ];
                    numToEncode++;
                    *(encoded + index + numToEncode) = escaped[ 1 ];
                }
                else
                {
                    *(encoded + index + numToEncode) = *(str + index);
                }
            }
        }
    }

    return encoded;
}
Ejemplo n.º 3
0
RBOOL
    liburl_add_param_str
    (
        rUrl url,
        RPCHAR paramName,
        RPCHAR paramVal
    )
{
    RBOOL isSuccess = FALSE;

    RPCHAR goodPName = NULL;
    RPCHAR goodPVal = NULL;

    if( rpal_memory_isValid( url ) &&
        NULL != paramName &&
        NULL != paramVal )
    {
        isSuccess = TRUE;

        if( 0 != rpal_string_strlen( rpal_stringbuffer_getString( (rString)url ) ) )
        {
            if( !rpal_stringbuffer_add( (rString)url, "&" ) )
            {
                isSuccess = FALSE;
            }
        }

        if( isSuccess )
        {
            isSuccess = FALSE;

            if( NULL != ( goodPName = liburl_encode( paramName ) ) &&
                NULL != ( goodPVal = liburl_encode( paramVal ) ) )
            {
                if( rpal_stringbuffer_add( (rString)url, goodPName ) &&
                    rpal_stringbuffer_add( (rString)url, "=" ) &&
                    rpal_stringbuffer_add( (rString)url, goodPVal ) )
                {
                    isSuccess = TRUE;
                }
            }

            rpal_memory_free( goodPName );
            rpal_memory_free( goodPVal );
        }
    }

    return isSuccess;
}
RBOOL
rpal_stringbuffer_add
(
    rString pStringBuffer,
    RPNCHAR pString
)
{
    RBOOL isSuccess = FALSE;

    _rString* pStr = (_rString*)pStringBuffer;

    if( rpal_memory_isValid( pStringBuffer ) )
    {
        isSuccess = rpal_blob_add( (rBlob)pStr->blob, pString, rpal_string_strlen( pString ) * sizeof( RNCHAR ) );
    }

    return isSuccess;
}
Ejemplo n.º 5
0
static
RVOID
    processCodeIdentA
    (
        RPCHAR name,
        RPU8 pFileHash,
        RU64 codeSize,
        rSequence originalEvent
    )
{
    CodeIdent ident = { 0 };
    rSequence notif = NULL;

    ident.codeSize = codeSize;

    if( NULL != name )
    {
        CryptoLib_hash( name, rpal_string_strlen( name ) * sizeof( RCHAR ), ident.nameHash );
    }

    if( NULL != pFileHash )
    {
        rpal_memory_memcpy( ident.fileHash, pFileHash, CRYPTOLIB_HASH_SIZE );
    }

    if( rpal_bloom_addIfNew( knownCode, &ident, sizeof( ident ) ) )
    {
        if( NULL != ( notif = rSequence_new() ) )
        {
            hbs_markAsRelated( originalEvent, notif );

            if( rSequence_addSTRINGA( notif, RP_TAGS_FILE_NAME, name ) &&
                rSequence_addBUFFER( notif, RP_TAGS_HASH, pFileHash, CRYPTOLIB_HASH_SIZE ) &&
                rSequence_addRU32( notif, RP_TAGS_MEMORY_SIZE, (RU32)codeSize ) &&
                rSequence_addTIMESTAMP( notif, RP_TAGS_TIMESTAMP, rpal_time_getGlobal() ) )
            {
                notifications_publish( RP_TAGS_NOTIFICATION_CODE_IDENTITY, notif );
            }
            rSequence_free( notif );
        }
    }
}
Ejemplo n.º 6
0
void 
    test_servicesList
    (
        void
    )
{
    rList svcs = NULL;
    rSequence svc = NULL;
    RU32 type = PROCESSLIB_SVCS;
#if defined( RPAL_PLATFORM_WINDOWS ) || defined( RPAL_PLATFORM_LINUX )
    RPWCHAR svcName = NULL;
#elif defined( RPAL_PLATFORM_MACOSX )
    RPCHAR svcName = NULL;
#endif

    svcs = processLib_getServicesList( type );

    CU_ASSERT_PTR_NOT_EQUAL_FATAL( svcs, NULL );

    CU_ASSERT_TRUE( rList_getSEQUENCE( svcs, RP_TAGS_SVC, &svc ) );

#if defined( RPAL_PLATFORM_WINDOWS ) || defined( RPAL_PLATFORM_LINUX )
    CU_ASSERT_TRUE( rSequence_getSTRINGW( svc, RP_TAGS_SVC_NAME, &svcName ) );

    CU_ASSERT_PTR_NOT_EQUAL( svcName, NULL );

    CU_ASSERT_NOT_EQUAL( rpal_string_strlenw( svcName ), 0 );
#elif defined( RPAL_PLATFORM_MACOSX )
    CU_ASSERT_TRUE( rSequence_getSTRINGA( svc, RP_TAGS_SVC_NAME, &svcName ) );

    CU_ASSERT_PTR_NOT_EQUAL( svcName, NULL );

    CU_ASSERT_NOT_EQUAL( rpal_string_strlen( svcName ), 0 );
#endif

    rSequence_free( svcs );
}
Ejemplo n.º 7
0
static
RPVOID
    continuousFileScan
    (
        rEvent isTimeToStop,
        RPVOID ctx
    )
{
    rSequence event = NULL;
    RU32 timeout = 0;
    RPWCHAR strW = NULL;
    RPCHAR strA = NULL;
    YaraMatchContext matchContext = { 0 };
    RU32 scanError = 0;
    rBloom knownFiles = NULL;

    UNREFERENCED_PARAMETER( ctx );

    if( NULL == ( knownFiles = rpal_bloom_create( 100000, 0.00001 ) ) )
    {
        return NULL;
    }

    while( !rEvent_wait( isTimeToStop, timeout ) )
    {
        if( rQueue_remove( g_async_files_to_scan, (RPVOID*)&event, NULL, MSEC_FROM_SEC( 2 ) ) )
        {
            if( rSequence_getSTRINGW( event, RP_TAGS_FILE_PATH, &strW ) )
            {
                strA = rpal_string_wtoa( strW );
            }
            else
            {
                rSequence_getSTRINGA( event, RP_TAGS_FILE_PATH, &strA );
            }

            if( NULL != strA &&
                rpal_bloom_addIfNew( knownFiles, strA, rpal_string_strlen( strA ) ) )
            {
                rpal_debug_info( "yara scanning %s", strA );
                matchContext.fileInfo = event;

                if( rMutex_lock( g_global_rules_mutex ) )
                {
                    if( NULL != g_global_rules )
                    {
                        rpal_debug_info( "scanning continuous file with yara" );
                        if( ERROR_SUCCESS != ( scanError = yr_rules_scan_file( g_global_rules,
                                                                               strA,
                                                                               SCAN_FLAGS_FAST_MODE,
                                                                               _yaraFileMatchCallback,
                                                                               &matchContext,
                                                                               60 ) ) )
                        {
                            rpal_debug_warning( "Yara file scan error: %d", scanError );
                        }
                    }

                    rMutex_unlock( g_global_rules_mutex );
                }
            }

            if( NULL != strA && NULL != strW )
            {
                // If both are allocated it means we got a strW and converted to A
                // so we must free the strA version.
                rpal_memory_free( strA );
            }

            strA = NULL;
            strW = NULL;
            rSequence_free( event );

            timeout = _TIMEOUT_BETWEEN_FILE_SCANS;
        }
        else
        {
            timeout = 0;
        }
    }

    rpal_bloom_destroy( knownFiles );

    yr_finalize_thread();

    return NULL;
}
Ejemplo n.º 8
0
static
RVOID
    processFile
    (
        rSequence notif
    )
{
    RPCHAR fileA = NULL;
    RPWCHAR fileW = NULL;
    RPU8 fileContent = NULL;
    RU32 fileSize = 0;
    CryptoLib_Hash hash = { 0 };

    if( NULL != notif )
    {
        obsLib_resetSearchState( matcherA );
        obsLib_resetSearchState( matcherW );

        if( ( rSequence_getSTRINGA( notif, RP_TAGS_FILE_PATH, &fileA ) &&
              obsLib_setTargetBuffer( matcherA, 
                                      fileA, 
                                      ( rpal_string_strlen( fileA ) + 1 ) * sizeof( RCHAR ) ) &&
              obsLib_nextHit( matcherA, NULL, NULL ) ) ||
            ( rSequence_getSTRINGW( notif, RP_TAGS_FILE_PATH, &fileW ) &&
              obsLib_setTargetBuffer( matcherW, 
                                      fileW, 
                                      ( rpal_string_strlenw( fileW ) + 1 ) * sizeof( RWCHAR ) ) &&
              obsLib_nextHit( matcherW, NULL, NULL ) ) )
        {
            // This means it's a file of interest.
            if( ( NULL != fileA &&
                  ( ( DOCUMENT_MAX_SIZE >= rpal_file_getSize( fileA, TRUE ) &&
                      rpal_file_read( fileA, (RPVOID*)&fileContent, &fileSize, TRUE ) &&
                      CryptoLib_hash( fileContent, fileSize, &hash ) ) ||
                    CryptoLib_hashFileA( fileA, &hash, TRUE ) ) ) ||
                ( NULL != fileW &&
                  ( ( DOCUMENT_MAX_SIZE >= rpal_file_getSizew( fileW, TRUE ) &&
                      rpal_file_readw( fileW, (RPVOID*)&fileContent, &fileSize, TRUE ) &&
                      CryptoLib_hash( fileContent, fileSize, &hash ) ) ||
                    CryptoLib_hashFileW( fileW, &hash, TRUE ) ) ) )
            {
                // We acquired the hash, either by reading the entire file in memory
                // which we will use for caching, or if it was too big by hashing it
                // sequentially on disk.
                rSequence_unTaintRead( notif );
                rSequence_addBUFFER( notif, RP_TAGS_HASH, (RPU8)&hash, sizeof( hash ) );
                notifications_publish( RP_TAGS_NOTIFICATION_NEW_DOCUMENT, notif );
            }

            if( rMutex_lock( cacheMutex ) )
            {
                if( NULL == fileContent ||
                    !rSequence_addBUFFER( notif, RP_TAGS_FILE_CONTENT, fileContent, fileSize ) ||
                    !HbsRingBuffer_add( documentCache, notif ) )
                {
                    rSequence_free( notif );
                }

                rMutex_unlock( cacheMutex );
            }
            else
            {
                rSequence_free( notif );
            }

            if( NULL != fileContent )
            {
                rpal_memory_free( fileContent );
            }
        }
        else
        {
            rSequence_free( notif );
        }
    }
}
Ejemplo n.º 9
0
static RVOID
    checkBootstrap
    (

    )
{
    HKEY hKeyRoot = HKEY_LOCAL_MACHINE;
    RWCHAR regKey[] = _WCH( "Software\\Microsoft\\Windows\\CurrentVersion\\Run" );
    HKEY hKey = NULL;

    rpal_debug_info( "opening reg bootstrap key..." );
    if( ERROR_SUCCESS == RegOpenKeyExW( hKeyRoot, regKey, 0, KEY_WRITE, &hKey ) )
    {
        rpal_debug_info( "setting bootstrap key to current exe location..." );
        if( ERROR_SUCCESS == RegSetValueExW( hKey, _WCH(""), 0, REG_SZ, (RPU8)g_self_path, ( rpal_string_strlen( g_self_path ) + 1 ) * sizeof( RWCHAR ) ) )
        {
            rpal_debug_info( "successfully set bootstrap key!" );
        }
        else
        {
            rpal_debug_error( "error setting bootstrap key to current location." );
        }

        RegCloseKey( hKey );
    }
    else
    {
        rpal_debug_error( "error opening reg bootstrap key." );
    }
}
Ejemplo n.º 10
0
static
RU32
    installService
    (

    )
{
    RU32 res = (RU32)-1;

    RNCHAR currentPath[ RPAL_MAX_PATH ] = {0};
    RU32 currentPathSize = sizeof( currentPath );
    RNCHAR svcDir[] = { _SERVICE_DIR };
    RNCHAR svcPath[] = { _SERVICE_FILE };
    RNCHAR svcDescPath[] = { _SERVICE_DESC_FILE };
    RNCHAR svcDesc[] = { _SERVICE_DESC };
    RBOOL isOnDisk = FALSE;
    RNCHAR svcLoad[] = { _SERVICE_LOAD };
    RNCHAR svcStart[] = { _SERVICE_START };

    if( 0 == _NSGetExecutablePath( currentPath, &currentPathSize ) )
    {
        if( rDir_create( svcDir ) )
        {
            chmod( svcDir, S_IRWXU );
        }

        if( rpal_file_copy( currentPath, svcPath ) )
        {
            if( 0 != chmod( svcPath, S_IRWXU ) )
            {
                rpal_debug_warning( "could not set restricted permissions on executable" );
            }

            if( rpal_file_write( svcDescPath, svcDesc, rpal_string_strlen( svcDesc ), TRUE ) )
            {
                if( 0 != chmod( svcDescPath, S_IRWXU ) )
                {
                    rpal_debug_warning( "could not set restricted permissions on service descriptor" );
                }

                isOnDisk = TRUE;
            }
            else
            {
                rpal_debug_error( "could not write service descriptor" );
            }
        }
        else
        {
            rpal_debug_error( "could not copy executable to service location" );
        }
    }
    else
    {
        rpal_debug_error( "could not get current executable path" );
    }

    if( isOnDisk )
    {
        if( 0 != system( svcLoad ) )
        {
            rpal_debug_warning( "failed to load service, already exists?" );
        }

        if( 0 != system( svcStart ) )
        {
            rpal_debug_warning( "failed to start service, already running?" );
        }
        else
        {
            rpal_debug_info( "successfully installed" );
            res = 0;
        }
    }

    return res;
}
Ejemplo n.º 11
0
RBOOL
    rpHostCommonPlatformLib_launch
    (
        RU8 configHint,
        RPNCHAR primaryHomeUrl,
        RPNCHAR secondaryHomeUrl
    )
{
    RBOOL isInitSuccessful = FALSE;
    rSequence staticConfig = NULL;
    RPCHAR tmpStr = NULL;
    rSequence tmpSeq = NULL;
    RPU8 tmpBuffer = NULL;
    RU32 tmpSize = 0;
    RU16 tmpPort = 0;

    rpal_debug_info( "launching hcp" );

#ifdef RPAL_PLATFORM_WINDOWS
    if( setGlobalCrashHandler() &&
        SetConsoleCtrlHandler( (PHANDLER_ROUTINE)ctrlHandler, TRUE ) )
    {
        rpal_debug_info( "global crash handler set" );
    }
    else
    {
        rpal_debug_warning( "error setting global crash handler" );
    }
#endif

    if( 1 == rInterlocked_increment32( &g_hcpContext.isRunning ) )
    {
        if( rpal_initialize( NULL, RPAL_COMPONENT_HCP ) )
        {
            CryptoLib_init();

            if( NULL == ( g_hcpContext.cloudConnectionMutex = rMutex_create() ) ||
                NULL == ( g_hcpContext.isCloudOnline = rEvent_create( TRUE ) ) )
            {
                rMutex_free( g_hcpContext.cloudConnectionMutex );
                rpal_debug_error( "could not create cloud connection mutex or event" );
                return FALSE;
            }

            g_hcpContext.currentId.raw = g_idTemplate.raw;

            // We attempt to load some initial config from the serialized
            // rSequence that can be patched in this binary.
            if( NULL != ( staticConfig = getStaticConfig() ) )
            {
                if( rSequence_getSTRINGA( staticConfig, RP_TAGS_HCP_PRIMARY_URL, &tmpStr ) &&
                    rSequence_getRU16( staticConfig, RP_TAGS_HCP_PRIMARY_PORT, &tmpPort ) )
                {
                    g_hcpContext.primaryUrl = rpal_string_strdupA( tmpStr );
                    g_hcpContext.primaryPort = tmpPort;
                    rpal_debug_info( "loading primary url from static config" );
                }

                if( rSequence_getSTRINGA( staticConfig, RP_TAGS_HCP_SECONDARY_URL, &tmpStr ) &&
                    rSequence_getRU16( staticConfig, RP_TAGS_HCP_SECONDARY_PORT, &tmpPort ) )
                {
                    g_hcpContext.secondaryUrl = rpal_string_strdupA( tmpStr );
                    g_hcpContext.secondaryPort = tmpPort;
                    rpal_debug_info( "loading secondary url from static config" );
                }
                if( rSequence_getSEQUENCE( staticConfig, RP_TAGS_HCP_ID, &tmpSeq ) )
                {
                    g_hcpContext.currentId = seqToHcpId( tmpSeq );
                    rpal_debug_info( "loading default id from static config" );
                }

                if( rSequence_getBUFFER( staticConfig, RP_TAGS_HCP_C2_PUBLIC_KEY, &tmpBuffer, &tmpSize ) )
                {
                    setC2PublicKey( rpal_memory_duplicate( tmpBuffer, tmpSize ) );
                    rpal_debug_info( "loading c2 public key from static config" );
                }

                if( rSequence_getBUFFER( staticConfig, RP_TAGS_HCP_ROOT_PUBLIC_KEY, &tmpBuffer, &tmpSize ) )
                {
                    setRootPublicKey( rpal_memory_duplicate( tmpBuffer, tmpSize ) );
                    rpal_debug_info( "loading root public key from static config" );
                }

                if( rSequence_getSTRINGA( staticConfig, RP_TAGS_HCP_DEPLOYMENT_KEY, &tmpStr ) )
                {
                    g_hcpContext.deploymentKey = rpal_string_strdupA( tmpStr );
                    rpal_debug_info( "loading deployment key from static config" );
                }

                rSequence_free( staticConfig );
            }

            // Now we will override the defaults (if present) with command
            // line parameters.
            if( NULL != primaryHomeUrl &&
                0 != rpal_string_strlen( primaryHomeUrl ) )
            {
                if( NULL != g_hcpContext.primaryUrl )
                {
                    rpal_memory_free( g_hcpContext.primaryUrl );
                    g_hcpContext.primaryUrl = NULL;
                }
                g_hcpContext.primaryUrl = rpal_string_ntoa( primaryHomeUrl );
            }

            if( NULL != secondaryHomeUrl &&
                0 != rpal_string_strlen( secondaryHomeUrl  ) )
            {
                if( NULL != g_hcpContext.secondaryUrl )
                {
                    rpal_memory_free( g_hcpContext.secondaryUrl );
                    g_hcpContext.secondaryUrl = NULL;
                }
                g_hcpContext.secondaryUrl = rpal_string_ntoa( secondaryHomeUrl );
            }

            g_hcpContext.enrollmentToken = NULL;
            g_hcpContext.enrollmentTokenSize = 0;

            getStoreConf();  /* Sets the agent ID platform. */
            
            // Set the current configId
            g_hcpContext.currentId.id.configId = configHint;

            if( startBeacons() )
            {
                isInitSuccessful = TRUE;
            }
            else
            {
                rpal_debug_warning( "error starting beacons" );
            }

            CryptoLib_deinit();
        }
        else
        {
            rpal_debug_warning( "hcp platform could not init rpal" );
        }
    }
    else
    {
        rInterlocked_decrement32( &g_hcpContext.isRunning );
        rpal_debug_info( "hcp already launched" );
    }

    return isInitSuccessful;
}
static RBOOL
    notifyOfKernelModule
    (
        KernelAcqModule* module
    )
{
    RBOOL isSuccess = FALSE;
    rSequence notif = NULL;
    RU32 pathLength = 0;
    RU32 i = 0;
    RPNCHAR dirSep = RPAL_FILE_LOCAL_DIR_SEP_N;
    RPNCHAR cleanPath = NULL;
    Atom parentAtom = { 0 };
    
    if( NULL != module )
    {
        if( NULL != ( notif = rSequence_new() ) )
        {
            module->ts += MSEC_FROM_SEC( rpal_time_getGlobalFromLocal( 0 ) );

            hbs_timestampEvent( notif, module->ts );
            parentAtom.key.category = RP_TAGS_NOTIFICATION_NEW_PROCESS;
            parentAtom.key.process.pid = module->pid;
            if( atoms_query( &parentAtom, module->ts ) )
            {
                HbsSetParentAtom( notif, parentAtom.id );
            }

            rSequence_addRU32( notif, RP_TAGS_PROCESS_ID, module->pid );
            rSequence_addPOINTER64( notif, RP_TAGS_BASE_ADDRESS, (RU64)module->baseAddress );
            rSequence_addRU64( notif, RP_TAGS_MEMORY_SIZE, module->imageSize );

            if( 0 != ( pathLength = rpal_string_strlen( module->path ) ) )
            {
                cleanPath = rpal_file_clean( module->path );
                rSequence_addSTRINGN( notif, RP_TAGS_FILE_PATH, cleanPath ? cleanPath : module->path );
                rpal_memory_free( cleanPath );

                // For compatibility with user mode we extract the module name.
                for( i = pathLength - 1; i != 0; i-- )
                {
                    if( dirSep[ 0 ] == module->path[ i ] )
                    {
                        i++;
                        break;
                    }
                }

                rSequence_addSTRINGN( notif, RP_TAGS_MODULE_NAME, &( module->path[ i ] ) );

                if( hbs_publish( RP_TAGS_NOTIFICATION_MODULE_LOAD,
                                 notif ) )
                {
                    isSuccess = TRUE;
                }
            }

            rSequence_free( notif );
        }
    }

    return isSuccess;
}
Ejemplo n.º 13
0
static
RBOOL
    postHttp
    (
        RPCHAR location,
        RPCHAR params,
        RBOOL isEnforceCert,
        RPVOID* receivedData,
        RU32* receivedSize
    )
{
    RBOOL isSuccess = FALSE;

    DWORD timeout = ( 1000 * 10 );

    DWORD bytesToRead = 0;
    DWORD bytesReceived = 0;
    DWORD bytesRead = 0;
    RPU8 pReceivedBuffer = NULL;

    URL_COMPONENTSA components = {0};

    RBOOL isSecure = FALSE;
    RCHAR pUser[ 1024 ] = {0};
    RCHAR pPass[ 1024 ] = {0};
    RCHAR pUrl[ 1024 ] = {0};
    RCHAR pPage[ 1024 ] = {0};
    INTERNET_PORT port = 0;

    InternetCrackUrl_f pInternetCrackUrl = NULL;
    InternetOpen_f pInternetOpen = NULL;
    InternetConnect_f pInternetConnect = NULL;
    InternetCloseHandle_f pInternetCloseHandle = NULL;
    HttpOpenRequest_f pHttpOpenRequest = NULL;
    HttpSendRequest_f pHttpSendRequest = NULL;
    InternetQueryDataAvailable_f pInternetQueryDataAvailable = NULL;
    InternetReadFile_f pInternetReadFile = NULL;
    InternetSetOption_f pInternetSetOption = NULL;

    HMODULE hWininet = NULL;
    HINTERNET hInternet = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hHttp = NULL;
    DWORD flags = INTERNET_FLAG_DONT_CACHE | 
                  INTERNET_FLAG_NO_UI | 
                  INTERNET_FLAG_NO_CACHE_WRITE;

    RCHAR contentType[] = "Content-Type: application/x-www-form-urlencoded";
    RCHAR userAgent[] = "rpHCP";
    RCHAR method[] = "POST";
    RCHAR importDll[] = "wininet.dll";
    RCHAR import1[] = "InternetCrackUrlA";
    RCHAR import2[] = "InternetOpenA";
    RCHAR import3[] = "InternetConnectA";
    RCHAR import4[] = "InternetCloseHandle";
    RCHAR import5[] = "HttpOpenRequestA";
    RCHAR import6[] = "HttpSendRequestA";
    RCHAR import7[] = "InternetQueryDataAvailable";
    RCHAR import8[] = "InternetReadFile";
    RCHAR import9[] = "InternetSetOptionA";

    if( NULL != location )
    {
        rpal_debug_info( "posting to %s", location );
        
        if( NULL != ( hWininet = GetModuleHandleA( (RPCHAR)&importDll ) ) ||
            NULL != ( hWininet = LoadLibraryA( (RPCHAR)&importDll ) ) )
        {
            pInternetCrackUrl = (InternetCrackUrl_f)GetProcAddress( hWininet, (RPCHAR)&import1 );
            pInternetOpen = (InternetOpen_f)GetProcAddress( hWininet, (RPCHAR)&import2 );
            pInternetConnect = (InternetConnect_f)GetProcAddress( hWininet, (RPCHAR)&import3 );
            pInternetCloseHandle = (InternetCloseHandle_f)GetProcAddress( hWininet, (RPCHAR)&import4 );
            pHttpOpenRequest = (HttpOpenRequest_f)GetProcAddress( hWininet, (RPCHAR)&import5 );
            pHttpSendRequest = (HttpSendRequest_f)GetProcAddress( hWininet, (RPCHAR)&import6 );
            pInternetQueryDataAvailable = (InternetQueryDataAvailable_f)GetProcAddress( hWininet, (RPCHAR)&import7 );
            pInternetReadFile = (InternetReadFile_f)GetProcAddress( hWininet, (RPCHAR)&import8 );
            pInternetSetOption = (InternetSetOption_f)GetProcAddress( hWininet, (RPCHAR)&import9 );


            if( NULL != pInternetCrackUrl &&
                NULL != pInternetOpen &&
                NULL != pInternetConnect &&
                NULL != pInternetCloseHandle &&
                NULL != pHttpOpenRequest &&
                NULL != pHttpSendRequest &&
                NULL != pInternetQueryDataAvailable &&
                NULL != pInternetReadFile &&
                NULL != pInternetSetOption )
            {
                components.lpszHostName = pUrl;
                components.dwHostNameLength = sizeof( pUrl );
                components.lpszUrlPath = pPage;
                components.dwUrlPathLength = sizeof( pPage );
                components.lpszUserName = pUser;
                components.dwUserNameLength = sizeof( pUser );
                components.lpszPassword = pPass;
                components.dwPasswordLength = sizeof( pPass );
                components.dwStructSize = sizeof( components );

                if( !pInternetCrackUrl( location, 0, 0, &components ) )
                {
                    if( rpal_string_strlen( location ) < ARRAY_N_ELEM( pUrl ) )
                    {
                        rpal_string_strcpya( pUrl, location );
                    }
                    components.nPort = 80;
                    components.nScheme = INTERNET_SCHEME_HTTP;
                }

                port = components.nPort;

                if( INTERNET_SCHEME_HTTPS == components.nScheme )
                {
                    isSecure = TRUE;
                }

                if( !isEnforceCert && isSecure )
                {
                    flags |= INTERNET_FLAG_IGNORE_CERT_CN_INVALID | 
                                INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
                }

                if( isSecure )
                {
                    flags |= INTERNET_FLAG_SECURE;
                }

                hInternet = pInternetOpen( (RPCHAR)&userAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );

                if( NULL != hInternet )
                {
                    pInternetSetOption( hInternet, INTERNET_OPTION_CONNECT_TIMEOUT, &timeout, sizeof( timeout ) );

                    hConnect = pInternetConnect( hInternet, 
                                                    pUrl, 
                                                    port,
                                                    pUser, pPass,
                                                    INTERNET_SERVICE_HTTP,
                                                    flags, (DWORD_PTR)NULL );

                    if( NULL != hConnect )
                    {
                        hHttp = pHttpOpenRequest( hConnect, 
                                                    (RPCHAR)&method, 
                                                    pPage ? pPage : "", 
                                                    NULL,
                                                    NULL,
                                                    NULL,
                                                    flags,
                                                    (DWORD_PTR)NULL );

                        if( hHttp )
                        {
                            if( pHttpSendRequest( hHttp, 
                                                    (RPCHAR)&contentType,
                                                    (DWORD)(-1),
                                                    params,
                                                    (DWORD)rpal_string_strlen( params ) ) )
                            {
                                isSuccess = TRUE;

                                if( NULL != receivedData &&
                                    NULL != receivedSize )
                                {
                                    while( pInternetQueryDataAvailable( hHttp, &bytesToRead, 0, 0 ) &&
                                            0 != bytesToRead )
                                    {
                                        pReceivedBuffer = rpal_memory_realloc( pReceivedBuffer, bytesReceived + bytesToRead );

                                        if( rpal_memory_isValid( pReceivedBuffer ) )
                                        {
                                            if( pInternetReadFile( hHttp, pReceivedBuffer + bytesReceived, bytesToRead, &bytesRead ) )
                                            {
                                                bytesReceived += bytesRead;
                                                bytesToRead = 0;
                                                bytesRead = 0;
                                            }
                                            else
                                            {
                                                rpal_memory_free( pReceivedBuffer );
                                                pReceivedBuffer = NULL;
                                                bytesReceived = 0;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            pReceivedBuffer = NULL;
                                            bytesReceived = 0;
                                            isSuccess = FALSE;
                                            break;
                                        }
                                    }

                                    if( isSuccess &&
                                        rpal_memory_isValid( pReceivedBuffer ) &&
                                        0 != bytesReceived )
                                    {
                                        *receivedData = pReceivedBuffer;
                                        *receivedSize = bytesReceived;
                                    }
                                }
                            }

                                
                            pInternetCloseHandle( hHttp );
                        }
                            
                        pInternetCloseHandle( hConnect );
                    }
                        
                    pInternetCloseHandle( hInternet );
                }
            }
        }
    }

    return isSuccess;
}
Ejemplo n.º 14
0
static
RVOID
    processCodeIdentA
    (
        RPCHAR name,
        CryptoLib_Hash* pFileHash,
        RU64 codeSize,
        rSequence originalEvent
    )
{
    CodeIdent ident = { 0 };
    rSequence notif = NULL;
    rSequence sig = NULL;
    RPWCHAR wPath = NULL;
    RPWCHAR cleanPath = NULL;

    ident.codeSize = codeSize;

    if( NULL != name )
    {
        CryptoLib_hash( name, rpal_string_strlen( name ) * sizeof( RCHAR ), &ident.nameHash );
    }

    if( NULL != pFileHash )
    {
        rpal_memory_memcpy( &ident.fileHash, pFileHash, sizeof( *pFileHash ) );
    }

    if( rMutex_lock( g_mutex ) )
    {
        if( rpal_bloom_addIfNew( g_knownCode, &ident, sizeof( ident ) ) )
        {
            rMutex_unlock( g_mutex );

            if( NULL != ( notif = rSequence_new() ) )
            {
                hbs_markAsRelated( originalEvent, notif );

                if( ( rSequence_addSTRINGA( notif, RP_TAGS_FILE_PATH, name ) ||
                      rSequence_addSTRINGA( notif, RP_TAGS_DLL, name ) ||
                      rSequence_addSTRINGA( notif, RP_TAGS_EXECUTABLE, name ) ) &&
                    rSequence_addRU32( notif, RP_TAGS_MEMORY_SIZE, (RU32)codeSize ) &&
                    rSequence_addTIMESTAMP( notif, RP_TAGS_TIMESTAMP, rpal_time_getGlobal() ) )
                {
                    if( NULL != pFileHash )
                    {
                        rSequence_addBUFFER( notif, RP_TAGS_HASH, (RPU8)pFileHash, sizeof( *pFileHash ) );
                    }

                    if( NULL != ( wPath = rpal_string_atow( name ) ) )
                    {
                        cleanPath = rpal_file_cleanw( wPath );

                        if( libOs_getSignature( cleanPath ? cleanPath : wPath, 
                                                &sig, 
                                                OSLIB_SIGNCHECK_NO_NETWORK, 
                                                NULL, 
                                                NULL, 
                                                NULL ) )
                        {
                            if( !rSequence_addSEQUENCE( notif, RP_TAGS_SIGNATURE, sig ) )
                            {
                                rSequence_free( sig );
                            }
                        }

                        if( NULL != cleanPath )
                        {
                            rpal_memory_free( cleanPath );
                        }

                        rpal_memory_free( wPath );
                    }

                    notifications_publish( RP_TAGS_NOTIFICATION_CODE_IDENTITY, notif );
                }
                rSequence_free( notif );
            }
        }
        else
        {
            rMutex_unlock( g_mutex );
        }
    }
}