{
  "$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/excessive-logon-failures-daily')]",
      "name": "[concat(parameters('workspace'),'/Microsoft.SecurityInsights/excessive-logon-failures-daily')]",
      "type": "Microsoft.OperationalInsights/workspaces/providers/alertRules",
      "kind": "Scheduled",
      "apiVersion": "2023-12-01-preview",
      "properties": {
        "displayName": "Excessive Logon Failures - Outcome Classified",
        "description": "Classifies Windows logon failure activity by what it demands from an analyst instead of alerting on volume alone. Raw failure counts against internet-facing hosts are background noise that asks for nothing, so the rule only fires on state changes: a logon success from a source that was failing against the same account, failures originating inside the network, internet failures reaching a host with no exposure history, a privileged or valid account under multi-source pressure, and lockouts on real accounts. A per-account median baseline from the prior 7 days supplies the spike context, computed independently of the attacker's source so a new attacker IP cannot erase it. Hosts that took internet-sourced failures on several prior days are treated as known-exposed and their internet noise is suppressed by design; that volume belongs in a reporting query, not the incident queue. Every alert carries AlertClass and a per-row Severity so triage starts from the required action.\n\nTABLES: SecurityEvent, IdentityInfo\nCONNECTORS: Security Events via AMA or Windows Security Events; Microsoft Sentinel UEBA (IdentityInfo)\nLICENSE: Microsoft Sentinel; Windows security event collection. UEBA only enriches (account roles); every signal reads the event data.\n\nTUNING:\n1. Query period must be P8D - today plus the 7-day baseline; well under the P14D cap.\n2. TodayFloor - minimum failures today before an account is considered, unless a success from a failing source exists.\n3. SpikeMultiple - multiple of the account's median day that counts as a spike.\n4. SpraySourceFloor and AttackFailFloor - what makes one source a spraying or bursting origin.\n5. SuccessPairFloor - attack-class failures from one source at one account before its later success counts.\n6. ExposedDaysFloor - days with internet failures in the prior 7 that make a host known-exposed.\n7. SensitiveRoles - the roles that make a failing account an admin target; include on-prem Domain Admins.\n\nKNOWN FALSE POSITIVES:\n1. A user who retries a stale credential many times, fixes it and signs in from the same address reads as a success after failures; a quick check with the user closes it.\n2. A vulnerability scanner or admin jump host inside the network can read as internal origin or internal spray; exclude its addresses once confirmed.\n3. A newly built internet-facing host reads as new exposure for its first days until the baseline learns it; confirm the exposure is deliberate.\n\nINVESTIGATION STEPS:\n1. Read AlertClass first; it names the required action.\n2. SuccessAfterFailures: treat as compromise. Contain the host, reset and revoke the account, and hunt forward from FirstSuccess.\n3. InternalBruteForce: the source address is the incident; find the machine behind it and investigate it for compromise.\n4. NewExternalExposure: a host with no exposure history is taking internet failures; find the network change and close or gate the service.\n5. AdminUnderAttack and ValidAccountPressure: confirm lockout policy and MFA, block the sources, and watch for a success.\n6. AccountExists false means the account is not real; the host and the sources are the story, not the name.\n\nBLIND SPOTS:\nAn attacker who validates a password from one address and uses it from another defeats the same-source success join. A single internet source guessing one valid unprivileged account on a known-exposed host stays silent without a lockout or a success; the reporting query shows the pressure. NAT collapses many origins into one address. Accounts outside IdentityInfo rely on failure codes to prove they exist. Low-and-slow failures under the today floor are out of scope for a daily rule. Cloud sign-in brute force is a sibling rule on SigninLogs.\n\nAuthor: Bartosz Wysocki | https://www.itprofessor.cloud\nVersion: 2.0 | 2026-07-19",
        "severity": "Medium",
        "enabled": true,
        "query": "// =====================================================================\n// Excessive Logon Failures - Outcome Classified\n// =====================================================================\n// Tables  : SecurityEvent, IdentityInfo\n// License : Microsoft Sentinel; Windows security event collection; UEBA enriches only\n// Tuning  : see rule description for full tuning notes\n// Author  : Bartosz Wysocki | itprofessor.cloud\n// Version : 2.0 | 2026-07-19\n// =====================================================================\nlet BaselineWindow = 8d;          // today plus 7 prior days for baselines and exposure history\nlet IdentityLookback = 8d;        // matches the query period; one full UEBA sync cycle\nlet TodayFloor = 30;              // minimum failures today, unless a success exists\nlet SpikeMultiple = 5;            // multiple of the account's median day that is a spike\nlet SpraySourceFloor = 5;         // distinct accounts one source failed against\nlet AttackFailFloor = 20;         // attack-class failures from one source\nlet SuccessPairFloor = 5;         // attack fails from one source at one account before its success counts\nlet ExposedDaysFloor = 3;         // prior days with internet failures that mark a host known-exposed\nlet FireThreshold = 5;\n// Scoring weights - a success after failures fires alone; everything else needs a second reason\nlet W_Success = 5;                // success from a source that was failing against the account\nlet W_Internal = 3;               // failures originate inside the network\nlet W_NewExposure = 3;            // internet failures on a host with no exposure history\nlet W_AdminTarget = 3;            // the account holds a sensitive role\nlet W_ValidPressure = 2;          // real account under multi-source attack-shaped spiking pressure\nlet W_Spread = 2;                 // spraying source, counted only internally or on new exposure\nlet W_Spike = 2;                  // today far above the account's own median day\nlet W_Lockout = 1;                // lockouts on a real account\n// Attack-shaped codes; 0xc0000064 is kept so sprays stay visible and ghosts separate from real accounts\nlet AttackSubStatus = dynamic([\n\"0xc000006a\", \"0xc000006d\", \"0xc000006e\", \"0xc0000064\",\n\"0xc0000070\", \"0xc000006f\", \"0xc0000234\", \"0xc0000072\",\n\"0xc000015b\", \"0xc0000413\"\n]);\nlet SensitiveRoles = dynamic([\n\"Global Administrator\", \"Privileged Role Administrator\", \"Privileged Authentication Administrator\",\n\"Security Administrator\", \"User Administrator\", \"Domain Admins\", \"Enterprise Admins\",\n\"Exchange Administrator\", \"SharePoint Administrator\", \"Intune Administrator\", \"Account Operators\"\n]);\n// All user 4625 across today plus the baseline, normalised once; loopback removed\nlet Failures = materialize(SecurityEvent\n    | where TimeGenerated > ago(BaselineWindow)\n    | where EventID == 4625 and AccountType =~ \"User\"\n    | where IpAddress !in (\"127.0.0.1\", \"::1\", \"-\", \"\")\n    | extend AccountSam = tolower(tostring(split(Account, \"\\\\\", 1)[0]))\n    | where isnotempty(AccountSam)\n    | extend SubStatus = tolower(SubStatus)\n    | extend IsAttackFail = SubStatus in (AttackSubStatus)\n    | extend IsExternal = not(ipv4_is_private(IpAddress))\n    | extend Day = bin(TimeGenerated, 1d)\n);\nlet TodayStart = startofday(now());\n// Baseline from the prior seven days only, so today cannot inflate it. The median is cast to\n// real because percentile of a long returns long, and coalesce with 0.0 must not mix types\nlet AccountBaseline = Failures\n    | where TimeGenerated < TodayStart\n    | summarize DailyCount = count() by AccountSam, Day\n    | summarize BaselineMedian = todouble(percentile(DailyCount, 50)), BaselineMaxDay = max(DailyCount) by AccountSam;\nlet AccountHistIps = Failures\n    | where TimeGenerated < TodayStart\n    | summarize HistIps = make_set(IpAddress, 500) by AccountSam;\n// Hosts with internet failures on several prior days are known-exposed; their noise is weather\nlet KnownExposed = toscalar(Failures\n    | where TimeGenerated < TodayStart and IsExternal\n    | summarize ExposedDays = dcount(Day) by Computer\n    | where ExposedDays >= ExposedDaysFloor\n    | summarize make_set(Computer, 10000));\n// Per-source spray context today: how many distinct accounts each origin went after\nlet SourceSprayToday = Failures\n    | where TimeGenerated >= TodayStart\n    | summarize SprayAccounts = dcount(AccountSam), SourceAttackFails = countif(IsAttackFail) by IpAddress\n    | where SprayAccounts >= SpraySourceFloor or SourceAttackFails >= AttackFailFloor;\nlet SprayIps = toscalar(SourceSprayToday | summarize make_set(IpAddress, 100000));\n// A 4624 from a source that already threw attack fails at the account always demands a response\nlet TodayFailPairs = Failures\n    | where TimeGenerated >= TodayStart and IsAttackFail\n    | summarize FirstFail = min(TimeGenerated), PairFails = count() by AccountSam, IpAddress\n    | where PairFails >= SuccessPairFloor;\nlet SuccessAfter = TodayFailPairs\n    | join kind=inner (\n        SecurityEvent\n        | where TimeGenerated >= TodayStart\n        | where EventID == 4624 and AccountType =~ \"User\"\n        | where IpAddress !in (\"127.0.0.1\", \"::1\", \"-\", \"\")\n        | extend AccountSam = tolower(tostring(split(Account, \"\\\\\", 1)[0]))\n        | where isnotempty(AccountSam)\n        | project TimeGenerated, AccountSam, IpAddress\n    ) on AccountSam, IpAddress\n    | where TimeGenerated > FirstFail\n    | summarize SuccessCount = count(), SuccessIps = make_set(IpAddress, 10), FirstSuccess = min(TimeGenerated) by AccountSam;\n// Account roles for the admin signal\nlet IdentityContext = IdentityInfo\n    | where TimeGenerated > ago(IdentityLookback)\n    | summarize arg_max(TimeGenerated, AssignedRoles) by SamName = tolower(AccountName);\n// Today's failures per account, classified by outcome, origin, target and exposure\nFailures\n| where TimeGenerated >= TodayStart\n| summarize\n    StartTime = min(TimeGenerated),\n    EndTime = max(TimeGenerated),\n    CountToday = count(),\n    AttackFailsToday = countif(IsAttackFail),\n    GhostFails = countif(SubStatus == \"0xc0000064\"),\n    LockoutsToday = countif(SubStatus == \"0xc0000234\"),\n    InternalFails = countif(not(IsExternal)),\n    DistinctSources = dcount(IpAddress),\n    InternalSources = dcountif(IpAddress, not(IsExternal)),\n    ExternalSources = dcountif(IpAddress, IsExternal),\n    SourceIps = make_set(IpAddress, 30),\n    PrimaryIp = take_any(IpAddress),\n    Computers = make_set(Computer, 15),\n    ExtComputers = make_set_if(Computer, IsExternal, 15),\n    PrimaryHost = take_any(Computer),\n    SubStatuses = make_set(SubStatus, 15)\n  by AccountSam\n| join kind=leftouter SuccessAfter on AccountSam\n| extend SuccessCount = coalesce(SuccessCount, 0)\n| where CountToday >= TodayFloor or SuccessCount > 0\n| join kind=leftouter AccountBaseline on AccountSam\n| join kind=leftouter AccountHistIps on AccountSam\n| join kind=leftouter IdentityContext on $left.AccountSam == $right.SamName\n| extend BaselineMedian = coalesce(BaselineMedian, 0.0)\n| extend NewSources = set_difference(SourceIps, coalesce(HistIps, dynamic([])))\n| extend NewExpHosts = set_difference(ExtComputers, KnownExposed)\n| extend AccountRoles = tostring(AssignedRoles)\n| extend SprayFromHere = set_intersect(SourceIps, SprayIps)\n| extend AccountExists = isnotempty(SamName) or GhostFails < CountToday\n| extend sSuccess = SuccessCount > 0\n| extend sInternal = InternalFails >= 10 or (InternalFails > 0 and InternalFails * 2 >= CountToday)\n| extend sNewExposure = array_length(NewExpHosts) > 0\n| extend sAdmin = AccountRoles has_any (SensitiveRoles)\n| extend sSpike = CountToday >= (BaselineMedian * SpikeMultiple) and CountToday >= TodayFloor\n| extend sAttackShaped = AttackFailsToday * 2 >= CountToday and AttackFailsToday >= 10\n| extend sValid = AccountExists and sAttackShaped and sSpike and (DistinctSources > 1 or array_length(SprayFromHere) > 0)\n| extend sSpread = array_length(SprayFromHere) > 0 and (InternalFails > 0 or sNewExposure)\n| extend sLockout = LockoutsToday > 0 and AccountExists\n| extend RiskScore =\n      iff(sSuccess, W_Success, 0)\n    + iff(sInternal, W_Internal, 0)\n    + iff(sNewExposure, W_NewExposure, 0)\n    + iff(sAdmin, W_AdminTarget, 0)\n    + iff(sValid, W_ValidPressure, 0)\n    + iff(sSpread, W_Spread, 0)\n    + iff(sSpike, W_Spike, 0)\n    + iff(sLockout, W_Lockout, 0)\n| where RiskScore >= FireThreshold\n| extend AlertClass = case(\n    sSuccess, \"SuccessAfterFailures\",\n    sInternal, \"InternalBruteForce\",\n    sNewExposure, \"NewExternalExposure\",\n    sAdmin, \"AdminUnderAttack\",\n    \"ValidAccountPressure\")\n| extend Severity = case(sSuccess, \"High\", sInternal or sAdmin, \"Medium\", \"Low\")\n| extend Name = AccountSam\n// Same indicator string as the series; built inline because this query brushes the 10000 char cap\n| extend RiskIndicators = trim(@\"\\s\\|\\s*$\", strcat(\n    iff(sSuccess, \"SuccessAfterFail | \", \"\"),\n    iff(sInternal, \"InternalOrigin | \", \"\"),\n    iff(sNewExposure, \"NewExposedHost | \", \"\"),\n    iff(sAdmin, \"AdminTarget | \", \"\"),\n    iff(sValid, \"ValidUnderPressure | \", \"\"),\n    iff(sSpread, \"SprayFromSource | \", \"\"),\n    iff(sSpike, \"BaselineSpike | \", \"\"),\n    iff(sLockout, \"LockoutsSeen | \", \"\")\n))\n| extend BaselineMedian = round(BaselineMedian, 1), SpikeRatio = round(CountToday / (BaselineMedian + 1.0), 1)\n| project\n    StartTime, EndTime, RiskScore, RiskIndicators, AlertClass, Severity,\n    AccountSam, Name, AccountExists, PrimaryIp, PrimaryHost, SourceIps, NewSources,\n    CountToday, BaselineMedian, BaselineMaxDay, SpikeRatio, AttackFailsToday, LockoutsToday,\n    DistinctSources, InternalSources, ExternalSources,\n    SuccessCount, SuccessIps, FirstSuccess,\n    Computers, NewExpHosts, SubStatuses, AccountRoles\n| sort by RiskScore desc, CountToday desc\n",
        "queryFrequency": "PT1H",
        "queryPeriod": "P8D",
        "triggerOperator": "GreaterThan",
        "triggerThreshold": 0,
        "suppressionDuration": "PT1H",
        "suppressionEnabled": false,
        "startTimeUtc": null,
        "tactics": [
          "CredentialAccess",
          "InitialAccess"
        ],
        "techniques": [
          "T1110",
          "T1078"
        ],
        "subTechniques": [
          "T1110.001",
          "T1110.003"
        ],
        "alertRuleTemplateName": null,
        "incidentConfiguration": {
          "createIncident": true,
          "groupingConfiguration": {
            "enabled": true,
            "reopenClosedIncident": false,
            "lookbackDuration": "PT12H",
            "matchingMethod": "Selected",
            "groupByEntities": [
              "Account"
            ],
            "groupByAlertDetails": null,
            "groupByCustomDetails": null
          }
        },
        "eventGroupingSettings": {
          "aggregationKind": "AlertPerResult"
        },
        "alertDetailsOverride": {
          "alertDisplayNameFormat": "{{AlertClass}}: {{AccountSam}}",
          "alertDescriptionFormat": "Account {{AccountSam}}: {{CountToday}} failures today, classified {{AlertClass}}.",
          "alertSeverityColumnName": "Severity"
        },
        "customDetails": {
          "RiskScore": "RiskScore",
          "RiskIndicators": "RiskIndicators",
          "AlertClass": "AlertClass",
          "AccountSam": "AccountSam",
          "AccountExists": "AccountExists",
          "CountToday": "CountToday",
          "BaselineMedian": "BaselineMedian",
          "SpikeRatio": "SpikeRatio",
          "AttackFailsToday": "AttackFailsToday",
          "LockoutsToday": "LockoutsToday",
          "InternalSources": "InternalSources",
          "ExternalSources": "ExternalSources",
          "SourceIps": "SourceIps",
          "NewSources": "NewSources",
          "SuccessCount": "SuccessCount",
          "SuccessIps": "SuccessIps",
          "FirstSuccess": "FirstSuccess",
          "Computers": "Computers",
          "NewExpHosts": "NewExpHosts",
          "AccountRoles": "AccountRoles"
        },
        "entityMappings": [
          {
            "entityType": "Account",
            "fieldMappings": [
              {
                "identifier": "Name",
                "columnName": "Name"
              }
            ]
          },
          {
            "entityType": "IP",
            "fieldMappings": [
              {
                "identifier": "Address",
                "columnName": "PrimaryIp"
              }
            ]
          },
          {
            "entityType": "Host",
            "fieldMappings": [
              {
                "identifier": "HostName",
                "columnName": "PrimaryHost"
              }
            ]
          }
        ],
        "sentinelEntitiesMappings": null,
        "templateVersion": null
      }
    }
  ]
}
