Query Details

13 Geo Top Threat Ips

Query

// REVIEW ONLY workbook query: 🌐 5.3 Top External Threat Source IPs — Geolocation, Trust Status & Microsoft Entra Overlap
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);
let AwsByIp = union isfuzzy=true
  (datatable(TimeGenerated:datetime, RecipientAccountId:string, UserIdentityAccountId:string, UserIdentityAccessKeyId:string, UserIdentityArn:string, UserIdentityType:string, SourceIpAddress:string, EventSource:string, EventName:string, ReadOnly:bool, ErrorCode:string)[]),
  (AWSCloudTrail | where TimeGenerated between (Start .. End)
   | project TimeGenerated, RecipientAccountId, UserIdentityAccountId, UserIdentityAccessKeyId, UserIdentityArn, UserIdentityType, SourceIpAddress, EventSource, EventName, ReadOnly, ErrorCode)
| where (UseAllAccounts or RecipientAccountId == AccountFilter or UserIdentityAccountId == AccountFilter)
| where isnotempty(SourceIpAddress) and isnotnull(parse_ipv4(SourceIpAddress)) and not(ipv4_is_private(SourceIpAddress))
| extend AWSAccountId = UserIdentityAccountId, AwsAccessKeyId = UserIdentityAccessKeyId, AwsPrincipalArn = UserIdentityArn
| join kind=leftouter IdentityMap on AWSAccountId, AwsAccessKeyId, AwsPrincipalArn
| summarize AwsEvents = count(),
    DeniedCalls = countif(isnotempty(ErrorCode)),
    MutatingCalls = countif(ReadOnly == false),
    SecretOrIamCalls = countif(EventName == "GetSecretValue" or (EventSource == "iam.amazonaws.com" and ReadOnly == false) or UserIdentityType =~ "Root"),
    MappedEvents = countif(isnotempty(EntraObjectId)),
    TargetAwsAccounts = dcount(RecipientAccountId),
    SamplePrincipals = make_set(UserIdentityArn, 5),
    SampleApis = make_set(EventName, 8)
    by SourceIp = SourceIpAddress;
let EntraByIp = union isfuzzy=true
  (datatable(IPAddress:string, Principal:string)[]),
  (SigninLogs | where TimeGenerated between (Start .. End) | project IPAddress, Principal=UserPrincipalName),
  (AADNonInteractiveUserSignInLogs | where TimeGenerated between (Start .. End) | project IPAddress, Principal=UserPrincipalName),
  (AADServicePrincipalSignInLogs | where TimeGenerated between (Start .. End) | project IPAddress, Principal=ServicePrincipalName)
| where isnotempty(IPAddress) and isnotnull(parse_ipv4(IPAddress)) and not(ipv4_is_private(IPAddress))
| summarize EntraSignIns = count(), EntraPrincipals = make_set(Principal, 5) by SourceIp = IPAddress;
AwsByIp
| join kind=leftouter EntraByIp on SourceIp
| extend Geo = geo_info_from_ip_address(SourceIp)
| extend Country = coalesce(iff(isnotempty(tostring(Geo.country)), tostring(Geo.country), ""), "Unknown"),
    City = coalesce(iff(isnotempty(tostring(Geo.city)), tostring(Geo.city), ""), "Unknown"),
    EntraSignIns = coalesce(EntraSignIns, long(0)),
    ThreatScore = (SecretOrIamCalls * 15) + (DeniedCalls * 3) + (MutatingCalls * 2) + iff(MappedEvents == 0, 20, 0) + iff(coalesce(EntraSignIns, long(0)) > 0 and MappedEvents == 0, 25, 0)
| extend LocationStatus = case(
    MappedEvents == 0 and DeniedCalls >= 5, "🔴 Untrusted / Unmapped Recon IP",
    MappedEvents == 0, "🟠 Unmapped External Location",
    "🟢 Verified Identity Bridge"),
    ThreatLevel = case(
    ThreatScore >= 60 or (SecretOrIamCalls > 0 and MappedEvents == 0), "🔴 CRITICAL - Compromise / Secret Risk",
    ThreatScore >= 30 or DeniedCalls >= 10, "🟠 HIGH - Active Recon / Mutation",
    MappedEvents == 0, "🟡 Medium - Unmapped External IP",
    "🟢 Low - Verified Routine IP")
| project ThreatLevel, LocationStatus, SourceIp, Country, City, ThreatScore, AwsEvents, DeniedCalls, MutatingCalls, SecretOrIamCalls, EntraSignIns, TargetAwsAccounts, SamplePrincipals, EntraPrincipals, SampleApis
| order by ThreatScore desc, AwsEvents desc
| take 5000

Explanation

This query is designed to analyze and identify potential external threats based on IP addresses interacting with AWS and Microsoft Entra (formerly Azure AD) services. Here's a simplified breakdown of what the query does:

  1. Time Range and Account Filtering: It sets a time range and filters based on AWS account information, allowing for either specific account analysis or all accounts.

  2. Identity Mapping: It creates a map of AWS identities that are verified and have evidence of mapping to Microsoft Entra identities. This helps in identifying known and trusted identities.

  3. AWS Events by IP: It gathers AWS CloudTrail events, focusing on external IP addresses (non-private) and counts various types of activities:

    • Total events
    • Denied access attempts
    • Changes made (mutating calls)
    • Access to secrets or IAM (Identity and Access Management) operations
    • Events that map to known Entra identities
    • Unique AWS accounts targeted
    • Samples of user identities and API calls involved
  4. Entra Sign-ins by IP: It collects sign-in logs from Microsoft Entra services, focusing on external IPs, and counts the number of sign-ins and unique principals (users or service principals) involved.

  5. Combining Data: It combines the AWS and Entra data by IP address, adds geolocation information, and calculates a threat score based on the types of activities detected.

  6. Threat Assessment: It assigns a threat level and location status to each IP based on the calculated threat score and mapping status:

    • Threat Level: Ranges from "Low" (verified routine IP) to "Critical" (potential compromise or secret risk).
    • Location Status: Indicates whether the IP is trusted, untrusted, or unmapped.
  7. Output: The query outputs a list of up to 5000 IP addresses, sorted by threat score and AWS event count, along with details like country, city, threat score, and sample activities.

In summary, this query helps identify and prioritize potential external threats by analyzing IP addresses interacting with AWS and Microsoft Entra services, considering both activity patterns and identity mappings.