Skip to content

Instantly share code, notes, and snippets.

@beneshed
Last active April 26, 2022 10:55
Show Gist options
  • Save beneshed/a4673e1bb601bf771771e72f92f786ea to your computer and use it in GitHub Desktop.
Save beneshed/a4673e1bb601bf771771e72f92f786ea to your computer and use it in GitHub Desktop.
Azure Firewall Calculate Rule Collection Group Size - Python (Unofficial)
"""
This is addressing the size
This should give a good rough estimation on sizing. Beware of floating point math, but should be good enough.
Maybe give a buffer of 0.05mb for safety
"""
import json
from typing import Dict, Any, Optional
SCALING_FACTOR = 10000
BYTES_TO_MEGABYTES = float(1<<20)
SIZE_LIMIT = 2.0
EXAMPLE_RULES = [
{
"rule_type": "FirewallPolicyFilterRule",
"name": "Example-Filter-Rule",
"action": {"type": "Deny"},
"rule_conditions": [
{
"rule_condition_type": "NetworkRuleCondition",
"name": "network-condition1",
"source_addresses": ["10.1.25.0/24"],
"destination_addresses": ["*"],
"ip_protocols": ["TCP"],
"destination_ports": ["*"],
}
],
}
]
EXAMPLE_RULE_COLLECTION_GROUP = {
"priority": "110",
"rules": EXAMPLE_RULES
}
EXAMPLE_BAD_RULE_COLLECTION_GROUP = {
"priority": "110",
"rules": EXAMPLE_RULES * SCALING_FACTOR
}
def calculate_rule_group_size(rule_collection_group: Dict[str, Any]):
"""
Takes whatever dict object you pass (hopefully the group body) and calculates the size in megabytes.
"""
return (len(json.dumps(rule_collection_group).encode("utf-8"))/BYTES_TO_MEGABYTES)
def validate_size(size: float) -> Optional[float]:
if size > SIZE_LIMIT:
raise ValueError(f"Size was {size} MB. Limit is 2MB. Please chunk into smaller sizes")
return size
def main():
print(f"Size : {validate_size(calculate_rule_group_size(EXAMPLE_RULE_COLLECTION_GROUP))} MB")
try:
validate_size(calculate_rule_group_size(EXAMPLE_BAD_RULE_COLLECTION_GROUP))
except ValueError as msg:
print(msg)
if __name__ == "__main__":
main()
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import os
from azure.identity import DefaultAzureCredential
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.resource import ResourceManagementClient
EXAMPLE_RULE_COLLECTION_GROUP = {
"priority": "110",
"rules": [
{
"rule_type": "FirewallPolicyFilterRule",
"name": "Example-Filter-Rule",
"action": {
"type": "Deny"
},
"rule_conditions": [
{
"rule_condition_type": "NetworkRuleCondition",
"name": "network-condition1",
"source_addresses": [
"10.1.25.0/24"
],
"destination_addresses": [
"*"
],
"ip_protocols": [
"TCP"
],
"destination_ports": [
"*"
]
}
]
}
]
}
def main():
SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
GROUP_NAME = "testgroupx"
FIREWALL_POLICY_RULE_GROUP = "firewall_policy_rule_groupxxyyzz"
FIREWALL_POLICY = "firewall_policyxxx"
# Create client
# For other authentication approaches, please see: https://pypi.org/project/azure-identity/
resource_client = ResourceManagementClient(
credential=DefaultAzureCredential(),
subscription_id=SUBSCRIPTION_ID
)
network_client = NetworkManagementClient(
credential=DefaultAzureCredential(),
subscription_id=SUBSCRIPTION_ID
)
# Create resource group
resource_client.resource_groups.create_or_update(
GROUP_NAME,
{"location": "eastus"}
)
# - init depended resources -
# Create firewall policy
network_client.firewall_policies.begin_create_or_update(
GROUP_NAME,
FIREWALL_POLICY,
{
"tags": {
"key1": "value1"
},
"location": "West US",
"threat_intel_mode": "Alert"
}
).result()
# - end -
# Create firewall policy rule group
try:
validate_size(EXAMPLE_RULE_COLLECTION_GROUP)
firewall_policy_rule_group = network_client.firewall_policy_rule_groups.begin_create_or_update(
GROUP_NAME,
FIREWALL_POLICY,
FIREWALL_POLICY_RULE_GROUP,
).result()
print("Create firewall policy rule group:\n{}".format(firewall_policy_rule_group))
except ValueError as msg:
print(msg)
# implement chunking function
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment