{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "workspace": {
            "type": "String"
        }
    },
    "resources": [
        {
            "id": "[concat(resourceId('Microsoft.OperationalInsights/workspaces/providers', parameters('workspace'), 'Microsoft.SecurityInsights'),'/alertRules/successful-logon-one-ip-credential-failure-another')]",
            "name": "[concat(parameters('workspace'),'/Microsoft.SecurityInsights/successful-logon-one-ip-credential-failure-another')]",
            "type": "Microsoft.OperationalInsights/workspaces/providers/alertRules",
            "kind": "Scheduled",
            "apiVersion": "2023-12-01-preview",
            "properties": {
                "displayName": "Successful Logon From One IP, Credential Failure From Another - Entra ID",
                "description": "Correlates a successful sign-in to an app with a credential-type sign-in failure (50126 wrong password, 50056 null password, 50053 locked by bad passwords) against the same app from a different IP within a short window. This surfaces credential guessing running in parallel with a live, legitimate session rather than a simple fumbled login. Every failure is filtered to credential-guessing result codes, so Conditional Access and MFA policy failures never enter the correlation. Country mismatch, account lockout, sign-in risk, failure burst, target privilege, guest status and UEBA investigation priority are weighted into a score, and the pair only alerts once the score crosses the threshold. Interactive and non-interactive sign-ins are both evaluated.\n\nTABLES: SigninLogs, AADNonInteractiveUserSignInLogs, IdentityInfo, BehaviorAnalytics\nCONNECTORS: Microsoft Entra ID (SignInLogs, NonInteractiveUserSignInLogs); Microsoft Sentinel UEBA (IdentityInfo, BehaviorAnalytics)\nLICENSE: Microsoft Sentinel; Microsoft Entra ID P1 (sign-in logs), P2 recommended (sign-in risk, UEBA)\n\nTUNING:\n1. LogonDiff - how close the success and failure must be to correlate.\n2. DetectionWindow - the sign-in slice to correlate; align the rule run frequency to it.\n3. Keep the rule query period at P14D - the IdentityInfo lookback uses ago(14d) and only resolves if the rule looks back that far.\n4. ExcludedApps - legacy-auth-heavy apps that throw benign 50126 from cached credentials.\n5. BurstThreshold - failed credential attempts from one IP that count as a burst.\n6. UebaThreshold - BehaviorAnalytics InvestigationPriority (0-10) treated as elevated.\n7. W_* weights and ScoreThreshold - shift these to fit your environment's noise profile.\n8. The UEBA and IdentityInfo joins are optional; remove them if UEBA is not enabled.\n\nKNOWN FALSE POSITIVES:\n1. A second device blocked by Conditional Access or MFA - excluded by the credential-code gate.\n2. A user's own device retrying a cached old password - scores low; a single local failure is suppressed.\n3. Legacy-auth clients with stale credentials - confine via ExcludedApps.\n\nINVESTIGATION STEPS:\n1. Read RiskIndicators and Score - CountryMismatch, AccountLockout, HighRiskFailure, FailureBurst, PrivilegedAccount, UEBAElevated, GuestAccount.\n2. Compare FailedIP / FailedCountry against SuccessIPs / SuccessCountries - a geographic split raises confidence.\n3. Confirm whether the account is privileged (AssignedRoles) or a guest (UserType).\n4. Review FailedAttempts, FailedResultTypes and MaxInvestigationPriority for volume and UEBA context.\n5. Check whether any success later originated from FailedIP - a hit means the attacker likely authenticated.\n6. If compromise is suspected, revoke sessions, reset credentials, and confirm MFA is enforced for the account.\n\nBLIND SPOTS:\nOnly fires when a success and a credential failure land on the same app within LogonDiff, so slow guessing or attempts on a different app are missed. Success or failure events split across separate hourly runs are not correlated. Country enrichment depends on LocationDetails being populated. Attacks that succeed on the first attempt, with no failure, produce no pair. Excluded apps are blind by design.\n\nAuthor: Bartosz Wysocki | https://www.itprofessor.cloud\nVersion: 1.0 | 2026-06-17",
                "severity": "Medium",
                "enabled": true,
                "query": "// =====================================================================\n// Successful Logon From One IP, Credential Failure From Another - Entra ID\n// =====================================================================\n// Tables  : SigninLogs, AADNonInteractiveUserSignInLogs, IdentityInfo, BehaviorAnalytics\n// License : Microsoft Sentinel; Microsoft Entra ID P1\n// Tuning  : see rule description for full tuning notes\n// Author  : Bartosz Wysocki | itprofessor.cloud\n// Version : 1.0 | 2026-06-17\n// =====================================================================\nlet DetectionWindow = 1h;\nlet LogonDiff = 10m;\nlet IdentityLookback = 14d;       // full directory resync cycle; guarantees complete identity enrichment\nlet ExcludedApps = dynamic([\"Office 365 Exchange Online\", \"Skype for Business Online\"]);\nlet CredentialFailures = dynamic([\"50126\", \"50056\", \"50053\"]);  // wrong password, null password, locked by bad passwords\nlet BurstThreshold = 5;           // failed credential attempts from the IP within the window\nlet UebaThreshold = 4;            // BehaviorAnalytics InvestigationPriority (0-10) treated as elevated\nlet SensitiveRoles = dynamic([\n\"Global Administrator\",\n\"Privileged Role Administrator\",\n\"Privileged Authentication Administrator\",\n\"Security Administrator\",\n\"Exchange Administrator\",\n\"SharePoint Administrator\",\n\"User Administrator\",\n\"Intune Administrator\",\n\"Application Administrator\",\n\"Hybrid Identity Administrator\"\n]);\n// Scoring weights - higher weight for the signals that most separate guessing from a fumbled login\nlet W_CountryMismatch = 3;\nlet W_AccountLockout  = 3;\nlet W_HighRiskFailure = 3;\nlet W_FailureBurst    = 2;\nlet W_Privileged      = 2;\nlet W_Ueba            = 2;\nlet W_Guest           = 1;\nlet ScoreThreshold    = 5;\n// Success on an app, then a credential failure on the same app from a different IP within LogonDiff\nlet CorrelatedPairs = (tableName:string) {\n    table(tableName)\n    | where TimeGenerated > ago(DetectionWindow)\n    | where AppDisplayName !in~ (ExcludedApps)\n    | where ResultType == \"0\"\n    | project SuccessTime = TimeGenerated, UserPrincipalName = tolower(UserPrincipalName),\n              SuccessIP = IPAddress, SuccessCountry = tostring(LocationDetails.countryOrRegion), AppDisplayName\n    | join kind=inner (\n        table(tableName)\n        | where TimeGenerated > ago(DetectionWindow)\n        | where AppDisplayName !in~ (ExcludedApps)\n        | where ResultType in (CredentialFailures)\n        | project FailedTime = TimeGenerated, UserPrincipalName = tolower(UserPrincipalName),\n                  FailedIP = IPAddress, FailedCountry = tostring(LocationDetails.countryOrRegion),\n                  FailedLocation = Location, AppDisplayName,\n                  FailedResultType = ResultType, FailedRisk = tostring(RiskLevelDuringSignIn)\n    ) on UserPrincipalName, AppDisplayName\n    | where SuccessTime < FailedTime and FailedTime - SuccessTime <= LogonDiff and FailedIP != SuccessIP\n};\nlet Pairs = union isfuzzy=true\n    CorrelatedPairs(\"SigninLogs\"),\n    CorrelatedPairs(\"AADNonInteractiveUserSignInLogs\");\n// Identity context (privilege / guest), keyed on UPN\nlet IdentityContext = IdentityInfo\n    | where TimeGenerated > ago(IdentityLookback)\n    | summarize arg_max(TimeGenerated, AccountDisplayName, Department, JobTitle, AssignedRoles, UserType, IsAccountEnabled) by AccountUPN = tolower(AccountUPN);\n// UEBA investigation priority for the user acting from the failed IP\nlet UebaContext = BehaviorAnalytics\n    | where TimeGenerated > ago(DetectionWindow)\n    | where ActivityType in (\"FailedLogOn\", \"LogOn\")\n    | where isnotempty(SourceIPAddress)\n    | summarize MaxInvestigationPriority = max(InvestigationPriority) by BAUser = tolower(UserPrincipalName), BAIP = SourceIPAddress;\nPairs\n| extend HighRiskFailureRow = FailedRisk in (\"high\", \"medium\")\n| summarize\n    SuccessTime = max(SuccessTime),\n    FailedTime = max(FailedTime),\n    FailedAttempts = dcount(FailedTime),\n    HighRiskFailureCount = countif(HighRiskFailureRow),\n    SuccessIPs = make_set(SuccessIP, 10),\n    SuccessCountries = make_set(SuccessCountry, 10),\n    FailedCountry = max(FailedCountry),\n    FailedLocation = max(FailedLocation),\n    Apps = make_set(AppDisplayName, 10),\n    FailedResultTypes = make_set(FailedResultType, 5)\n  by UserPrincipalName, FailedIP\n| join kind=leftouter IdentityContext on $left.UserPrincipalName == $right.AccountUPN\n| join kind=leftouter UebaContext on $left.UserPrincipalName == $right.BAUser and $left.FailedIP == $right.BAIP\n| extend CountryMismatch = isnotempty(FailedCountry) and not(set_has_element(SuccessCountries, FailedCountry))\n| extend IsAccountLockout = set_has_element(FailedResultTypes, \"50053\")\n| extend HighRiskFailure = HighRiskFailureCount > 0\n| extend FailureBurst = FailedAttempts >= BurstThreshold\n| extend IsPrivileged = tostring(AssignedRoles) has_any (SensitiveRoles)\n| extend UEBAElevated = isnotnull(MaxInvestigationPriority) and MaxInvestigationPriority >= UebaThreshold\n| extend IsGuest = tostring(UserType) =~ \"Guest\"\n| extend Score = toint(CountryMismatch) * W_CountryMismatch\n               + toint(IsAccountLockout) * W_AccountLockout\n               + toint(HighRiskFailure) * W_HighRiskFailure\n               + toint(FailureBurst)    * W_FailureBurst\n               + toint(IsPrivileged)    * W_Privileged\n               + toint(UEBAElevated)    * W_Ueba\n               + toint(IsGuest)         * W_Guest\n| where Score >= ScoreThreshold\n| extend RiskIndicators = trim(@\"\\s\\|\\s*$\", strcat(\n    iff(CountryMismatch, \"CountryMismatch | \", \"\"),\n    iff(IsAccountLockout, \"AccountLockout | \", \"\"),\n    iff(HighRiskFailure, \"HighRiskFailure | \", \"\"),\n    iff(FailureBurst, \"FailureBurst | \", \"\"),\n    iff(IsPrivileged, \"PrivilegedAccount | \", \"\"),\n    iff(UEBAElevated, \"UEBAElevated | \", \"\"),\n    iff(IsGuest, \"GuestAccount | \", \"\")\n))\n| extend Name = tostring(split(UserPrincipalName, \"@\", 0)[0]), UPNSuffix = tostring(split(UserPrincipalName, \"@\", 1)[0])\n| project\n    SuccessTime, FailedTime, Score, RiskIndicators,\n    UserPrincipalName, Name, UPNSuffix,\n    FailedIP, FailedCountry, FailedLocation, SuccessIPs, SuccessCountries,\n    FailedAttempts, FailedResultTypes, Apps,\n    MaxInvestigationPriority, AccountDisplayName, Department, JobTitle, AssignedRoles, UserType\n| sort by Score desc",
                "queryFrequency": "PT1H",
                "queryPeriod": "P14D",
                "triggerOperator": "GreaterThan",
                "triggerThreshold": 0,
                "suppressionDuration": "PT1H",
                "suppressionEnabled": false,
                "startTimeUtc": null,
                "tactics": [
                    "CredentialAccess"
                ],
                "techniques": [
                    "T1110"
                ],
                "subTechniques": [
                    "T1110.001"
                ],
                "alertRuleTemplateName": null,
                "incidentConfiguration": {
                    "createIncident": true,
                    "groupingConfiguration": {
                        "enabled": true,
                        "reopenClosedIncident": false,
                        "lookbackDuration": "PT6H",
                        "matchingMethod": "Selected",
                        "groupByEntities": [
                            "Account"
                        ],
                        "groupByAlertDetails": null,
                        "groupByCustomDetails": null
                    }
                },
                "eventGroupingSettings": {
                    "aggregationKind": "SingleAlert"
                },
                "alertDetailsOverride": {
                    "alertDisplayNameFormat": "Logon success then credential failure for {{UserPrincipalName}} ({{RiskIndicators}})",
                    "alertDescriptionFormat": "{{UserPrincipalName}} had a successful sign-in, then credential failures from {{FailedIP}} ({{FailedCountry}})."
                },
                "customDetails": {
                    "Score": "Score",
                    "RiskIndicators": "RiskIndicators",
                    "FailedAttempts": "FailedAttempts",
                    "FailedCountry": "FailedCountry",
                    "FailedLocation": "FailedLocation",
                    "UEBAPriority": "MaxInvestigationPriority",
                    "AssignedRoles": "AssignedRoles",
                    "Apps": "Apps"
                },
                "entityMappings": [
                    {
                        "entityType": "Account",
                        "fieldMappings": [
                            {
                                "identifier": "FullName",
                                "columnName": "UserPrincipalName"
                            },
                            {
                                "identifier": "Name",
                                "columnName": "Name"
                            },
                            {
                                "identifier": "UPNSuffix",
                                "columnName": "UPNSuffix"
                            }
                        ]
                    },
                    {
                        "entityType": "IP",
                        "fieldMappings": [
                            {
                                "identifier": "Address",
                                "columnName": "FailedIP"
                            }
                        ]
                    }
                ],
                "sentinelEntitiesMappings": null,
                "templateVersion": null
            }
        }
    ]
}
