id: azure-vm-poweroff-unalerted
info:
  name: Azure Virtual Machine Power Off Alert Not Configured
  author: princechaddha
  severity: high
  description: |
    Ensure that a Microsoft Azure activity log alert is fired whenever a "Power Off Virtual Machine" event is triggered within your cloud account. An Azure activity log alert fires each time the action event that matches the condition defined in the alert configuration is triggered. The alert condition that this conformity rule checks for is `Whenever the Administrative Activity Log "Power Off Virtual Machine (Microsoft.Compute/virtualMachines)" has "any" Event level, with "any" Status and Event initiated by "any"`
  impact: |
    Failure to monitor "Power Off Virtual Machine" events can result in missed critical alerts when virtual machines are powered off, potentially leading to operational disruptions and unauthorized actions going unnoticed.
  remediation: |
    Configure the activity log alert to trigger on the event "Microsoft.Compute/virtualMachines/powerOff/action". Ensure the alert condition includes any event level, status, and initiator to capture all related events.
  reference:
    - https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-activity-log
  tags: cloud,devops,azure,microsoft,virtual-machines,azure-cloud-config

flow: |
  code(1);
  for (let AlertData of iterate(template.alertList)) {
    set("id", AlertData);
    code(2);
  }

self-contained: true
code:
  - engine:
      - sh
      - bash
    source: |
      az monitor activity-log alert list --output json --query '[?(enabled==`true`)].id'

    extractors:
      - type: json
        name: alertList
        internal: true
        json:
          - '.[]'

  - engine:
      - sh
      - bash
    source: |
      az monitor activity-log alert show --ids "$id" --query 'condition'

    matchers-condition: and
    matchers:
      - type: word
        words:
          - '"field": "operationName"'

      - type: word
        words:
          - "Microsoft.Compute/virtualMachines/powerOff/action"
        negative: true

    extractors:
      - type: dsl
        dsl:
          - 'id + " does not have the correct alert configuration for Power Off Virtual Machine events"'
# digest: 4a0a00473045022052617da754da5c5cd93d84e8617c9d28fa36aa99ea81916e4ce702d4e9eb514d02210089a4c0b84cf8607ba37b7da5bd498a1fd8cac7d50fc7c69767060cd85ad92b81:922c64590222798bb761d5b6d8e72950