# Rules Engine for Firewall

import DocButton from '~/components/webkit/DocButton.vue';
import RulesExecution from '~/includes/snippets/RulesEngineExecution/en/snippet.mdx'
import Tag from '~/components/webkit/Tag.vue'

The **Rules Engine for Firewall** is a feature designed to implement security logic for your applications. You can find the Rules Engine settings tab within a created firewall.

The Rules Engine is programmable, allowing you to define the conditions (**Criteria**) and actions (**Behaviors**). If the Criteria are met, the Behaviors will be executed.

You can use the Rules Engine for Firewall to configure all operational aspects of your application's firewalls. Here are some implementations examples you can use it for:

- Blocking a request.
- Ignoring a request.
- Limiting the access rate.
- Applying a **Web Application Firewall (WAF)** policy.
- Running an Function for Firewall with your own security code.
- Monitoring traffic to identify threats.

A firewall can have as many rules as needed. These rules are interchangeable, allowing you to share the same rule across all other firewalls.

<DocButton href="/en/documentation/products/secure/firewall/" label="Go to Firewall Reference" outlined size="medium" />

<DocButton href="/en/documentation/products/guides/secure/work-with-rules-engine/" label="Go to Work With Rules Engine Guide" outlined size="medium" />

## Implementation

| Scope | Resource |
| --- | --- |
| Secure an application | [How to secure an application](/en/documentation/products/secure/secure-application/) |
| Configuring main settings | [How to configure Firewall main settings](/en/documentation/products/guides/secure/firewall-configure-main-settings/) |
| Creating a WAF rule set | [How to create a WAF rule set](/en/documentation/products/guides/secure/create-waf-rule-set/) |
| Blocking Tor exit node IP addresses | [How to block Tor exit node IP addresses](/en/documentation/products/guides/secure/block-tor-networks/) |

---

## How Rules Engine for Firewall works

Each request from your users to your application is processed first by **Firewall**. You can define a set of security rules within Firewall. 

The rules are composed by *Criteria*, which represent the conditions for executing the rules, and by *Behaviors*, which represent the actions to be executed. 

The processing of the rules is sequential and you can use them as a powerful set of variables and comparison operators. If the conditions are met, the *Behaviors* of each rule are executed until all the rules are processed.

:::note
A firewall is composed of several key components that define its functionality and operation. While configuring a firewall, you can define its main settings, including: a **Name**, the **Domains** that will be secured by the firewall, and the **Modules** that will be used to extend the usability of **Rules Engine**, as well as enable the **Debug Rules** feature. 

After that, you'll be able to add [Functions Instances](/en/documentation/products/secure/firewall/functions-instances/) and **Rules Engine** rules. The fields and requirements to use **Rules Engine for Firewall** are explained in the sections below.
:::

---

## Name

Each rule must have a unique and easy-to-remember name, allowing you to easily reference and manage it within your system.

---

## Description

Aside from the name of the rule, you can add a description to your rule using the **Description** field. Your description will be visible from the rule list and can be used to help you identify what the rule does.

---

## Criteria

The **Criteria** section of **Rules Engine for Firewall** is where you define the conditions for executing the rule. Criteria are composed of:

- Variables
- Comparison operators
- Logic operators
- Arguments, when applicable

