{
  "$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-officeactivity')]",
      "name": "[concat(parameters('workspace'),'/Microsoft.SecurityInsights/ti-ip-officeactivity')]",
      "type": "Microsoft.OperationalInsights/workspaces/providers/alertRules",
      "kind": "Scheduled",
      "apiVersion": "2023-12-01-preview",
      "properties": {
        "displayName": "TI Mapped IP - Office Activity",
        "description": "Fires when a session operating from a threat intelligence listed IP performs Office 365 activity worth an analyst: exfiltration-class operations (downloads, bulk sync, mail item access, anonymous links), mailbox manipulation (inbox rules, forwarding, permissions), or mass activity, weighted with account privilege, indicator confidence, failed-operation bursts and timing. Every OfficeActivity match is post-authentication, so this rule scores what the session did; the companion sign-in rule watches how it got in. Ordinary work by staff behind VPN-listed egress scores below threshold. Reads the current ThreatIntelIndicators table; TLP markings are surfaced, and rows whose client IP cannot be parsed are dropped.\n\nTABLES: OfficeActivity, ThreatIntelIndicators, IdentityInfo\nCONNECTORS: Microsoft 365 (OfficeActivity); Threat Intelligence (ThreatIntelIndicators); Microsoft Sentinel UEBA (IdentityInfo)\nLICENSE: Microsoft Sentinel; Microsoft 365 audit. UEBA only enriches (roles, department). MailItemsAccessed requires Purview Audit Premium (E5); without it that operation never appears and the file-side operations carry the signal.\n\nTUNING:\n1. Query period must be P14D - the 14d indicator and identity lookups only resolve if the rule looks back that far.\n2. ExfilOps / MailManipOps - extend to your estate, for example eDiscovery export operations.\n3. MassFloor / ObjectFloor - events and distinct objects that count as mass activity.\n4. FailFloor - explicitly failed operations that count as a probing burst.\n5. ConfidenceFloor - indicator confidence that counts as high; align to your feeds.\n6. BusinessStart / BusinessEnd - local working hours; TimeGenerated is UTC.\n\nKNOWN FALSE POSITIVES:\n1. Staff behind VPN or Tor egress that sits in a feed doing ordinary work: a handful of routine operations scores below threshold and stays silent.\n2. The same staff member legitimately downloading a project folder fires on ExfilOperations; one look at bulk movement from listed infrastructure is the design.\n3. OneDrive sync retry storms producing failed-operation bursts: weight one, never fires alone.\n\nINVESTIGATION STEPS:\n1. Read RiskIndicators; ExfilOperations with MailboxManipulation is business email compromise end to end.\n2. Read ObjectsSample and Operations; the paths and actions are the blast radius.\n3. Read the indicator context: TiDescriptions, TiSources, MaxConfidence, ActivityGroups, TlpLevels, LatestValidUntil.\n4. Check the account: UserRoles, Department, UserType; UsersFromIp shows whether the address touched others.\n5. Pair with the sign-in companion rule for the same IP to see how the session was opened.\n6. If malicious: revoke sessions and tokens, remove inbox rules and forwarding, review sharing links created, and preserve the audit trail.\n\nBLIND SPOTS:\nRecords without a ClientIP, and rows whose address cannot be parsed, are out of scope. Indicators expressed as CIDR ranges do not equal a single address and will not match. Without E5 audit, MailItemsAccessed is invisible. Graph API access that does not surface in OfficeActivity is a different telemetry problem. Failure-only probing never fires alone by design.\n\nAuthor: Bartosz Wysocki | https://www.itprofessor.cloud\nVersion: 1.0 | 2026-07-05",
        "severity": "High",
        "enabled": true,
        "query": "// =====================================================================\n// TI Mapped IP - Office Activity\n// =====================================================================\n// Tables  : OfficeActivity, ThreatIntelIndicators, IdentityInfo\n// License : Microsoft Sentinel; M365 audit; UEBA enriches only; MailItemsAccessed needs E5 audit\n// Tuning  : see rule description for full tuning notes\n// Author  : Bartosz Wysocki | itprofessor.cloud\n// Version : 1.0 | 2026-07-05\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 MassFloor = 30;               // events from one user and IP that count as mass activity\nlet ObjectFloor = 15;             // distinct objects touched that count as mass activity\nlet FailFloor = 10;               // explicitly failed operations that count as a probing burst\nlet BusinessStart = 7;\nlet BusinessEnd = 19;\nlet FireThreshold = 4;\n// Scoring weights - what the session did decides; soft context cannot fire on its own\nlet W_ExfilOps = 4;               // download, bulk sync, mail item access or anonymous link operations\nlet W_MailManip = 4;              // inbox rules, forwarding or mailbox permission changes; the BEC toolkit\nlet W_MassActivity = 2;           // event or distinct-object volume past the floors\nlet W_Privileged = 2;             // the account holds a sensitive directory role\nlet W_HighConfidence = 1;         // indicator confidence at or above ConfidenceFloor\nlet W_FailBurst = 1;              // explicitly failed operations at volume; permission probing\nlet W_OffHours = 1;               // activity outside working hours\nlet ExfilOps = dynamic([\n\"FileDownloaded\", \"FileSyncDownloadedFull\", \"FileCopied\",\n\"MailItemsAccessed\", \"AnonymousLinkCreated\"\n]);\nlet MailManipOps = dynamic([\n\"New-InboxRule\", \"Set-InboxRule\", \"UpdateInboxRules\",\n\"Set-Mailbox\", \"Add-MailboxPermission\", \"Add-RecipientPermission\"\n]);\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// Office activity in the window, client IP parsed from its bracket, port and prefix wrappers;\n// rows whose IP cannot be parsed are dropped\nlet OfficeEvents = materialize(OfficeActivity\n    | where TimeGenerated > ago(DetectionWindow)\n    | where isnotempty(ClientIP)\n    | extend ClientIPValues = extract_all(@'\\[?(::ffff:)?(?P<IPAddress>(\\d+\\.\\d+\\.\\d+\\.\\d+)|[^\\]%]+)(%\\d+)?\\]?([-:](?P<Port>\\d+))?', dynamic([\"IPAddress\", \"Port\"]), ClientIP)[0]\n    | extend IPAddress = tolower(iff(array_length(ClientIPValues) > 0, tostring(ClientIPValues[0]), \"\"))\n    | where isnotempty(IPAddress)\n    | extend UserId = tolower(UserId)\n    | extend IsExfilOp = Operation in~ (ExfilOps)\n    | extend IsMailManipOp = Operation in~ (MailManipOps)\n    // several workloads leave ResultStatus empty on success, so only an explicit Failed counts as failure\n    | extend IsFailed = ResultStatus =~ \"Failed\"\n    | extend HourOfDay = datetime_part(\"Hour\", TimeGenerated)\n    | extend OffHoursEvent = HourOfDay < BusinessStart or HourOfDay >= BusinessEnd or dayofweek(TimeGenerated) in (0d, 6d)\n);\nlet ActivityIpSet = toscalar(OfficeEvents | 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 (ActivityIpSet)\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 TlpLevel = tostring(parse_json(AdditionalFields).TLPLevel)\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        TlpLevels = make_set_if(TlpLevel, isnotempty(TlpLevel), 5),\n        LatestValidUntil = max(ValidUntil)\n      by TiIp;\n// How many accounts each listed IP touched in the window; context for the analyst\nlet IpContext = OfficeEvents\n    | summarize UsersFromIp = dcount(UserId) by IPAddress;\n// Account context for the acting user\nlet IdentityContext = IdentityInfo\n    | where TimeGenerated > ago(IdentityLookback)\n    | summarize arg_max(TimeGenerated, AssignedRoles, Department, UserType) by AccountUPN = tolower(AccountUPN);\n// One row per account and listed IP, scored on what the session did\nOfficeEvents\n| summarize\n    StartTime = min(TimeGenerated),\n    EndTime = max(TimeGenerated),\n    EventCount = count(),\n    ExfilCount = countif(IsExfilOp),\n    MailManipCount = countif(IsMailManipOp),\n    FailedCount = countif(IsFailed),\n    DistinctObjects = dcount(OfficeObjectId),\n    Operations = make_set(Operation, 15),\n    Workloads = make_set(OfficeWorkload, 10),\n    ObjectsSample = make_set_if(OfficeObjectId, isnotempty(OfficeObjectId), 10),\n    UserAgent = take_any(UserAgent),\n    RawClientIP = take_any(ClientIP),\n    OffHoursCount = countif(OffHoursEvent)\n  by UserId, 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.UserId == $right.AccountUPN\n| extend UserRoles = tostring(AssignedRoles)\n| extend sExfil = ExfilCount > 0\n| extend sMailManip = MailManipCount > 0\n| extend sMass = EventCount >= MassFloor or DistinctObjects >= ObjectFloor\n| extend sPrivileged = UserRoles has_any (SensitiveRoles)\n| extend sHighConf = MaxConfidence >= ConfidenceFloor\n| extend sFailBurst = FailedCount >= FailFloor\n| extend sOffHours = OffHoursCount > 0\n| extend RiskScore =\n      iff(sExfil, W_ExfilOps, 0)\n    + iff(sMailManip, W_MailManip, 0)\n    + iff(sMass, W_MassActivity, 0)\n    + iff(sPrivileged, W_Privileged, 0)\n    + iff(sHighConf, W_HighConfidence, 0)\n    + iff(sFailBurst, W_FailBurst, 0)\n    + iff(sOffHours, W_OffHours, 0)\n| where RiskScore >= FireThreshold\n| extend Name = tostring(split(UserId, \"@\", 0)[0]), UPNSuffix = tostring(split(UserId, \"@\", 1)[0])\n| extend Risk_1 = iff(sExfil, \"ExfilOperations\", \"\")\n| extend Risk_2 = iff(sMailManip, \"MailboxManipulation\", \"\")\n| extend Risk_3 = iff(sMass, \"MassActivity\", \"\")\n| extend Risk_4 = iff(sPrivileged, \"PrivilegedAccount\", \"\")\n| extend Risk_5 = iff(sHighConf, \"HighConfidenceIoc\", \"\")\n| extend Risk_6 = iff(sFailBurst, \"FailedOpsBurst\", \"\")\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    UserId, Name, UPNSuffix, IPAddress, RawClientIP,\n    EventCount, ExfilCount, MailManipCount, FailedCount, DistinctObjects,\n    Operations, Workloads, ObjectsSample, UserAgent, UsersFromIp,\n    MaxConfidence, TiSources, TiDescriptions, ActivityGroups, TlpLevels, 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": [
          "Collection",
          "DefenseEvasion"
        ],
        "techniques": [
          "T1530",
          "T1114",
          "T1564"
        ],
        "subTechniques": [
          "T1114.002",
          "T1564.008"
        ],
        "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": "Office activity from TI listed IP {{IPAddress}}",
          "alertDescriptionFormat": "{{UserId}} performed {{EventCount}} operations from a TI listed IP. Risk indicators: {{RiskIndicators}}"
        },
        "customDetails": {
          "RiskScore": "RiskScore",
          "RiskIndicators": "RiskIndicators",
          "EventCount": "EventCount",
          "ExfilCount": "ExfilCount",
          "MailManipCount": "MailManipCount",
          "FailedCount": "FailedCount",
          "DistinctObjects": "DistinctObjects",
          "Operations": "Operations",
          "Workloads": "Workloads",
          "ObjectsSample": "ObjectsSample",
          "UsersFromIp": "UsersFromIp",
          "MaxConfidence": "MaxConfidence",
          "TiSources": "TiSources",
          "TiDescriptions": "TiDescriptions",
          "ActivityGroups": "ActivityGroups",
          "TlpLevels": "TlpLevels",
          "LatestValidUntil": "LatestValidUntil",
          "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
      }
    }
  ]
}