Query Details

14 Geo Multicountry Keys

Query

// REVIEW ONLY workbook query: ✈️ 5.4 Multi-Country AWS Access Key Activity (Potential Credential Theft / Session Replay)
let Start = {TimeRange:start};
let End = {TimeRange:end};
let AccountFilter = trim(" ", base64_decode_tostring("{AwsAccount:base64}"));
let UseAllAccounts = AccountFilter in ("", "*");
let IdentityMap = union isfuzzy=true
  (datatable(SearchKey:string)[]),
  (_GetWatchlist('AWS_EntraIdentityMap'))
| where isnotempty(tostring(column_ifexists("SearchKey", "")))
| extend VerifiedVal = tolower(tostring(column_ifexists("Verified", ""))),
    MappingEvidenceVal = tostring(column_ifexists("MappingEvidence", ""))
| where VerifiedVal == "true" and isnotempty(MappingEvidenceVal)
| project AwsAccessKeyId=tostring(column_ifexists("AwsAccessKeyId", "")),
    AwsPrincipalArn=tostring(column_ifexists("AwsPrincipalArn", "")),
    AWSAccountId=tostring(column_ifexists("AWSAccountId", "")),
    EntraTenantId=tolower(tostring(column_ifexists("EntraTenantId", ""))),
    EntraObjectId=tolower(tostring(column_ifexists("EntraObjectId", ""))),
    IdentityType=tostring(column_ifexists("IdentityType", "")),
    AppClientId=tolower(tostring(column_ifexists("AppClientId", ""))),
    ValidFrom=todatetime(column_ifexists("ValidFromUtc", "")),
    ValidTo=todatetime(column_ifexists("ValidToUtc", ""))
| summarize MappingRows=count(), take_any(*) by AwsAccessKeyId, AwsPrincipalArn, AWSAccountId
| where MappingRows == 1 and isnotempty(EntraTenantId) and isnotempty(EntraObjectId);
union isfuzzy=true
  (datatable(TimeGenerated:datetime, RecipientAccountId:string, UserIdentityAccountId:string, UserIdentityAccessKeyId:string, UserIdentityArn:string, SourceIpAddress:string, EventName:string, ErrorCode:string)[]),
  (AWSCloudTrail | where TimeGenerated between (Start .. End)
   | project TimeGenerated, RecipientAccountId, UserIdentityAccountId, UserIdentityAccessKeyId, UserIdentityArn, SourceIpAddress, EventName, ErrorCode)
| where (UseAllAccounts or RecipientAccountId == AccountFilter or UserIdentityAccountId == AccountFilter)
| where isnotempty(UserIdentityAccessKeyId) and isnotempty(SourceIpAddress) and isnotnull(parse_ipv4(SourceIpAddress)) and not(ipv4_is_private(SourceIpAddress))
| extend Geo = geo_info_from_ip_address(SourceIpAddress)
| extend Country = tostring(Geo.country), City = tostring(Geo.city)
| where isnotempty(Country)
| summarize DistinctCountries = dcount(Country), Countries = make_set(Country, 10), Cities = make_set(City, 10),
    DistinctIps = dcount(SourceIpAddress), SourceIps = make_set(SourceIpAddress, 10),
    Events = count(), DeniedCalls = countif(isnotempty(ErrorCode)), SampleApis = make_set(EventName, 10),
    FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated)
    by AWSAccountId = UserIdentityAccountId, AwsAccessKeyId = UserIdentityAccessKeyId, AwsPrincipalArn = UserIdentityArn
| where DistinctCountries >= 2
| join kind=leftouter IdentityMap on AWSAccountId, AwsAccessKeyId, AwsPrincipalArn
| extend CompromiseRisk = case(
    DistinctCountries >= 3 or isempty(EntraObjectId), "🔴 CRITICAL - Multi-Country Unmapped / Replay Likely",
    "🟠 HIGH - Multi-Country Access Key Activity"),
    BridgeState = iff(isnotempty(EntraObjectId), strcat("🟢 Verified (", EntraObjectId, ")"), "🔴 UNMAPPED KEY")
| project CompromiseRisk, BridgeState, AWSAccountId, AwsAccessKeyId, AwsPrincipalArn, DistinctCountries, Countries, Cities, DistinctIps, Events, DeniedCalls, SourceIps, SampleApis, FirstSeen, LastSeen
| order by DistinctCountries desc, Events desc
| take 5000

Explanation

This query is designed to detect potential security issues related to AWS access keys that are being used from multiple countries, which could indicate credential theft or session replay attacks. Here's a simplified breakdown of what the query does:

  1. Time Range and Account Filtering: The query starts by defining a time range and filtering for specific AWS accounts based on input parameters.

  2. Identity Mapping: It retrieves a list of verified AWS identities from a watchlist, ensuring that only those with valid mapping evidence are considered. This helps in identifying legitimate access keys and their associated AWS accounts.

  3. CloudTrail Data: The query pulls AWS CloudTrail logs within the specified time range, focusing on events where access keys are used. It filters out events with private IP addresses, ensuring only public IPs are considered.

  4. Geolocation Analysis: For each event, it determines the geographical location (country and city) of the IP address used to access AWS resources.

  5. Multi-Country Activity Detection: It summarizes the data to find access keys that have been used from multiple countries. If an access key is used from two or more distinct countries, it flags this as suspicious.

  6. Risk Assessment: The query assesses the risk of compromise:

    • If an access key is used from three or more countries or lacks a verified identity, it is marked as "CRITICAL."
    • Otherwise, it is marked as "HIGH" risk.
  7. Output: The results include details such as the risk level, AWS account ID, access key ID, countries and cities involved, number of distinct IPs, events, denied calls, and a sample of API calls. The results are sorted by the number of distinct countries and events, and only the top 5000 entries are returned.

In summary, this query helps identify potentially compromised AWS access keys by analyzing their usage patterns across different geographical locations and assessing the risk based on the number of countries involved and the presence of verified identity mappings.