google.cloud.forseti.enforcer.gce_firewall_enforcer module

Core classes for firewall policy enforcement.

Simplifies the interface with the compute API for managing firewall policies.

exception DuplicateFirewallRuleNameError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.Error

Raised if a rule name is reused in a policy, names must be unique.

exception EmptyProposedFirewallRuleSetError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.FirewallEnforcementFailedError

Raised if the proposed firewall rule set is empty.

exception Error[source]

Bases: exceptions.Exception

Base error class for the module.

exception FirewallEnforcementDeleteFailedError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.FirewallEnforcementFailedError

Deletion of a firewall rule failed.

exception FirewallEnforcementFailedError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.Error

Updating firewall for project failed.

exception FirewallEnforcementInsertFailedError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.FirewallEnforcementFailedError

Insertion of a firewall rule failed.

exception FirewallEnforcementUpdateFailedError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.FirewallEnforcementFailedError

Update of a firewall rule failed.

class FirewallEnforcer(project, compute_client, expected_rules, current_rules=None, project_sema=None, operation_sema=None, add_rule_callback=None)[source]

Bases: object

Enforce a set of firewall rules for use with GCE projects.

_apply_change(firewall_function, rules)[source]

Modify the firewall using the passed in function and rules.

If self.operation_sema is defined, then the number of outstanding changes is limited to the number of semaphore locks that can be acquired.

Parameters:
  • firewall_function – The delete|insert|update function to call for this set of rules
  • rules – A list of rules to pass to the firewall_function.
Returns:

A tuple with the rules successfully changed by this function and the rules that failed.

_apply_change_set(delete_before_insert)[source]

Updates project firewall rules based on the generated changeset.

Extends self._(deleted|inserted|updated)_rules with the rules changed by these operations.
Parameters:
  • delete_before_insert – If true, delete operations are completed before
  • Otherwise insert operations are completed first. (inserts.) –
Returns:

The total number of firewall rules deleted, inserted and updated.

Raises:

FirewallEnforcementFailedError – Raised if one or more changes fails.

_build_change_set(networks=None)[source]

Enumerate changes between the current and expected firewall rules.

_check_change_operation_order(insert_count, delete_count)[source]

Check if enough quota to do the firewall changes insert first.

If current usage is near the limit, check if deleting current rules before adding the new rules would allow the project to stay below quota.

Parameters:
  • insert_count – The number of rules that will be inserted.
  • delete_count – The number of rules that will be deleted.
Returns:

True if existing rules should be deleted before new rules are inserted, otherwise false.

Raises:
_delete_rules()[source]

Delete old rules from the project firewall.

_insert_rules()[source]

Insert new rules into the project firewall.

_update_rules()[source]

Update existing rules in the project firewall.

_validate_change_set(networks=None)[source]

Validate the changeset will not leave the project in a bad state.

apply_firewall(prechange_callback=None, networks=None, allow_empty_ruleset=False)[source]

Enforce the expected firewall rules on the project.

Parameters:
  • prechange_callback

    An optional callback function that will get called if the firewall policy for a project does not match the expected policy, before any changes are actually applied. If the callback returns False then no changes will be made to the project. If it returns True then the changes will be pushed. If prechange_callback is set to None then the callback will be skipped and enforcement will continue as though it had returned True.

    The callback template is callback_func(project,
    rules_to_delete, rules_to_insert, rules_to_update)

    The callback may be used to limit the kinds of firewall changes that are allowed to be pushed for a project, limit the number of rules that can get changed, to check if the project should have rules changed, etc.

    The callback may also raise FirewallEnforcementFailedError if it determines that the set of changes to the policy could result in an outage for an underlying service, or otherwise are inconsistent with business rules. This will cause the enforcement to fail.

  • networks

    A list of networks to limit rule changes to. Rules on networks not in the list will not be changed.

    Note- This can lead to duplicate rule name collisions since all
    rules are not included when building the change set. The change set will be validated before getting enforced and any errors will cause a FirewallEnforcementFailedError exception to be raised.
  • allow_empty_ruleset – If set to true and expected_rules has no rules, all current firewall rules will be deleted from the project.
Returns:

The total number of firewall rules deleted, inserted and updated.

Raises:

EmptyProposedFirewallRuleSetError – An error occurred while updating the firewall. The calling code should validate the current state of the project firewall, and potentially revert to the old firewall rules.

Any rules changed before the error occurred can be retrieved by calling the Get(Deleted|Inserted|Updated)Rules methods.

get_deleted_rules()[source]

Returns the list of deleted rules.

get_inserted_rules()[source]

Returns the list of inserted rules.

get_updated_rules()[source]

