# Firewall

Here are the default settings for configuring the security firewall in CBSecurity:

```javascript
/**
 * --------------------------------------------------------------------------
 * Firewall Settings
 * --------------------------------------------------------------------------
 * The firewall is used to block/check access on incoming requests via security rules or via annotation on handler actions.
 * Here you can configure the operation of the firewall and especially what Validator will be in charge of verifying authentication/authorization
 * during a matched request.
 */
firewall : {
	// Auto load the global security firewall automatically, else you can load it a-la-carte via the `Security` interceptor
	"autoLoadFirewall"            : true,
	// The Global validator is an object that will validate the firewall rules and annotations and provide feedback on either authentication or authorization issues.
	"validator"                   : "CBAuthValidator@cbsecurity",
	// Activate handler/action based annotation security
	"handlerAnnotationSecurity"   : true,
	// The global invalid authentication event or URI or URL to go if an invalid authentication occurs
	"invalidAuthenticationEvent"  : "",
	// Default Auhtentication Action: override or redirect when a user has not logged in
	"defaultAuthenticationAction" : "redirect",
	// The global invalid authorization event or URI or URL to go if an invalid authorization occurs
	"invalidAuthorizationEvent"   : "",
	// Default Authorization Action: override or redirect when a user does not have enough permissions to access something
	"defaultAuthorizationAction"  : "redirect",
	// Firewall database event logs.
	"logs" : {
		"enabled"    : false,
		"dsn"        : "",
		"schema"     : "",
		"table"      : "cbsecurity_logs",
		"autoCreate" : true
	}
	// Firewall Rules, this can be a struct of detailed configuration
	// or a simple array of inline rules
	"rules"                       : {
		// Use regular expression matching on the rule match types
		"useRegex" : true,
		// Force SSL for all relocations
		"useSSL"   : false,
		// A collection of default name-value pairs to add to ALL rules
		// This way you can add global roles, permissions, redirects, etc
		"defaults" : {},
		// You can store all your rules in this inline array
		"inline"   : [],
		// If you don't store the rules inline, then you can use a provider to load the rules
		// The source can be a json file, an xml file, model, db
		// Each provider can have it's appropriate properties as well. Please see the documentation for each provider.
		"provider" : { "source" : "", "properties" : {} }
	}
},
```

### AutoLoadFirewall

The security firewall is always enabled by default, but you can disable it globally if you like.

```javascript
autoLoadFirewall : false
```

### HandlerAnnotationSecurity

By default, annotation security is enabled. This will inspect ALL incoming event executions for the security annotation `secured`. If you do not want to use annotation security, we recommend you turn it off to avoid the inspection of events.

```javascript
handlerAnnotationSecurity : false
```

### Validator

This global validator will be used to validate authentication/authorization.  The default is `CBAuthValidator@cbsecurity`.  This object needs to match the interface: `cbsecurity.interfaces.ISecurityValidator` .  The available validators we ship are:

