Azure policy to validate mandatory NSG rules during deployment not working as expected

Ratish Kumar 71 Reputation points
2020-05-19T17:24:30.833+00:00

I have the following requirement:

Users should not deploy NSG without the mandatory security rules. if the mandatory rule is not present or if the properties for the security rule are different than expected then the deployment should fail.

Below is the logic used. the policy deny is activated if any change is attempted from the portal directly however when the NSG rule is updated through ansible or powershell the policy check do not work.

why is the policy behaving differently for different mode of updations:

"if": {
    "allof": [
      {
        "anyOf": [
          {
            "field": "type",
            "equals": "Microsoft.Network/networkSecurityGroups/securityRules"
          },
          {
            "field": "type",
            "equals": "Microsoft.Network/networkSecurityGroups"
          }
        ]
      },
      {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules/access",
        "equals": "Allow"
      },
      {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules/priority",
        "equals": "1040"
      },
      {
        "anyOf": [
          {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules/direction",
            "notequals": "Inbound"
          },
          {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules/protocol",
            "notequals": "TCP"
          },
          {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules/destinationPortRange",
            "notequals": "*"
          },
          {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules/sourceAddressPrefixes",
            "notin": [
              "10.23.1.11/28",
              "10.23.1.11/28"
                    ]
          }
        ]
      }
    ]
  },
  "then": {
    "effect": "deny"
  }
}
Azure Policy
Azure Policy
An Azure service that is used to implement corporate governance and standards at scale for Azure resources.
789 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. DCtheGeek-MSFT 451 Reputation points Microsoft Employee
    2020-05-20T17:37:38.677+00:00

    I believe part of the issue is checking for two different resource types in the definition. Since the securityRules aliases (as a [*] array alias) are on the NSG, I'd evaluate only the Microsoft.Network/networkSecurityGroups type. There's an example pretty similar to this in the Community Policy repo, I'd check it out and just adapt the securityRules properties/settings to your needs: https://github.com/Azure/Community-Policy/blob/master/Policies/Network/deny-nsgs-with-rules-with-source-any/azurepolicy.json. It uses count to evaluate each instance of the securityRules array alias.

    1 person found this answer helpful.