Skip to content

Commit

Permalink
Update Symfony_Cheat_Sheet.md (#1384)
Browse files Browse the repository at this point in the history
Some lite spelling and grammar tweaks.
  • Loading branch information
aolives authored Apr 22, 2024
1 parent f299ae7 commit f650787
Showing 1 changed file with 37 additions and 37 deletions.
74 changes: 37 additions & 37 deletions cheatsheets/Symfony_Cheat_Sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ By following the guidelines outlined here, you can strengthen the security of yo
Cross-Site Scripting (XSS) is a type of attack where malicious JavaScript code is injected into a displayed variable.
For example, if the value of the variable name is `<script>alert('hello')</script>`, and we display it in HTML like this: `Hello {{name}}`, the injected script will be executed when the HTML is rendered.

Symfony comes by default with twig templates that automatically protect applications from XSS attacks by using **output escaping** to transform variables containing special characters by wrapping variable with `{{ }}` statement.
Symfony comes by default with twig templates that automatically protect applications from XSS attacks by using **output escaping** to transform variables containing special characters by wrapping the variable with `{{ }}` statement.

```twig
<p>Hello {{name}}</p>
Expand All @@ -35,7 +35,7 @@ exactly that instead of 'Lorem &lt;strong&gt;Ipsum&lt;/strong&gt;' #}

Explore the [Twig output escaping documentation](https://twig.symfony.com/doc/3.x/api.html#escaper-extension) to gain insights into disabling output escaping for a specific block or an entire template.

For other information on XSS prevention that is not specific to Symfony, you may refer the [Cross Site Scripting Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md).
For other information on XSS prevention that is not specific to Symfony, you may refer to the [Cross Site Scripting Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md).

### Cross-Site Request Forgery (CSRF)

Expand Down Expand Up @@ -77,7 +77,7 @@ framework:
csrf_protection: ~
```
Next consider this HTML Twig template when CSRF token is generated by `csrf_token()` Twig function
Next, consider this HTML Twig template when a CSRF token is generated by the `csrf_token()` Twig function

```twig
<form action="{{ url('delete_post', { id: post.id }) }}" method="post">
Expand All @@ -86,7 +86,7 @@ Next consider this HTML Twig template when CSRF token is generated by `csrf_toke
</form>
```

Then you can get value of CSRF token in controller using `isCsrfTokenValid()` function:
Then you can get the value of the CSRF token in the controller using the `isCsrfTokenValid()` function:

```php
use App\Entity\Post;
Expand Down Expand Up @@ -119,7 +119,7 @@ SQL Injection is a type of security vulnerability that occurs when an attacker i
This can allow attackers to view, modify, or delete data in the database, potentially leading to unauthorized access or data loss.

Symfony, particularly when used with Doctrine ORM (Object-Relational Mapping), provides protection against SQL injection through prepared statements parameters.
Thanks to this it is harder to mistakenly write unprotected queries, however it is still possible.
Thanks to this it is harder to mistakenly write unprotected queries, however, it is still possible.
The following example shows **insecure DQL usage**:

```php
Expand All @@ -144,7 +144,7 @@ class ExampleController extends AbstractController {
```

Examples bellow shows the **correct ways** that provides protection against SQL Injection:
The examples below show the **correct ways** to provide protection against SQL Injection:

- Using entity repository built-in method

Expand Down Expand Up @@ -173,15 +173,15 @@ $post = $qb->select('p')
->getSingleResult();
```

For more information about Doctrine you can refer to [their documentation](https://www.doctrine-project.org/index.html).
You may also refer the [SQL Injection Prevention Cheatsheet](SQL_Injection_Prevention_Cheat_Sheet.md) for more information that is not specific to neither Symfony nor Doctrine.
For more information about Doctrine, you can refer to [their documentation](https://www.doctrine-project.org/index.html).
You may also refer to the [SQL Injection Prevention Cheatsheet](SQL_Injection_Prevention_Cheat_Sheet.md) for more information that is not specific to either Symfony or Doctrine.

### Command Injection

Command Injection occurs when malicious code is injected into an application system and executed.
For more information refer to [Command Injection Defense Cheat Sheet](OS_Command_Injection_Defense_Cheat_Sheet.md).

Consider the following example, where file is removed using the exec() function without any input escaping:
Consider the following example, where a file is removed using the exec() function without any input escaping:

```php
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -204,7 +204,7 @@ class ExampleController
}
```

In the above code, there is no any validation of user's input. Imagine what could happen if user provides a malicious value like `test.txt && rm -rf .` . To mitigate this risk, it is advisable to use native PHP functions like in this case `unlink()` or Symfony Filesystem Component `remove()` method instead of `exec()`.
In the above code, there is no validation of the user's input. Imagine what could happen if the user provides a malicious value like `test.txt && rm -rf .` . To mitigate this risk, it is advisable to use native PHP functions like in this case `unlink()` or Symfony Filesystem Component `remove()` method instead of `exec()`.

For specific PHP filesystem functions relevant to your case, you can refer to the [PHP documentation](https://www.php.net/manual/en/refs.fileprocess.file.php) or [Symfony Filesystem Component documentation](https://symfony.com/doc/current/components/filesystem.html).

Expand Down Expand Up @@ -241,7 +241,7 @@ File upload vulnerabilities are security issues that arise when an application d
#### Validate file type and size

Always validate the file type on the server side to ensure that only allowed file types are accepted.
Also consider limiting the size of uploaded files to prevent denial-of-service attacks and to ensure that your server has enough resources to handle the uploads.
Also, consider limiting the size of uploaded files to prevent denial-of-service attacks and to ensure that your server has enough resources to handle the uploads.

Example with PHP Attributes:

Expand Down Expand Up @@ -298,18 +298,18 @@ Ensure that each uploaded file has a unique name to prevent overwriting existing

#### Store uploaded files securely

Store uploaded files outside the public directory to prevent direct access. If you use public directory to store them, configure your web server to deny access to the upload directory.
Store uploaded files outside the public directory to prevent direct access. If you use a public directory to store them, configure your web server to deny access to the upload directory.

Refer the [File Upload Cheatsheet](File_Upload_Cheat_Sheet.md) to learn more.
Refer to the [File Upload Cheatsheet](File_Upload_Cheat_Sheet.md) to learn more.

### Directory Traversal

A directory or path traversal attack aims to access files and directories that are stored on server by manipulating input data that reference files with “../” *dot-dot-slash* sequences and its variations or by using absolute file paths.
A directory or path traversal attack aims to access files and directories that are stored on a server by manipulating input data that reference files with “../” *dot-dot-slash* sequences and its variations or by using absolute file paths.
For more details refer to [OWASP Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal).

You can protect your application before directory traversal attack by validating whether the absolute path of requested file location is correct or strip out directory information from filename input.
You can protect your application from a directory traversal attack by validating whether the absolute path of the requested file location is correct or strip out the directory information from filename input.

- Check if path exists using PHP *realpath* function and that it leads to the storage directory
- Check if the path exists using the PHP *realpath* function and check that it leads to the storage directory

```php
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
Expand Down Expand Up @@ -365,7 +365,7 @@ composer update
When using multiple dependencies, some of them may contain security vulnerabilities.
To address this concern, Symfony comes with [Symfony Security Checker](https://symfony.com/doc/current/setup.html#checking-security-vulnerabilities). This tool specifically examines the *composer.lock* file in your project to identify any known security vulnerabilities within the dependencies that have been installed and address any potential security issues in your Symfony project.

To use Security Checker run following command using [Symfony CLI](https://github.com/symfony-cli/symfony-cli):
To use Security Checker run the following command using [Symfony CLI](https://github.com/symfony-cli/symfony-cli):

```bash
symfony check:security
Expand All @@ -377,13 +377,13 @@ You should also consider similar tools:

- [Enlightn Security Checker](https://github.com/enlightn/security-checker)

### Cross Origin Resource Sharing
### Cross-Origin Resource Sharing (CORS)

CORS is a security feature implemented in web browsers to control how web applications in one domain can request and interact with resources hosted on another domains.
CORS is a security feature implemented in web browsers to control how web applications in one domain can request and interact with resources hosted on other domains.

In Symfony you can manage CORS policies using `nelmio/cors-bundle`. This bundle lets you control CORS rules precisely without changing your server settings.
In Symfony, you can manage CORS policies using `nelmio/cors-bundle`. This bundle lets you control CORS rules precisely without changing your server settings.

To install it with composer, run:
To install it with Composer, run:

```bash
composer require nelmio/cors-bundle
Expand Down Expand Up @@ -421,9 +421,9 @@ It's advisable to enhance the security of your Symfony application by adding to
- Cross-Origin-Resource-Policy
- Cache-Control

To find more details about individual header refer to [OWASP secure headers project](https://owasp.org/www-project-secure-headers/).
To find more details about individual headers refer to the [OWASP secure headers project](https://owasp.org/www-project-secure-headers/).

In Symfony you can add those headers either manually or automatically by listening the [ResponseEvent](https://symfony.com/doc/current/reference/events.html#kernel-response) to your to every response or configuring web servers like Nginx or Apache.
In Symfony, you can add those headers either manually or automatically by listening the [ResponseEvent](https://symfony.com/doc/current/reference/events.html#kernel-response) to your to every response or configuring web servers like Nginx or Apache.

```php
use Symfony\Component\HttpFoundation\Request;
Expand All @@ -434,9 +434,9 @@ $response->headers->set('X-Frame-Options', 'SAMEORIGIN');

### Session & Cookies Management

By default sessions are securely configured and enabled. However, they can be controlled manually in `config/packages/framework.yaml` under the `framework.session` key. Make sure to set the following in your session configuration to make your application more aware.
By default, sessions are securely configured and enabled. However, they can be controlled manually in `config/packages/framework.yaml` under the `framework.session` key. Make sure to set the following in your session configuration to make your application more aware.

Ensure `cookie_secure` is not explicitly set to `false`(it is set to `true` by default). Setting http only to `true` means that cookie won't be accessible by JavaScript.
Ensure `cookie_secure` is not explicitly set to `false`(it is set to `true` by default). Setting http only to `true` means that the cookie won't be accessible by JavaScript.

```yaml
cookie_httponly: true
Expand All @@ -448,7 +448,7 @@ Make sure to set a short session TTL duration. According to [OWASP's recommendat
cookie_lifetime: 5
```

It is recommended to set `cookie_samesite` to either `lax` or `strict` to prevent cookies being send from cross-origin requests. `lax` allows the cookie to be sent along with "safe" top-level navigations and same-site requests. With `strict` it would not be possible to send any cookie when the HTTP request is not from the same domain.
It is recommended to set `cookie_samesite` to either `lax` or `strict` to prevent cookies from being sent from cross-origin requests. `lax` allows the cookie to be sent along with "safe" top-level navigations and same-site requests. With `strict` it would not be possible to send any cookie when the HTTP request is not from the same domain.

```yaml
cookie_samesite: lax|strict
Expand All @@ -461,7 +461,7 @@ cookie_secure: auto
```

OWASP provides more general information about sessions in [Session Management Cheat Sheet](Session_Management_Cheat_Sheet.md).
You may also refer the [Cookie Security Guide](https://owasp.org/www-chapter-london/assets/slides/OWASPLondon20171130_Cookie_Security_Myths_Misconceptions_David_Johansson.pdf).
You may also refer to the [Cookie Security Guide](https://owasp.org/www-chapter-london/assets/slides/OWASPLondon20171130_Cookie_Security_Myths_Misconceptions_David_Johansson.pdf).

---
In Symfony, sessions are managed by the framework itself and rely on Symfony's session handling mechanisms rather than PHP's default session handling via the `session.auto_start = 1` directive in the php.ini file.
Expand All @@ -473,9 +473,9 @@ The `session.auto_start = 1` directive in PHP is used to automatically start a s

- **Providers**

Symfony authentication relies on providers to fetch user information from various storages such as databases, LDAP, or custom sources. Providers get users based on the defined propety and load the corresponding user object.
Symfony authentication relies on providers to fetch user information from various storage types such as databases, LDAP, or custom sources. Providers get users based on the defined property and load the corresponding user object.

In below example [Entity User Provider](https://symfony.com/doc/current/security/user_providers.html#security-entity-user-provider) is presented which uses Doctrine to fetch user by unique identifier.
In the example below [Entity User Provider](https://symfony.com/doc/current/security/user_providers.html#security-entity-user-provider) is presented which uses Doctrine to fetch user by unique identifier.

```yaml
providers:
Expand All @@ -487,7 +487,7 @@ The `session.auto_start = 1` directive in PHP is used to automatically start a s

- **Firewalls**

Symfony use firewalls to define security configurations for different parts of an application. Each firewall define a specific set of rules and actions for incoming requests. They protect different sections of the application by specifying which routes or URLs are secured, the authentication mechanisms to use, and how to handle unauthorized access. A firewall can be associated with specific patterns, request methods, access controls, and authentication providers.
Symfony uses firewalls to define security configurations for different parts of an application. Each firewall defines a specific set of rules and actions for incoming requests. They protect different sections of the application by specifying which routes or URLs are secured, the authentication mechanisms to use, and how to handle unauthorized access. A firewall can be associated with specific patterns, request methods, access controls, and authentication providers.

```yaml
firewalls:
Expand Down Expand Up @@ -519,18 +519,18 @@ The `session.auto_start = 1` directive in PHP is used to automatically start a s

### Error Handling Disclosure

Symfony has a robust error handling system. By default, Symfony applications are configured to display detailed error messages only in the development environment for security reasons. In the production environment, a generic error page is shown. Symfony's error handling system also allows to customize error pages based on different HTTP status codes, providing a seamless and branded user experience. Additionally, Symfony logs detailed error information, aiding developers in identifying and resolving issues efficiently.
Symfony has a robust error-handling system. By default, Symfony applications are configured to display detailed error messages only in the development environment for security reasons. In the production environment, a generic error page is shown. Symfony's error handling system also allows customized error pages based on different HTTP status codes, providing a seamless and branded user experience. Additionally, Symfony logs detailed error information, aiding developers in identifying and resolving issues efficiently.

For more information about error handling unrelated to Symfony refer to [Error Handling Cheat Sheet](Error_Handling_Cheat_Sheet.md).

### Sensitive data

In Symfony the best way for storing configurations like API keys, etc., is through the use of environment variable, which are dependent on the application's location.
In Symfony, the best way to store configurations like API keys, etc., is through the use of environment variables, which are dependent on the application's location.
To ensure the security of sensitive values, Symfony provides a *secrets management system* in which values are additionally encoded using cryptographic keys and stored as **secrets**.

Consider an example where an API_KEY is stored as secret:
Consider an example where an API_KEY is stored as a secret:

To generate a pair of cryptographic keys you can run the following command. The private key file is highly sensitive and it shouldn't be committed in repository.
To generate a pair of cryptographic keys you can run the following command. The private key file is highly sensitive and it shouldn't be committed in a repository.

```bash
bin/console secrets:generate-keys
Expand All @@ -543,7 +543,7 @@ bin/console secret:set API_KEY
```

You can access secret values in your code in the same manner as environment variables.
It's very important to note that if there are environment variables and secrets with identical names, **the values from environment variables will always will override secrets**.
It's very important to note that if there are environment variables and secrets with identical names, **the values from environment variables will always override secrets**.

For more details refer to [Symfony Secrets Documentation](https://symfony.com/doc/current/configuration/secrets.html).

Expand All @@ -555,15 +555,15 @@ For more details refer to [Symfony Secrets Documentation](https://symfony.com/do
APP_ENV=prod
```

- Make sure your PHP configuration is secure. You may refer the [PHP Configuration Cheat Sheet](PHP_Configuration_Cheat_Sheet.md) for more information on secure PHP configuration settings.
- Make sure your PHP configuration is secure. You may refer to the [PHP Configuration Cheat Sheet](PHP_Configuration_Cheat_Sheet.md) for more information on secure PHP configuration settings.

- Ensure that the SSL certificate is properly configured in your web server and configure it to enforce HTTPS by redirecting HTTP traffic to HTTPS.

- Implement security headers to enhance the security posture of your application.

- Ensure that file and directory permissions are set correctly to minimize security risks.

- Implement regular backups of your production database and critical files. Have a recovery plan in place to quickly restore your application in case of any issue.
- Implement regular backups of your production database and critical files. Have a recovery plan in place to quickly restore your application in case of any issues.

- Use security checkers to scan your dependencies to identify known vulnerabilities.

Expand Down

0 comments on commit f650787

Please sign in to comment.