The inclusion of arguments in a criteria depends on the comparison operators chosen. The format of the arguments is described in the [variables](#variables) and [comparison operators](#comparison-operators) sections below. You can also add [logical operators](#logical-operators) to increase the amount of comparisons that the rule will execute.

For example, this criteria identifies requests where the URI starts with a forward slash ("/") so that the defined behavior can then be applied to them.

| | Variable | Comparison operator | Argument |
| --- | ---- | --- | --- |
| If | `Request URI` | *starts with* | `/` |

:::note 
The availability of certain criteria depends on the enabled modules of your Firewall. Go to the [Firewall modules reference](/en/documentation/products/secure/firewall/#about-edge-firewall-modules) for more details.
:::

### Variables

These are all the Criteria variables you can set:

| Variable | Description | Example | Requirements |
| -------- | ----------- | ------------ | ------------ |
| Header Accept | Header that tells you what types of media the customer accepts for the response. | `application/json` | Web Application Firewall |
| Header Accept Encoding | Header that tells you what types of content encoding, usually compression algorithms, that the client accepts for the response |  `gzip` | Web Application Firewall |
| Header Accept Language | Header that informs the expected language | `en-US` | Web Application Firewall |
| Header Cookie | Header containing the cookies sent by the client in the request to the server | `session_id=abc123` | Web Application Firewall |
| Header Origin | Header that informs the origin of a cross-site access request or a preflight request. The source is a URI indicating the name of the server, with no path information | `https://example.com` | Web Application Firewall |
| Header Referer | Header indicating the address of the document, or element in a document, from which the request's URI was obtained | `https://example.com/landing-page` | Web Application Firewall |
| Header User Agent | Header with a characteristic string that allows servers to identify the application, operating system, vendor, and/or version of the device | `Mozilla/5.0` | Web Application Firewall |
| Request Args | All arguments sent by the user in the request string (*query string*). | `page=1` | Web Application Firewall |
| Network | The IP address of the client making the HTTP request, which can be used for any network comparison (CIDR, ASN or Country) | `1xx.xxx.x.0` | Network Shield |
| Host | In order of precedence: the *hostname* of the request line, or the value of the *Host* header field of the request, or the name of the server serving the request | `api.example.com` | - |
| Request Method | The request's HTTP method. For example: `GET`, `POST`, `PUT`, etc. | `POST` | -                        |
| Request URI | This relates to the `${uri}` variable from Rules Engine for Applications. The normalized (urldecoded) URI of the request. The value of `${uri}` can change during the processing of a request, for example, when an internal redirect occurs or when index files are used. It doesn't carry the Query String parameters as `${request_uri}` do.| `/api/v1/` | - |
| Scheme | The scheme of the request: HHTP or HTTPS. | `https` | - |
| Client Certificate Validation | Server process to authenticate client digital certificate. | `true` | - | 
| SSL Verification Status | Server result to client certificate validation. It can be `Success`, when the client certificate validation passed; `Certificate Verification Error`, when the client certificate wasn't valid; and `Missing Client Certificate`, when the client certificate wasn't sent in the request. | `Certificate Verification Error` | - |  

### Comparison operators

The condition for the execution of a rule must be the comparison of a variable with an argument. The comparison operators are:

| Operator | Description | Argument type |
| -------- | ----------- | -------- |
| is equal | The value of the variable is equal to the argument, compared character by character | String |
| is not equal | The value of the variable isn't exactly the same as the argument | String |
| starts with | The value of the variable starts with the argument | String |
| does not start with | The value of the variable doesn't start with the argument | String |
| matches | The value of the variable matches the regular expression or list entered as an argument | Regular expression or list |
| does not match | The value of the variable doesn't match the regular expression entered as an argument | Regular expression or list |
| exists | The variable has a defined value. For example, `Request Args` exists if an argument is sent in the request's query string | - |
| does not exist | The variable doesn't have a defined value. For example, `Request Args` doesn't exist if an argument is sent in the request's query string | - |

:::note
These operators may vary according to the selected Criteria.
:::

### Logic operators

Multiple criteria can be defined using the logical operators `And` and `Or`. 

:::note
The operator `And` has implicit precedence over the operator `Or`.
:::

If explicit precedence is required, you can add multiple criteria groups under the `And` logic.

---

## Behaviors

In the Behaviors section of the Rules Engine, you must add the behaviors you want your rule to perform if the conditions defined in the criteria are met.

For example, this behavior runs the specified function, allowing you to execute custom logic for handling requests.

| Behavior | Argument |
| --- | ---- |
| `Run Function` | `<name-of-the-instantiated-function>` |

### Deny (403 Forbidden)

It closes the request with an HTTP *403 Forbidden* response. No arguments are required.

### Drop (Close Without Response) 

It closes the request without responding to the customer. No arguments are required.

### Set Rate Limit

It defines an access rate limit that, if exceeded, will result in an HTTP *429 Too Many Requests* response. To configure the *Rate Limit*, you must inform:

- `Type` is the field to select the type of request for the Rate Limit, choosing `Req/s` (requests per second) or `Req/min` (requests per minute).
- `Average Rate Limit`, which is the limit rate itself by second.
- `Client IP address`, if you want the access rate to be counted by the client's IP address or `Global`, if you want total access rate counted. 
- `Maximum burst size`, which indicates the maximum burst size of HTTP requests sent simultaneously, which will be queued and dispatched gradually, respecting the limit rate.
   - The configured value will be the Rate Limit for each Azion Edge Node, implemented using the Leaky Bucket algorithm. It's recommended to use `Maximum burst size` at a maximum of 10 times of the value configured in `Average Rate Limit`, which would result in penalizing the last request for a burst with up to a 10 second delay.

As the Rate Limit is applied by IP address of Global and by rule, if a rule has *more than one URI* specified and uses the *conditional Or*, the rate limit will be shared between the URIs. Create different rules if you wish to have a Rate Limite for each URI.

:::note
The `Maximum Burst size` is only available for the `Req/s` (request per second).
:::

### Set WAF Rule Set 

<Tag severity="info">Requires WAF</Tag>

It associates the WAF Rule Set to be used in the request. WAF policies must be previously configured in **Edge Libraries** > **WAF Rules**. You must also define the **WAF mode**: **Learning** or **Blocking**. Read more on [WAF Rule Sets](/en/documentation/products/secure/firewall/web-application-firewall/rules-set/). 

:::caution[Warning]
Azion platform maintains only one `Set WAF Rule Set` behavior configuration for each criteria logic. If you have two different firewalls configured with the same criteria logic but different `Set WAF Rule Set` behaviors, only the most recent one will be processed. This can be useful in case your application needs constant switching between two or more behaviors for the same criteria.
:::

### Run Function

<Tag severity="info">Requires Functions</Tag>

It runs a function specified as a parameter. The function must have been previously [instantiated and parameterized](/en/documentation/products/guides/secure/instantiate-functions/) in the Functions tab in order to be used.

### Set Custom Response

It allows a customized response when the request matches the criteria. You can customize the `Status Code` by changing it from 200 to 499, the `Content Type` header, and `Content Body` of your request with a maximum of `500` characters.

### Behaviors execution and logic

<RulesExecution />

---

## Debugging rules

You can [debug rules created with Rules Engine for Firewall](/en/documentation/products/guides/debug-rules/) through the GraphQL API, Data Stream, or Real-Time Events.

---

Watch a video tutorial about programming Firewall rules for optimal WAF usage and cost optimization on Azion's YouTube channel:

<Video src="https://www.youtube.com/embed/HhVdxVnOnvw" title="Rules Engine for Firewall" description="Implement security logic, based on criteria and behaviors, with Rules Engine for Firewall." uploadDate="2023-07-03" />