Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DOC Update secure coding documentation to reflect best practices #696

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 106 additions & 74 deletions en/02_Developer_Guides/09_Security/05_Secure_Coding.md
Original file line number Diff line number Diff line change
Expand Up @@ -660,115 +660,159 @@ This is a recommended option to secure any controller which displays
or submits sensitive user input, and is enabled by default in all CMS controllers,
as well as the login form.

## Request hostname forgery {#request-hostname-forgery}
## Request hostname forgery and host header injection attacks {#request-hostname-forgery}

To prevent a forged hostname appearing being used by the application, Silverstripe CMS
allows the configure of a whitelist of hosts that are allowed to access the system. By defining
this whitelist in your `.env` file, any request presenting a `Host` header that is
*not* in this list will be blocked with a HTTP 400 error:
Ideally your hosting will reject invalid host headers. For example Apache allows you to define valid hosts as part of the virtual host configuration, and a Web Application Firewall (WAF) can also be configured to validate the host header. However if your hosting is set to allow *any* host header, your project might be vulnerable to host header injection attacks.

To prevent a forged hostname being used by your application, Silverstripe CMS
allows the configuration of an allow list of valid hosts that are allowed in the `Host` header. This is an extra layer of protection against this type of attack.
By defining this allow list, any request presenting a `Host` header that is *not* in this list will be blocked with a HTTP 400 error.

While you should have appropriate validation at a hosting level, it is best practice to also configure this in your project.

The main way to configure this is using the `SS_ALLOWED_HOSTS` environment variable:

```bash
SS_ALLOWED_HOSTS="www.example.com,example.com,subdomain.example.com"
SS_ALLOWED_HOSTS="example.com,www.example.com,subdomain.example.com"
```

You can also configure the allow list with YAML configuration, which can be useful if you don't have full control over your hosting:

```yml
---
after: requestprocessors
---
SilverStripe\Core\Injector\Injector:
SilverStripe\Control\Middleware\AllowedHostsMiddleware:
properties:
AllowedHosts:
- 'example.com'
- 'www.example.com'
- 'subdomain.example.com'
```

Please note that if this configuration is defined, you *must* include *all* subdomains (eg `<www>.`)
that will be accessing the site.
> [!WARNING]
> Please note that you *must* include *all* subdomains (eg `www.`) that will be serving out content from the project using the same codebase.
> For example if your CMS serves content on the following hosts, *all* of them must be added to the allow list:
>
> - `example.com` (primary domain)
> - `www.example.com` (www subdomain)
> - `blog.example.com` (subdomain for a blog)
> - `example.org` (secondary domain serving the same content)

Note that domains which only *redirect* to your project (i.e. with a `301` HTTP response) should not be added as allowed hosts.

### Reverse proxies and forwarded hosts

When Silverstripe CMS is run behind a reverse proxy, it's normally necessary for this proxy to
use the `X-Forwarded-Host` request header to tell the webserver which hostname was originally
requested. However, when Silverstripe CMS is not run behind a proxy, this header can still be
requested. The [`TrustedProxyMiddleware`](api:SilverStripe\Control\Middleware\TrustedProxyMiddleware) ensures only trusted IP addresses are allowed to use
that header to override the host header in Silverstripe CMS.

Without that middleware, the `X-Forwarded-Host` header could be
used by attackers to fool the server into mistaking its own identity.

The risk of this kind of attack causing damage is especially high on sites which utilise caching
mechanisms, as rewritten urls could persist between requests in order to misdirect other users
into visiting external sites.

In order to prevent this kind of attack, it's necessary to whitelist trusted proxy
server IPs using the SS_TRUSTED_PROXY_IPS define in your `.env`.
In order to prevent this kind of attack, if your project is behind a reverse proxy, it's necessary to define the trusted proxy
server IP addresses in an allow list.

The primary way to define this allow list is using the `SS_TRUSTED_PROXY_IPS` environment variable:

```bash
SS_TRUSTED_PROXY_IPS="127.0.0.1,192.168.0.1"
```

You can also whitelist subnets in CIDR notation if you don't know the exact IP of a trusted proxy.
For example, some cloud provider load balancers don't have fixed IPs.
You can also allow subnets in CIDR notation if you don't know the exact IP of a trusted proxy.
For example, some cloud provider load balancers don't have fixed IP addresses.

