{
  "$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/ti-ip-signin-success')]",
      "name": "[concat(parameters('workspace'),'/Microsoft.SecurityInsights/ti-ip-signin-success')]",
      "type": "Microsoft.OperationalInsights/workspaces/providers/alertRules",
      "kind": "Scheduled",
      "apiVersion": "2023-12-01-preview",
      "properties": {
        "displayName": "TI Mapped IP - Successful Sign-in",
        "description": "Fires when an account successfully signs in from an IP listed in threat intelligence, scored by what makes the success dangerous: single-factor authentication, Entra sign-in risk, a privileged account, a spray backdrop from the same address, indicator confidence and token-replay shape. Failed attempts from listed IPs are context columns, never candidates, because a blocked spray from known-bad infrastructure is internet weather. Indicator values are lowercased so IPv6 matches work, revoked and expired indicators are honoured, and indicators without an expiry stay valid instead of being dropped.\n\nTABLES: SigninLogs, AADNonInteractiveUserSignInLogs, ThreatIntelIndicators, IdentityInfo\nCONNECTORS: Microsoft Entra ID (SignInLogs, NonInteractiveUserSignInLogs); Threat Intelligence (ThreatIntelIndicators); Microsoft Sentinel UEBA (IdentityInfo)\nLICENSE: Microsoft Sentinel; Microsoft Entra ID P1 (sign-in logs); P2 recommended (sign-in risk, UEBA). Without P2 the HighRiskSignIn and PrivilegedAccount signals stay silent.\n\nTUNING:\n1. Query period must be P14D - the 14d indicator and identity lookups only resolve if the rule looks back that far.\n2. ConfidenceFloor - indicator confidence that counts as high; align to your feeds.\n3. SprayFloor - distinct accounts failed against from one IP that count as a spray backdrop.\n4. SensitiveRoles - the roles that make a signed-in account privileged.\n5. BusinessStart / BusinessEnd - local working hours; TimeGenerated is UTC.\n6. Raise W_HighConfidence to 2 if your feeds are curated and you want MFA-protected successes from high-confidence indicators to fire alone.\n\nKNOWN FALSE POSITIVES:\n1. Staff on commercial VPNs or Tor whose egress IP sits in a feed: an MFA-protected, low-risk success scores below threshold and stays silent.\n2. Corporate egress IPs recycled onto low-grade lists: same handling; check TiSources in the row and clean the feed rather than the rule.\n3. A pentest or red team signing in single-factor from flagged infrastructure fires, as it should.\n\nINVESTIGATION STEPS:\n1. Read RiskIndicators; SingleFactorSuccess with SprayBackdrop is spray-then-success, the classic shape.\n2. Read the indicator context in the row: TiDescriptions, TiSources, MaxConfidence, ActivityGroups, LatestValidUntil.\n3. Check the account: UserRoles, Department, UserType; a privileged hit escalates immediately.\n4. Check the session: Apps, Country, SingleFactorCnt versus InteractiveSuccess; NonInteractiveOnly suggests token replay.\n5. Confirm with the user, then revoke sessions and refresh tokens, reset credentials, and review MFA registration for tampering.\n6. Pivot on the IPAddress across the tenant; FailedCount and TargetedUsers in the row already show the blast radius.\n\nBLIND SPOTS:\nFailure-only spray from listed IPs never fires here by design; a spray detection owns that axis. Indicators expressed as CIDR ranges do not equal a single IP and will not match. URL, domain and hash indicators are sibling rules, not this one. A token replay that carries an MFA claim scores low unless risk, privilege or spray stack on top.\n\nAuthor: Bartosz Wysocki | https://www.itprofessor.cloud\nVersion: 1.0 | 2026-07-04",
        "severity": "High",
        "enabled": true,
        "query": "// =====================================================================\n// TI Mapped IP - Successful Sign-in\n// =====================================================================\n// Tables  : SigninLogs, AADNonInteractiveUserSignInLogs, ThreatIntelIndicators, IdentityInfo\n// License : Microsoft Sentinel; Entra ID P1; P2 recommended (sign-in risk, UEBA)\n// Tuning  : see rule description for full tuning notes\n// Author  : Bartosz Wysocki | itprofessor.cloud\n// Version : 1.0 | 2026-07-04\n// =====================================================================\nlet DetectionWindow = 1h;\nlet TiLookback = 14d;             // indicator ingestion window; the rule query period must match\nlet IdentityLookback = 14d;       // full UEBA sync cycle, for roles and department\nlet ConfidenceFloor = 75;         // indicator confidence that counts as high\nlet SprayFloor = 5;               // distinct accounts failed against from one IP in the window\nlet BusinessStart = 7;\nlet BusinessEnd = 19;\nlet FireThreshold = 2;\n// Scoring weights - the success is the gate; these decide whether it is worth an analyst\nlet W_NoMfa = 3;                  // interactive success that satisfied only a single factor\nlet W_HighRisk = 2;               // Entra scored the successful sign-in medium or high\nlet W_Privileged = 2;             // the account holds a sensitive directory role\nlet W_SprayBackdrop = 2;          // the same IP also failed against several other accounts\nlet W_HighConfidence = 1;         // indicator confidence at or above ConfidenceFloor\nlet W_NonInteractiveOnly = 1;     // success arrived only through non-interactive flows; token-replay shape\nlet W_OffHours = 1;               // activity outside working hours\nlet SensitiveRoles = dynamic([\n\"Global Administrator\", \"Privileged Role Administrator\", \"Privileged Authentication Administrator\",\n\"Security Administrator\", \"User Administrator\", \"Application Administrator\",\n\"Cloud Application Administrator\", \"Hybrid Identity Administrator\",\n\"Exchange Administrator\", \"SharePoint Administrator\", \"Intune Administrator\"\n]);\n// Sign-ins in the window, both flavours, IPs lowercased so IPv6 can ever match an indicator\nlet WindowSignins = materialize(union isfuzzy=true\n    (SigninLogs\n        | where TimeGenerated > ago(DetectionWindow)\n        | extend IsInteractive = true),\n    (AADNonInteractiveUserSignInLogs\n        | where TimeGenerated > ago(DetectionWindow)\n        | extend Status = todynamic(Status), LocationDetails = todynamic(LocationDetails)\n        | extend IsInteractive = false)\n    | extend IPAddress = tolower(IPAddress)\n    | extend UserPrincipalName = tolower(UserPrincipalName)\n    | extend IsSuccess = tostring(ResultType) == \"0\"\n    | extend AuthReq = tostring(AuthenticationRequirement)\n    | extend IsRisky = tostring(RiskLevelDuringSignIn) in (\"high\", \"medium\")\n    | extend Country = tostring(LocationDetails.countryOrRegion)\n    | extend HourOfDay = datetime_part(\"Hour\", TimeGenerated)\n    | extend OffHoursEvent = HourOfDay < BusinessStart or HourOfDay >= BusinessEnd or dayofweek(TimeGenerated) in (0d, 6d)\n);\nlet SigninIpSet = toscalar(WindowSignins | summarize make_set(IPAddress, 1000000));\n// Active, unrevoked, unexpired IP indicators seen against the window's IPs, one row per IP.\n// Lowercase both sides; indicators without an expiry stay valid instead of being dropped\nlet TI = ThreatIntelIndicators\n    | where TimeGenerated > ago(TiLookback)\n    | extend IndicatorType = replace(@\"\\[|\\]|\\\"\"\", \"\", tostring(split(ObservableKey, \":\", 0)))\n    | where IndicatorType in (\"ipv4-addr\", \"ipv6-addr\", \"network-traffic\")\n    | extend TiIp = tolower(trim(\" \", ObservableValue))\n    | where TiIp in (SigninIpSet)\n    | summarize arg_max(TimeGenerated, *) by Id, ObservableValue\n    | where IsActive == true and Revoked != true\n    | where isnull(ValidUntil) or ValidUntil > now()\n    | extend Description = tostring(parse_json(Data).description)\n    | where Description !contains_cs \"State: inactive;\" and Description !contains_cs \"State: falsepos;\"\n    | extend ActivityGroup = extract(@\"ActivityGroup:(\\S+)\", 1, tostring(parse_json(Data).labels))\n    | summarize\n        MaxConfidence = max(Confidence),\n        TiSources = make_set(SourceSystem, 10),\n        TiDescriptions = make_set(Description, 5),\n        ActivityGroups = make_set_if(ActivityGroup, isnotempty(ActivityGroup), 5),\n        TiIds = make_set(Id, 10),\n        LatestValidUntil = max(ValidUntil)\n      by TiIp;\n// Per-IP failure context: who else this address went after in the same window\nlet IpContext = WindowSignins\n    | summarize FailedCount = countif(IsSuccess == false),\n                TargetedUsers = dcountif(UserPrincipalName, IsSuccess == false)\n      by IPAddress;\n// Account context for the signed-in user\nlet IdentityContext = IdentityInfo\n    | where TimeGenerated > ago(IdentityLookback)\n    | summarize arg_max(TimeGenerated, AssignedRoles, Department, UserType) by AccountUPN = tolower(AccountUPN);\n// Successful sign-ins from listed IPs, one row per account and IP, scored\nWindowSignins\n| where IsSuccess\n| summarize\n    StartTime = min(TimeGenerated),\n    EndTime = max(TimeGenerated),\n    SuccessCount = count(),\n    InteractiveSuccess = countif(IsInteractive),\n    SingleFactorCnt = countif(IsInteractive and AuthReq =~ \"singleFactorAuthentication\"),\n    RiskySuccesses = countif(IsRisky),\n    Apps = make_set(AppDisplayName, 10),\n    Country = take_any(Country),\n    OffHoursCount = countif(OffHoursEvent)\n  by UserPrincipalName, IPAddress\n| join kind=inner TI on $left.IPAddress == $right.TiIp\n| join kind=leftouter IpContext on IPAddress\n| join kind=leftouter IdentityContext on $left.UserPrincipalName == $right.AccountUPN\n| extend UserRoles = tostring(AssignedRoles)\n| extend sNoMfa = SingleFactorCnt > 0\n| extend sHighRisk = RiskySuccesses > 0\n| extend sPrivileged = UserRoles has_any (SensitiveRoles)\n| extend sSpray = TargetedUsers >= SprayFloor\n| extend sHighConf = MaxConfidence >= ConfidenceFloor\n| extend sNonInteractive = InteractiveSuccess == 0\n| extend sOffHours = OffHoursCount > 0\n| extend RiskScore =\n      iff(sNoMfa, W_NoMfa, 0)\n    + iff(sHighRisk, W_HighRisk, 0)\n    + iff(sPrivileged, W_Privileged, 0)\n    + iff(sSpray, W_SprayBackdrop, 0)\n    + iff(sHighConf, W_HighConfidence, 0)\n    + iff(sNonInteractive, W_NonInteractiveOnly, 0)\n    + iff(sOffHours, W_OffHours, 0)\n| where RiskScore >= FireThreshold\n| extend Name = tostring(split(UserPrincipalName, \"@\", 0)[0]), UPNSuffix = tostring(split(UserPrincipalName, \"@\", 1)[0])\n| extend Risk_1 = iff(sNoMfa, \"SingleFactorSuccess\", \"\")\n| extend Risk_2 = iff(sHighRisk, \"HighRiskSignIn\", \"\")\n| extend Risk_3 = iff(sPrivileged, \"PrivilegedAccount\", \"\")\n| extend Risk_4 = iff(sSpray, \"SprayBackdrop\", \"\")\n| extend Risk_5 = iff(sHighConf, \"HighConfidenceIoc\", \"\")\n| extend Risk_6 = iff(sNonInteractive, \"NonInteractiveOnly\", \"\")\n| extend Risk_7 = iff(sOffHours, \"OffHoursActivity\", \"\")\n| extend RiskIndicators = trim(@\"\\s\\|\\s*$\", strcat(\n    iff(isnotempty(Risk_1), strcat(Risk_1, \" | \"), \"\"),\n    iff(isnotempty(Risk_2), strcat(Risk_2, \" | \"), \"\"),\n    iff(isnotempty(Risk_3), strcat(Risk_3, \" | \"), \"\"),\n    iff(isnotempty(Risk_4), strcat(Risk_4, \" | \"), \"\"),\n    iff(isnotempty(Risk_5), strcat(Risk_5, \" | \"), \"\"),\n    iff(isnotempty(Risk_6), strcat(Risk_6, \" | \"), \"\"),\n    iff(isnotempty(Risk_7), strcat(Risk_7, \" | \"), \"\")\n))\n| project\n    StartTime, EndTime, RiskScore, RiskIndicators,\n    UserPrincipalName, Name, UPNSuffix, IPAddress, Country,\n    SuccessCount, InteractiveSuccess, SingleFactorCnt, RiskySuccesses,\n    FailedCount, TargetedUsers, Apps,\n    MaxConfidence, TiSources, TiDescriptions, ActivityGroups, TiIds, LatestValidUntil,\n    UserRoles, Department, UserType, OffHoursCount\n| sort by RiskScore desc, EndTime desc\n",
        "queryFrequency": "PT1H",
        "queryPeriod": "P14D",
        "triggerOperator": "GreaterThan",
        "triggerThreshold": 0,
        "suppressionDuration": "PT1H",
        "suppressionEnabled": false,
        "startTimeUtc": null,
        "tactics": [
          "InitialAccess"
        ],
        "techniques": [
          "T1078"
        ],
        "subTechniques": [
          "T1078.004"
        ],
        "alertRuleTemplateName": null,
        "incidentConfiguration": {
          "createIncident": true,
          "groupingConfiguration": {
            "enabled": true,
            "reopenClosedIncident": false,
            "lookbackDuration": "PT8H",
            "matchingMethod": "Selected",
            "groupByEntities": [
              "IP"
            ],
            "groupByAlertDetails": null,
            "groupByCustomDetails": null
          }
        },
        "eventGroupingSettings": {
          "aggregationKind": "AlertPerResult"
        },
        "alertDetailsOverride": {
          "alertDisplayNameFormat": "Successful sign-in from TI listed IP {{IPAddress}}",
          "alertDescriptionFormat": "{{UserPrincipalName}} signed in from TI listed {{IPAddress}}. Risk indicators: {{RiskIndicators}}"
        },
        "customDetails": {
          "RiskScore": "RiskScore",
          "RiskIndicators": "RiskIndicators",
          "MaxConfidence": "MaxConfidence",
          "TiSources": "TiSources",
          "TiDescriptions": "TiDescriptions",
          "ActivityGroups": "ActivityGroups",
          "TiIds": "TiIds",
          "LatestValidUntil": "LatestValidUntil",
          "SuccessCount": "SuccessCount",
          "SingleFactorCnt": "SingleFactorCnt",
          "RiskySuccesses": "RiskySuccesses",
          "FailedCount": "FailedCount",
          "TargetedUsers": "TargetedUsers",
          "Apps": "Apps",
          "Country": "Country",
          "UserRoles": "UserRoles",
          "Department": "Department",
          "UserType": "UserType"
        },
        "entityMappings": [
          {
            "entityType": "Account",
            "fieldMappings": [
              {
                "identifier": "Name",
                "columnName": "Name"
              },
              {
                "identifier": "UPNSuffix",
                "columnName": "UPNSuffix"
              }
            ]
          },
          {
            "entityType": "IP",
            "fieldMappings": [
              {
                "identifier": "Address",
                "columnName": "IPAddress"
              }
            ]
          }
        ],
        "sentinelEntitiesMappings": null,
        "templateVersion": null
      }
    }
  ]
}