Returns the list of updated rules.

refresh_current_rules()[source]

Updates the current rules for the project using the compute API.

exception FirewallQuotaExceededError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.FirewallEnforcementFailedError

Raised if the proposed changes would exceed firewall quota.

exception FirewallRuleValidationError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.Error

Raised if a firewall rule fails validation.

class FirewallRules(project, rules=None, add_rule_callback=None)[source]

Bases: object

A collection of validated firewall rules.

DEFAULT_DIRECTION = 'INGRESS'
DEFAULT_PRIORITY = 1000
__eq__(other)[source]

Equality.

__ne__(other)[source]

Not Equal.

_check_rule_before_adding(rule)[source]

Validates that a rule is valid and not a duplicate.

Validation is based on reference: https://cloud.google.com/compute/docs/reference/beta/firewalls and https://cloud.google.com/compute/docs/vpc/firewalls#gcp_firewall_rule_summary_table If add_rule_callback is set, this will also confirm that add_rule_callback returns True for the rule, otherwise it will not add the rule.

Parameters:

rule – The rule to validate.

Returns:

True if rule is valid, False if the add_rule_callback returns False.

Raises:
_order_lists_in_rule(unsorted_rule)[source]

Recursively iterates a rule dictionary and sorts any lists.

This ensures that two rule with the same polices, but with unordered lists will compare equal when tested.

Parameters:unsorted_rule – A rule dictionary that has not been sorted.
Returns:A new rule dictionary with the lists sorted
add_rule(rule, network_name=None)[source]

Adds rule to the self.rules dictionary.

Parameters:
  • rule – A valid dict representing a GCE firewall rule
  • network_name

    If set, rules which have no network currently defined will have their network set to network_name, and network_name will be prepended to the rule name.

    Rules that do have a network defined have their network matched against network_name, and if they differ the rule is not added.

Raises:
add_rules(rules, network_name=None)[source]

Adds rules from a list of rule dicts.

Parameters:
  • rules – A list of rule dicts to add to the object
  • network_name

    If set, rules which have no network currently defined will have their network set to network_name, and network_name will be prepended to the rule name.

    Rules that do have a network defined have their network matched against network_name, and if they differ the rule is not added.

Raises:
add_rules_from_api(compute_client)[source]

Loads rules from compute.firewalls().list().

Parameters:

compute_client – A ComputeClient instance for interfacing with GCE API.

Raises:
add_rules_from_json(json_rules)[source]

Import rules from a json string as exported by as_json.

The JSON string should be an array of Firewall resource objects, see https://cloud.google.com/compute/docs/reference/latest/firewalls for details. Only the fields in ALLOWED_RULE_ITEMS are permitted.

The legacy format from older versions of GCE Enforcer is also supported. This format wraps the array of Firewall resources in a dictionary under the key ‘items’.

Parameters:

json_rules – The JSON formatted string containing the rules to import.

Raises:
as_json()[source]

Export rules to a json string.

The JSON string should be an array of Firewall resource objects, see https://cloud.google.com/compute/docs/reference/latest/firewalls for details. Only the fields in ALLOWED_RULE_ITEMS are permitted.

Returns:A JSON string with an array of rules sorted by network and name.
filtered_by_networks(networks)[source]

Returns the subset of rules that apply to the specified network(s).

Parameters:networks – A list of one or more network names to fetch rules for.
Returns:A dictionary of rules that apply to the filtered networks.
exception InvalidFirewallRuleError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.Error

Raised if a firewall rule doesn’t look like a firewall rule should.

exception NetworkImpactValidationError[source]

Bases: google.cloud.forseti.enforcer.gce_firewall_enforcer.FirewallEnforcementFailedError

Raised if a firewall rule is to be applied to a disallowed network.

_is_successful(operation)[source]

Checks if the operation finished with no errors.

If the operation response contains an ‘error’ key, then the error code is checked. Any error code that is not ignored causes this to return False.

Parameters:operation – A Compute GlobalOperations response object from an API call.
Returns:
True if there were no errors, or all errors are ignored, otherwise
False.
Return type:bool
build_network_url(project, network)[source]

Render the network url from project and network names.

Parameters:
  • project – A str- The name of the GCE project to operate upon.
  • network – A str- The name of the network to operate upon.
Returns:

The fully qualified network url for the given project/network.

get_network_name_from_url(network_url)[source]

Given a network URL, return the name of the network.

Parameters:network_url – str - the fully qualified network url, such as (‘<root>/compute/v1/projects/my-proj/global/networks/my-network’)
Returns:str - the network name, my-network in the previous example
http_retry(e)[source]

retry_on_exception for retry. Returns True for exceptions to retry.