```bash
SS_TRUSTED_PROXY_IPS="10.10.0.0/24,10.10.1.0/24,10.10.2.0/24"
```

If you wish to change the headers that are used to find the proxy information, you should reconfigure the
TrustedProxyMiddleware service:
You can also define the allow list using YAML configuration:

```yml
SilverStripe\Control\TrustedProxyMiddleware:
properties:
ProxyHostHeaders: X-Forwarded-Host
ProxySchemeHeaders: X-Forwarded-Protocol
ProxyIPHeaders: X-Forwarded-Ip
```

```bash
SS_TRUSTED_PROXY_HOST_HEADER="HTTP_X_FORWARDED_HOST"
SS_TRUSTED_PROXY_IP_HEADER="HTTP_X_FORWARDED_FOR"
SS_TRUSTED_PROXY_PROTOCOL_HEADER="HTTP_X_FORWARDED_PROTOCOL"
---
after: requestprocessors
---
SilverStripe\Core\Injector\Injector:
SilverStripe\Control\Middleware\TrustedProxyMiddleware:
properties:
TrustedProxyIPs:
- '127.0.0.1'
- '192.168.0.1'
```

At the same time, you'll also need to define which headers you trust from these proxy IPs. Since there are multiple ways through which proxies can pass through HTTP information on the original hostname, IP and protocol, these values need to be adjusted for your specific proxy. The header names match their equivalent `$_SERVER` values.

If there is no proxy server, 'none' can be used to distrust all clients.
If there is no proxy server, 'none' can be used to explicitly distrust all clients.
If only trusted servers will make requests then you can use '*' to trust all clients.
Otherwise a comma separated list of individual IP addresses (or subnets in CIDR notation) should be declared.

This behaviour is enabled whenever `SS_TRUSTED_PROXY_IPS` is defined, or if the
`BlockUntrustedIPs` environment variable is declared. It is advisable to include the
following in your .htaccess to ensure this behaviour is activated.

```text
<IfModule mod_env.c>
# Ensure that X-Forwarded-Host is only allowed to determine the request
# hostname for servers ips defined by SS_TRUSTED_PROXY_IPS in your .env
# Note that in a future release this setting will be always on.
SetEnv BlockUntrustedIPs true
</IfModule>
```
At the same time, you'll also need to define which headers you trust from these proxy IPs. Since there are multiple ways through which proxies can pass through HTTP information on the original hostname, IP and protocol, these values need to be adjusted for your specific proxy. The header names match their equivalent `$_SERVER` values.

This behaviour is on by default; the environment variable is not required. For correct operation, it is necessary to always set `SS_TRUSTED_PROXY_IPS` if using a proxy.
If you wish to change the headers that are used to find the proxy information, you should reconfigure the
`TrustedProxyMiddleware` service:

## Secure sessions, cookies and TLS (HTTPS)
```yml
SilverStripe\Control\TrustedProxyMiddleware:
properties:
ProxyHostHeaders: X-Forwarded-Host
ProxySchemeHeaders: X-Forwarded-Protocol
ProxyIPHeaders: X-Forwarded-Ip
```

Silverstripe CMS recommends the use of TLS (HTTPS) for your application, and you can easily force the use through the
director function `forceSSL()`
## TLS (aka SSL aka HTTPS)

```php
use SilverStripe\Control\Director;
Silverstripe CMS recommends the use of TLS (HTTPS) for your application. You can configure this by setting the `ForceSSL` property on the [`CanonicalURLMiddleware`](api:SilverStripe\Control\Middleware\CanonicalURLMiddleware) singleton.

if (!Director::isDev()) {
Director::forceSSL();
Copy link
Member Author

@GuySartorelli GuySartorelli Feb 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This API does exist but it's a lot less powerful than configuring via YAML because

  • there are a lot of options on CanonicalURLMiddleware that can't be set via director (even the rest of this old docs has to instantiate a singleton of the middleware to set something)
  • you ideally want everything configuring this in the same place - so if you have to set some of it in YAML and then some here, that's hard to notice and may cause problems
  • I'd expect basically every project that configures CanonicalURLMiddleware uses YAML, following CWP's example.

Basically there's no good reason to be setting this in _config.php

}
```yml
---
After: '#canonicalurls'
---
SilverStripe\Core\Injector\Injector:
SilverStripe\Control\Middleware\CanonicalURLMiddleware:
properties:
ForceSSL: true
```

`forceSSL()` will only take effect in environment types that `CanonicalURLMiddleware` is configured to apply to (by
will only take effect in environment types that `CanonicalURLMiddleware` is configured to apply to (by
default, only `LIVE`). To apply this behaviour in all environment types, you'll need to update that configuration:

```php
use SilverStripe\Control\Director;
use SilverStripe\Control\Middleware\CanonicalURLMiddleware;

