def append_rule()

in Azure Firewall/Script - Migrate Checkpoint config to Azure Firewall Policy/chkp2azfw.py [0:0]


def append_rule(rule_to_be_appended, rules_to_append_to):
    if log_level >= 8:
        print("DEBUG: appending to rules:", str(rule_to_be_appended), file=sys.stderr)
    src_fields = ('sourceAddresses', 'sourceIpGroups', 'sourceServiceTags')
    dst_fields = ('destinationAddresses', 'destinationIpGroups', 'destinationFqdns', 'destinationServiceTags')
    all_fields = src_fields + dst_fields
    # Count how many rules we will be splitting (to avoid unnecessary suffixes if there is only one rule)
    total_rule_no = 0
    for src_field in src_fields:
        for dst_field in dst_fields:
            if len(rule_to_be_appended[src_field]) > 0 and len(rule_to_be_appended[dst_field]) > 0:
                total_rule_no += 1
    # Process the rule
    split_rule_counter = 0
    for src_field in src_fields:
        for dst_field in dst_fields:
            # Only look at combinations where the src_field and dst_field are non-zero
            if len(rule_to_be_appended[src_field]) > 0 and len(rule_to_be_appended[dst_field]) > 0:
                # Should we split a rule that contains both IP addresses and service tags in either sourceAddresses or destinationAddresses?
                temp_rule = copy.copy(rule_to_be_appended)
                split_rule_counter += 1
                if total_rule_no > 1:
                    temp_rule['name'] = temp_rule['name'] + '-' + str(split_rule_counter)
                else:
                    temp_rule['name'] = temp_rule['name']
                # Blank all the rest fields
                for blank_field in all_fields:
                    if blank_field != src_field and blank_field != dst_field:
                        temp_rule [blank_field] = []
                rules_to_append_to.append(temp_rule)
                # The fields 'sourceServiceTags' and 'destinationServiceTags' are not supported in Azure Firewall, so we need to change them to 'sourceAddresses' and 'destinationAddresses'
                if src_field == 'sourceServiceTags':
                    temp_rule['sourceAddresses'] = temp_rule['sourceServiceTags']
                    temp_rule.pop('sourceServiceTags')
                if dst_field == 'destinationServiceTags':
                    temp_rule['destinationAddresses'] = temp_rule['destinationServiceTags']
                    temp_rule.pop('destinationServiceTags')
    if split_rule_counter > 1:
        if log_level >= 7:
            print("DEBUG: Checkpoint rule {0} has been split in {1} Azure Firewall rules".format(rule_to_be_appended['name'], split_rule_counter), file=sys.stderr)
    return rules_to_append_to