Using Firewall Rules

This page describes the commands for working with firewall rules and offers some examples in using them. To learn more about firewall rules, read the Firewall Rules Overview.

Creating firewall rules

Please review the firewall rule components if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.

Console

  1. Go to the Firewall rules page in the Google Cloud Platform Console.
    Go to the Firewall rules page
  2. Click Create firewall rule.
  3. Enter a Name for the firewall rule.
    This name must be unique for the project.
  4. Specify the Network where the firewall rule will be implemented.
  5. Specify the Priority of the rule.
    The lower the number, the higher the priority.
  6. For the Direction of traffic, choose ingress or egress.
  7. For the Action on match, choose allow or deny.
  8. Specify the Targets of the rule.
    • If you want the rule to apply to all instances in the network, choose All instances in the network.
    • If you want the rule to apply to select instances by network (target) tags, choose Specified target tags, then type the tags to which the rule should apply into the Target tags field.
    • If you want the rule to apply to select instances by associated service account, choose Specified service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Target service account field.
  9. For an ingress rule, specify the Source filter:
    • Choose IP ranges and type the CIDR blocks into the Source IP ranges field to define the source for incoming traffic by IP address ranges. Use 0.0.0.0/0 for a source from any network.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the source for incoming traffic by subnet name.
    • To limit source by network tag, choose Source tags, then type the network tags in to the Source tags field. Filtering by source tag is only avaiable if the target is not specified by service account. For more information, see filtering by service account vs. network tag.
    • To limit source by service account, choose Service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Source service account field. Filtering by source service account is only available if the target is not specified by network tag. For more information, see filtering by service account vs. network tag.
    • Specify a Second source filter if desired. Secondary source filters cannot use the same filter criteria as the primary one.
  10. For an egress rule, specify the Destination filter:
    • Choose IP ranges and type the CIDR blocks into the Destination IP ranges field to define the destination for outgoing traffic by IP address ranges. Use 0.0.0.0/0 to mean everywhere.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the destination for outgoing traffic by subnet name.
  11. Define the Protocols and ports to which the rule will apply:
    • Choose Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.
    • Choose Specified protocols and ports then type a list of protocols and port numbers using this convention.
  12. (Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.
  13. Click Create.

gcloud

The gcloud command for creating firewall rules is:

gcloud [beta] compute firewall-rules create [NAME] \
    [--network [NETWORK]; default=”default”] \
    [--priority [PRIORITY];default=1000] \
    [--direction (ingress|egress|in|out); default=”ingress”] \
    [--action (deny | allow )] \
    [--target-tags [TAG][,TAG,...]] \
    [--target-service-accounts=[IAM Service Account] \
    [--source-ranges [CIDR-RANGE][,CIDR-RANGE…]] \
    [--source-tags [TAG][,TAG,...]] \
    [--source-service-accounts=[IAM Service Account] \
    [--destination-ranges [CIDR-RANGE][,CIDR-RANGE...]] \
    [--rules ([PROTOCOL][:PORT[-PORT]],[PROTOCOL[:PORT[-PORT]],...]] | all ) \
    [--disabled | --no-disabled] (requires gcloud beta)

Use the parameters as follows. More details about each are available in the SDK reference documentation.

  • --network The network where the rule will be created. If omitted, the rule will be created in the default network.
  • --priority A numerical value that indicates the priority for the rule. The lower the number, the higher the priority.
  • --direction The direction of traffic, either ingress or egress.
  • --action The action on match, either allow or deny. Must be used with the --rules flag.
  • Specify a target in one of three ways:
    • Omit --target-tags and --target-service-accounts if the rule should apply to all targets in the network.
    • --target-tags Use this flag to define targets by network tags.
    • --target-service-accounts Use this flag to define targets by an associated service account.
  • For an ingress rule, specify a source:
    • Omit --source-ranges, source-tags, and --source-service-accounts if the ingress source should be everywhere, 0.0.0.0/0.
    • --source-ranges Use this flag to specify ranges of source IP addresses in CIDR format.
    • --source-tags Use this flag to specify source instances by network tags. Filtering by source tag is only avaiable if the target is not specified by service account. For more information, see filtering by service account vs. network tag.
    • --source-ranges and --source-tags can be used together. If both are specified, the effective source set is the union of the source range IP addresses and the instances identified by network tags, even if the tagged instances do not have IPs in the source ranges.
    • --source-service-accounts Use this flag to specify instances by service account they use. Filtering by source service account is only avaiable if the target is not specified by network tag. For more information, see filtering by service account vs. network tag.
  • For an egress rule, specify a destination:
    • Omit --destination-ranges if the egress destination should be anywhere, 0.0.0.0/0.
    • --destination-ranges Use this flag to specify ranges of destination IP addresses in CIDR format.
  • --rules A list of protocols and ports to which the rule will apply. Use all to make the rule applicable to all protocols and all ports. Requires the --action flag.
  • (Beta) By default, firewall rules are created and enforced automatically; however, you can change this behavior.
    • If both --disabled and --no-disabled are omitted, the firewall rule is created and enforced.
    • --disabled Add this flag to create the firewall rule but not enforce it. The firewall rule will remain in a disabled state until you update the firewall rule to enable it.
    • --no-disabled Add this flag to ensure the firewall rule is enforced.

Updating firewall rules

You can modify any component of a firewall rule except for its name, its network, the action on match, and the direction of traffic. Changing the priority of the rule requires that you use gcloud.

If you need to change the name, network, or the action or direction component, you must delete the rule and create a new one instead.

Console

  1. Go to the Firewall rules page in the Google Cloud Platform Console.
    Go to the Firewall rules page
  2. Click the firewall rule you want to modify.
  3. Click Edit.
  4. Modify any of the editable components to meet your needs. The user interface is similar to the one used to create a rule.
  5. Click Save.

gcloud

The gcloud command for updating firewall rules is:

gcloud [beta] compute firewall-rules update [NAME] \
    [--priority=[PRIORITY]] \
    [--description=[DESCRIPTION]] \
    [--target-tags=[[TAG],…]] \
    [--target-service-accounts=[IAM Service Account] \
    [--source-ranges=[[CIDR_RANGE],…]] \
    [--source-tags=[[TAG],…]] \
    [--source-service-accounts=[IAM Service Account] \
    [--destination-ranges=[CIDR_RANGE,…]] \
    [--rules=[[PROTOCOL][:PORT[-PORT]],…]] \
    [--disabled | --no-disabled] (requires gcloud beta)

The descriptions for each flag are the same as for creating firewall rules, and more details about each are available in the SDK reference documentation.

Listing firewall rules

Console

To show all firewall rules for all networks in your project:

To show firewall rules in a particular network:

  1. Go to the VPC networks page in the Google Cloud Platform Console.
    Go to the VPC networks page
  2. Click the Name of a VPC network to go to its details page.
  3. On the details page for the network, click the Firewall rules tab.

To view the firewall rules that apply to a specific network interface of a VM instance:

  1. Go to the VM instances page in the Google Cloud Platform Console and find the instance to view.
    Go to the VM instances page
  2. In the instance's more actions menu (), select View network details.
  3. If an instance has multiple network interfaces, select the network interface to view in the Network interface details section.
  4. Click the Firewall rules tab to see all the rules that apply to the network interface.

gcloud

The following command produces a sorted list of firewall rules for a given network ([NETWORK_NAME]).

gcloud compute firewall-rules list --filter network=[NETWORK_NAME] \
    --sort-by priority \
    --format="table(
        name,
        network,
        direction,
        priority,
        sourceRanges.list():label=[SRC_RANGES],
        destinationRanges.list():label=[DEST_RANGES],
        allowed[].map().firewall_rule().list():label=ALLOW,
        denied[].map().firewall_rule().list():label=DENY,
        sourceTags.list():label=[SRC_TAGS],
        targetTags.list():label=[TARGET_TAGS]
        )"

Viewing firewall rules details

You can inspect a firewall rule to see its name, applicable network, and components, including whether the rule is enabled or disabled.

Console

  1. List your firewall rules. You can view a list of all rules or just those in a particular network.
  2. Click the rule to view.

gcloud

The following command describes an individual firewall rule. Replace [FIREWALL_RULE_NAME] with the name of the firewall rule. Because firewall rule names are unique to the project, you don't have to specify a network when describing an existing one.

gcloud compute firewall-rules describe [FIREWALL_RULE_NAME]

Deleting firewall rules

Console

  1. List your firewall rules. You can view a list of all rules or just those in a particular network.
  2. Click the rule to delete.
  3. Click Delete.
  4. Click Delete again to confirm.

gcloud

The following command deletes a firewall rule. Replace [FIREWALL_RULE_NAME] with the name of the rule to be deleted.

gcloud compute firewall-rules delete [FIREWALL_RULE_NAME]

Configuration examples

The diagram below demonstrates an example firewall configuration. The scenario involves a my-network that contains the following:.

  • a subnet subnet1 with IP range 10.240.10.0/24
  • a subnet subnet2 with IP range 192.168.1.0/24
  • instance vm1 in subnet2 having tag webserver and internal IP 192.168.1.2
  • instance vm2 in subnet2 having tag database and internal IP 192.168.1.3
Sample network configuration (click to enlarge)
Sample network configuration (click to enlarge)

Example 1: Deny all ingress TCP connections except those to port 80 from subnet1

This example creates a set of firewall rules that deny all ingress TCP connections except connections destined to port 80 from subnet1.

  1. Create a firewall rule to deny all ingress TCP traffic to instances tagged with webserver.

    gcloud compute firewall-rules create deny-subnet1-webserver-access \
        --network my-network \
        --action deny \
        --direction ingress \
        --rules tcp \
        --source-ranges 0.0.0.0/0 \
        --priority 1000 \
        --target-tags webserver
    

  2. Create a firewall rule to allow all IPs in subnet1 (10.240.10.0/24) to access TCP port 80 on instances tagged with webserver.

    gcloud compute firewall-rules create vm1-allow-ingress-tcp-port80-from-subnet1 \
        --network my-network \
        --action allow \
        --direction ingress \
        --rules tcp:80 \
        --source-ranges 10.240.10.0/24 \
        --priority 50 \
        --target-tags webserver
    

Example 2: Deny all egress TCP connections except those to port 80 of vm1

  1. Create a firewall rule to deny all egress TCP traffic.

    gcloud compute firewall-rules create deny-all-access \
        --network my-network \
        --action deny \
        --direction egress \
        --rules tcp \
        --destination-ranges 0.0.0.0/0 \
        --priority 1000
    

  2. Create firewall rule to allow TCP traffic destined to vm1 port 80.

    gcloud compute firewall-rules create vm1-allow-egress-tcp-port80-to-vm1 \
        --network my-network \
        --action allow \
        --direction egress \
        --rules tcp:80 \
        --destination-ranges 192.168.10.2/32 \
        --priority 60
    

Example 3: Allow egress TCP connections to port 443 of an external host

Create a firewall rule that allows instances tagged with webserver to send egress TCP traffic to port 443 of an sample external IP address, 192.0.2.5.

gcloud compute firewall-rules create vm1-allow-egress-tcp-port443-to-192-0-2-5 \
    --network my-network \
    --action allow \
    --direction egress \
    --rules tcp:443 \
    --destination-ranges 192.0.2.5/32 \
    --priority 70 \
    --target-tags webserver

Example 4: Allow SSH connections from vm2 to vm1

Create firewall rule that allows SSH traffic from instances with tag database (vm2) to reach instances with tag webserver (vm1).

gcloud compute firewall-rules create vm1-allow-ingress-tcp-ssh-from-vm2 \
    --network my-network \
    --action allow \
    --direction ingress \
    --rules tcp:22 \
    --source-tags database \
    --priority 80 \
    --target-tags webserver

Example 5: Allow TCP:1443 from webserver to database using service accounts

For additional information on service accounts and roles, see Granting roles to service accounts.

Consider the scenario in the diagram below, in which there are two applications that are autoscaled through templates, a webserver application my-sa-web, and a database application 'my-sa-db". A Security admin wants to allow TCP flows on port 1443 from my-sa-web to my-sa-db.

Using firewall rules with service accounts (click to enlarge)
Using firewall rules with service accounts (click to enlarge)

The configuration steps, including the creation of the service accounts, is as follows:

  1. A project EDITOR or project OWNER creates the service accounts my-sa-web and my-sa-db.

    gcloud iam service-accounts create my-sa-web \
        --display-name "webserver service account"
    

    gcloud iam service-accounts create my-sa-db \
        --display-name "database service account"
    

  2. A project OWNER assigns the webserver developer web-dev@example.com a serviceAccountUser role for service account my-sa-web by setting an IAM policy.

    gcloud iam service-accounts add-iam-policy-binding \
       my-sa-web@my-project.iam.gserviceaccount.com \
       --member='user:web-dev@example.com' \
       --role='roles/iam.serviceAccountUser'
    

  3. A project OWNER assigns the database developer "db-dev@example.com" a serviceAccountUser role for service account my-sa-db by setting an IAM policy.

    gcloud iam service-accounts add-iam-policy-binding \
       my-sa-db@my-project.iam.gserviceaccount.com \
       --member='user:db-dev@example.com' \
       --role='roles/iam.serviceAccountUser'
    

  4. Developer web-dev@example.com, which has the Instance admin role, creates webserver instance template and authorize instances to run as service account my-sa-web.

    gcloud compute instance-templates create [INSTANCE_TEMPLATE_NAME]  \
        --service-account my-sa-web@my-project-123.iam.gserviceaccount.com
    

  5. Developer db-dev@example.com, which has the Instance Admin role, creates the database instance template and authorize instances to run as service account my-sa-web.

    gcloud compute instance-templates create [INSTANCE_TEMPLATE_NAME] \
        --service-account my-sa-db@my-project-123.iam.gserviceaccount.com
    

  6. Security admin creates the firewall rules using service accounts to allow traffic TCP:1443 from service account my-sa-web to service account my-sa-db.

    gcloud compute firewall-rules create [NAME] \
        --network network_a \
        --allow TCP:1443 \
        --source-service-accounts my-sa-web@my-project.iam.gserviceaccount.com \
        --target-service-accounts my-sa-db@my-project.iam.gserviceaccount.com
       

Troubleshooting

Error messages when creating or updating a firewall rule

You may see one of the following error messages:

  • Should not specify destination range for ingress direction.

    Destination ranges are not valid parameters for ingress firewall rules. Firewall rules are assumed to be ingress rules unless a direction of egress is specifically specified. If you create a rule that does not specify a direction, it will be created as an ingress rule, which does not allow a destination range. Also, source ranges are not valid parameters for egress rules.

  • Firewall direction cannot be changed once created.

    You cannot change the direction of an existing firewall rule. You have to create a new rule with the correct parameters, then delete the old one.

  • Firewall traffic control action cannot be changed once created.

    You cannot change the action of an existing firewall rule. You have to create a new rule with the correct parameters, then delete the old one.

  • Service accounts must be valid RFC 822 email addresses. The service account specified in firewall rule must be an email address formatted per RFC 822.

    gcloud compute firewall-rules create bad --allow tcp --source-service-accounts invalid-email
    
    Creating firewall...failed.
    ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
    - Invalid value for field 'resource.sourceServiceAccounts[0]': 'invalid-email'. Service accounts must be valid RFC 822 email addresses.
    

  • ServiceAccounts and Tags are mutually exclusive and can't be combined in the same firewall rule. You cannot specify both both service accounts and tags in the same rule.

    gcloud compute firewall-rules create bad --allow tcp --source-service-accounts test@google.com --target-tags target
    

    Creating firewall...failed.
     ERROR: (gcloud.compute.firewall-rules.create) Could not fetch resource:
    - ServiceAccounts and Tags are mutually exclusive and can't be combined in the same firewall rule.
    

Cannot connect to VM instance

If you cannot connect to a VM instance, check your firewall rules.

  1. If you are initiating the connection from another VM instance, list the egress firewall rules for that instance.

    gcloud compute firewall-rules list --filter network=[NETWORK_NAME] \
        --filter EGRESS \
        --sort-by priority \
        --format="table(
            name,
            network,
            direction,
            priority,
            sourceRanges.list():label=SRC_RANGES,
            destinationRanges.list():label=DEST_RANGES,
            allowed[].map().firewall_rule().list():label=ALLOW,
            denied[].map().firewall_rule().list():label=DENY,
            sourceTags.list():label=SRC_TAGS,
            sourceServiceAccounts.list():label=SRC_SVC_ACCT,
            targetTags.list():label=TARGET_TAGS,
            targetServiceAccounts.list():label=TARGET_SVC_ACCT
            )"
    

  2. Check if the destination IP is denied by any egress rules. The rule with the highest priority (lowest priority number) overrides lower priority rules. For two rules with same priority, the deny rule take precedence.

  3. Check ingress firewall rule for the network that contains the destination VM instance.

    gcloud compute firewall-rules list --filter network=[NETWORK_NAME] \
        --filter INGRESS \
        --sort-by priority \
        --format="table(
            name,
            network,
            direction,
            priority,
            sourceRanges.list():label=SRC_RANGES,
            destinationRanges.list():label=DEST_RANGES,
            allowed[].map().firewall_rule().list():label=ALLOW,
            denied[].map().firewall_rule().list():label=DENY,
            sourceTags.list():label=SRC_TAGS,
            sourceServiceAccounts.list():label=SRC_SVC_ACCT,
            targetTags.list():label=TARGET_TAGS,
            targetServiceAccounts.list():label=TARGET_SVC_ACCT
            )"
    

    Sample output. Your output will depend on your list of firewall rules

    NAME                    NETWORK  DIRECTION  PRIORITY  SRC_RANGES    DEST_RANGES  ALLOW                         DENY  SRC_TAGS  SRC_SVC_ACCT      TARGET_TAGS  TARGET_SVC_ACCT
    default-allow-icmp      default  INGRESS    65534     0.0.0.0/0                  icmp
    default-allow-internal  default  INGRESS    65534     10.128.0.0/9               tcp:0-65535,udp:0-65535,icmp
    default-allow-rdp       default  INGRESS    65534     0.0.0.0/0                  tcp:3389
    default-allow-ssh       default  INGRESS    65534     0.0.0.0/0                  tcp:22
    firewall-with-sa        default  INGRESS    1000                                 tcp:10000                                     test1@google.com               target@google.com
    

Is my firewall rule enabled or disabled?

To see if a firewall rule is enabled or disabled, view the firewall rules details.

In the Google Cloud Platform Console, look for Enabled or Disabled under Enforcement.

In the gcloud command line tool output, look for the disabled field. If it says disabled:false, the rule is enabled and being enforced. If it says disabled: true, the rule is disabled.

What's next

Was this page helpful? Let us know how we did:

Send feedback about...