if (!Director::isDev()) {
// You can also specify individual environment types
CanonicalURLMiddleware::singleton()->setEnabledEnvs(true);
Director::forceSSL();
}
```yml
---
After: '#canonicalurls'
---
SilverStripe\Core\Injector\Injector:
SilverStripe\Control\Middleware\CanonicalURLMiddleware:
properties:
# ...
EnabledEnvs:
- test
- dev
```

Forcing HTTPS so requires a certificate to be purchased or obtained through a vendor such as
[lets encrypt](https://letsencrypt.org/) and configured on your web server.

Note that by default enabling SSL will also enable `CanonicalURLMiddleware::forceBasicAuthToSSL` which will detect
and automatically redirect any requests with basic authentication headers to first be served over HTTPS. You can
disable this behaviour using `CanonicalURLMiddleware::singleton()->setForceBasicAuthToSSL(false)`, or via Injector
configuration in YAML.
disable this behaviour setting the `ForceBasicAuthToSSL` property to `false` in the YAML configuration.

### Using SSL in database connections

In some circumstances, like connecting to a database on a remote host for example, you may wish to enable SSL encryption to ensure the protection of sensitive information and database access credentials.
You can configure that by setting the following environment variables:

| Name | Description |
| ---- | ----------- |
| `SS_DATABASE_SSL_KEY` | Absolute path to SSL key file (optional - but if set, `SS_DATABASE_SSL_CERT` must also be set) |
| `SS_DATABASE_SSL_CERT` | Absolute path to SSL certificate file (optional - but if set, `SS_DATABASE_SSL_KEY` must also be set) |
| `SS_DATABASE_SSL_CA` | Absolute path to SSL Certificate Authority bundle file (optional) |
| `SS_DATABASE_SSL_CIPHER` | Custom SSL cipher for database connections (optional) |
Comment on lines +803 to +813
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to move this to be adjacent to the other bit of docs talking about TLS.


## Secure sessions and cookies
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense to separate this into its own section - secure cookies and TLS are sort-of related but I don't think enough so to join them together like that.


We also want to ensure cookies are not shared between secure and non-secure sessions, so we must tell Silverstripe CMS to
use a [secure session](/developer_guides/cookies_and_sessions/sessions/#secure-session-cookie).
Expand Down Expand Up @@ -826,18 +870,6 @@ Cookie::set(
);
```

### Using SSL in database connections

In some circumstances, like connecting to a database on a remote host for example, you may wish to enable SSL encryption to ensure the protection of sensitive information and database access credentials.
You can configure that by setting the following environment variables:

| Name | Description |
| ---- | ----------- |
| `SS_DATABASE_SSL_KEY` | Absolute path to SSL key file (optional - but if set, `SS_DATABASE_SSL_CERT` must also be set) |
| `SS_DATABASE_SSL_CERT` | Absolute path to SSL certificate file (optional - but if set, `SS_DATABASE_SSL_KEY` must also be set) |
| `SS_DATABASE_SSL_CA` | Absolute path to SSL Certificate Authority bundle file (optional) |
| `SS_DATABASE_SSL_CIPHER` | Custom SSL cipher for database connections (optional) |

## Security headers

In addition to forcing HTTPS browsers can support additional security headers which can only allow access to a website
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ icon: cookie-bite
# Cookies

Note that cookies can have security implications - before setting your own cookies, make sure to read through the
[secure coding](/developer_guides/security/secure_coding#secure-sessions-cookies-and-tls-https) documentation.
[secure coding](/developer_guides/security/secure_coding#secure-sessions-and-cookies) documentation.

## Accessing and manipulating cookies

Expand Down