* **CBAuth Validator**: this is the default validator, which uses the [cbauth](https://cbauth.ortusbooks.com/) module. It provides authentication and *permission-*&#x62;ased security.
* **CFML Security Validator:** Coldbox security has had this validator since version 1,  and it will talk to the ColdFusion engine's security methods (`cflogin,cflogout`). It provides authentication and *role-based* security.
* **Basic Auth Validator:** This validator secures your app via [basic authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication) browser challenges to incoming requests. It can also work with the `BasicAuthUserService` and provide you a basic user credentials storage within your configuration file.&#x20;
* **JWT Validator**: If you want to use JSON Web Tokens, the JWT Validator provides authorization and authentication by validating incoming access/refresh tokens via headers for RESTFul API communications.
* **Custom Validator:** You can define your own authentication and authorization engines and plug them into the cbsecurity framework.

```javascript
validator : "BasicAuthValidator@cbsecurity"
```

### InvalidAuthenticationEvent

This setting is used to set the global event that will be executed or redirected to if an invalid authentication is detected.  Usually, you want to direct users to a login screen.

```javascript
"invalidAuthenticationEvent"  : "security.login",
```

### DefaultAuthenticationAction

We set the default event above, but how do we get there? This setting is the action the firewall will take when an invalid authentication event is detected. &#x20;

1. `redirect` - Redirect them to the `invalidAuthenticationEvent`
2. `override` - Override the incoming event to the `invalidAuthenticationEvent`
3. `block` - Block the request entirely with a 401 Not Authorized response.

### InvalidAuthorizationEvent

This setting is used to set the global event that will be executed or redirected to if an invalid authorization is detected.  Usually, you could direct them to a not authorized page.

```javascript
"invalidAuthorizationEvent"  : "dashboard.notAuthorized",
```

### DefaultAuthorizationAction

We set the default event above, but how do we get there? This setting is the action the firewall will take when an invalid authorization event is detected. &#x20;

1. `redirect` - Redirect them to the `invalidAuthorizationEvent`
2. `override` - Override the incoming event to the `invalidAuthorizationEvent`
3. `block` - Block the request entirely with a 401 Not Authorized response.

### Logs

You can enable the firewall logs, and CBSecurity will log all blocks the firewall detects.  By default, it is disabled, but if you enable the logs, we will create the table for you.

```javascript
"logs" : {
    "enabled"    : false,
    "dsn"        : "",
    "schema"     : "",
    "table"      : "cbsecurity_logs",
    "autoCreate" : true
}
```

{% hint style="info" %}
The `dsn` key is optional, and CBSecurity will inspect the Application settings for a default datasource.
{% endhint %}

We have also included a migrations file so you can add this to your database migrations schemas.  Just run: `migrate create create_cbsecurity_logs_table` and fill it out with this:

{% code lineNumbers="true" %}

```javascript
component {

	variables.INDEX_COLUMNS = [
		"userId",
		"userAgent",
		"ip",
		"host",
		"httpMethod",
		"path",
		"referer"
	];

	function up( schema, qb ){
		schema.create( "cbsecurity_logs", function( table ){
			table.string( "id", 36 ).primaryKey();
			table.timestamp( "logDate" ).withCurrent();
			table.string( "action" );
			table.string( "blockType" );
			table.string( "ip" );
			table.string( "host" );
			table.string( "httpMethod" );
			table.string( "path" );
			table.string( "queryString" );
			table.string( "referer" ).nullable();
			table.string( "userAgent" );
			table.string( "userId" ).nullable();
			table.longText( "securityRule" ).nullable();
			table.index( [ "logDate", "action", "blockType" ], "idx_cbsecurity" );

			INDEX_COLUMNS.each( ( key ) => {
				table.index( [ arguments.key ], "idx_cbsecurity_#arguments.key#" );
			} );
		} );
	}

	function down( schema, qb ){
		schema.drop( "cbsecurity_logs" );
	}

}
```

{% endcode %}

### Rules

This key defines where rules come from and how they interact with the firewall.  The `rules` key can be of two types:

* An `array` of rules
* A `struct` of configuration with a rule source

#### Array of Rules

This is the shorthand way of defining global rules.

```javascript
"rules" : [
	// should use direct action and do a global redirect
	{
		"whitelist"   : "",
		"securelist"  : "admin",
		"match"       : "event",
		"roles"       : "admin",
		"permissions" : "",
		"action"      : "redirect",
		"httpMethods" : "*"
	},
	// Match only put/post
	{
		"whitelist"   : "",
		"securelist"  : "putpost",
		"match"       : "event",
		"roles"       : "",
		"permissions" : "",
		"action"      : "block",
		"httpMethods" : "put,post"
	},
	{
		"whitelist"   : "",
		"securelist"  : "cfide",
		"match"       : "url",
		"roles"       : "",
		"permissions" : "",
		"action"      : "redirect",
		"allowedIPs"  : "10.0.0.1"
	},
	// no action, use global default action
	{
		"whitelist"   : "",
		"securelist"  : "noAction",
		"match"       : "url",
		"roles"       : "admin",
		"permissions" : "",
		"httpMethods" : "*"
	}
]
```

#### Rule Configuration

If this setting is a struct, you can configure how the rules behave and where they come from JSON, XML, database, model, etc.

<pre class="language-javascript"><code class="lang-javascript"><strong>"rules" : {
</strong>    // Use regular expression matching on the rule match types
    "useRegex" : true,
    // Force SSL for all relocations
    "useSSL"   : false,
    // A collection of default name-value pairs to add to ALL rules
    // This way you can add global roles, permissions, redirects, etc
    "defaults" : {},
    // You can store all your rules in this inline array
    "inline"   : [],
    // If you don't store the rules inline, then you can use a provider to load the rules
    // The source can be a json file, an xml file, model, db
    // Each provider can have it's appropriate properties as well. Please see the documentation for each provider.
    "provider" : { "source" : "", "properties" : {} }
}
</code></pre>

#### useRegex

This is `true` by default.   It tells the firewall to use regular expression matching against white and secure lists in a rule.

#### useSSL

If `true` then if a security rule needs to do a redirect, it will force the redirect to SSL. This defaults to `false`.

#### defaults

This is a collection of name-value pairs that each security rule will inherit by default.

```javascript
defaults : {
    action : "block",
    roles  : "users"
}
```

#### inline

This is an array that holds all the rules you can define in CFML. This is the same as making the entire `rules` key an array of rules.

```javascript
"rules" : {
    // You can store all your rules in this inline array
    "inline"   : [
	// should use direct action and do a global redirect
	{
		"whitelist"   : "",
		"securelist"  : "admin",
		"match"       : "event",
		"roles"       : "admin",
		"permissions" : "",
		"action"      : "redirect",
		"httpMethods" : "*"
	},
	// Match only put/post
	{
		"whitelist"   : "",
		"securelist"  : "putpost",
		"match"       : "event",
		"roles"       : "",
		"permissions" : "",
		"action"      : "block",
		"httpMethods" : "put,post"
	}
    ]
}
```

#### provider

The `provider` key is how you can define rules from the following sources:

* A JSON file
* An XML file
* From a model object via a method call
* From a database

Here are the different ways you can define rules from other sources rather than inline:

{% content-ref url="/pages/-LTJ0k-4j6u9wQ5zwn9d" %}
[DB Rules](/getting-started/configuration/firewall/untitled.md)
{% endcontent-ref %}

{% content-ref url="/pages/-LTJ1v\_hNnjsikLmqXzv" %}
[JSON Rules](/getting-started/configuration/firewall/json-properties.md)
{% endcontent-ref %}

{% content-ref url="/pages/-Lp-8TeC7az5DWyOipiQ" %}
[Model Rules](/getting-started/configuration/firewall/model-rules.md)
{% endcontent-ref %}

{% content-ref url="/pages/-LTJ1uzOrjwuNmxKDcop" %}
[XML Rules](/getting-started/configuration/firewall/xml-properties.md)
{% endcontent-ref %}

{% hint style="success" %}
Please note that defining rules are both the same in a global ColdBox config as in a ModuleConfig.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coldbox-security.ortusbooks.com/getting-started/configuration/firewall.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
