Git Product home page Git Product logo

nelmiosecuritybundle's Issues

Provide console command to review security settings

The console command should inspect the current security settings and give hints which settings should also be enabled.

  • report missing CSP directives (neither enforced nor reported)
  • report other missing security features like Clickjacking Protection, Forced HTTPS/SSL Handling

Such a reporting might be especially useful if new CSP versions add new directives or if entirely new security mechanisms are added to this bundle.

Public-Key-Pins

Hello,

Is there a way to set-up the Public-Key-Pins header?
I cannot see it reading the docs at README.md file.

Thanks!

Cannot find the "nelmio_security.csp_reporter_controller" controller.

I keep getting the following error in my symfony "prod.log" log file, but not the "dev.log" log file:

request.CRITICAL: Uncaught PHP Exception Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: "You have requested a non-existent service "nelmio_security.csp_reporter_controller"."

[Question] Deprecate PHP 5.3

PHP 5.3 is not maintained, what about dropping support to this version to avoid writing compatible code ?

ie : $that injection

Can't install in "symfony/symfony": "2.8.*"

Hello, I had tried to install the Bundle in symfony 2.8.X, it failed.

composer require nelmio/NelmioSecurityBundle
You are running composer with xdebug enabled. This has a major impact on runtime
 performance. See https://getcomposer.org/xdebug


  [InvalidArgumentException]
  Could not find package nelmio/NelmioSecurityBundle at any version for your
  minimum-stability (stable). Check the package spelling or your minimum-stab
  ility


require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-update]
[--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--sort-
packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--] [<packag
es>]...

Unrecognized option "referrer_policy"

I can't figure it out why it doesn't work

[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]  
  Unrecognized option "referrer_policy" under "nelmio_security"

[Symfony3] Wrong with log external Redirect

I want to log all external redirect, so I set configure:

// security.yml
nelmio_security:
    external_redirects:
        log: true
        abort: true

Problem:

ContextErrorException in ExternalRedirectListener.php line 39: Catchable Fatal Error: Argument 5 passed to Nelmio\SecurityBundle\EventListener\ExternalRedirectListener::__construct() must be an instance of Symfony\Component\HttpKernel\Log\LoggerInterface, instance of Symfony\Bridge\Monolog\Logger given, called in /vagrant/generic/var/cache/dev/appDevDebugProjectContainer.php on line 2131 and defined

Reason:

The `Symfony\Component\HttpKernel\Log\LoggerInterface` has been removed in favor of `Psr\Log\LoggerInterface`

So I think we need update file: ExternalRedirectListener.php, remove Symfony\Component\HttpKernel\Log\LoggerInterface and update with Psr\Log\LoggerInterface

Release 2.0

Hello,

I'm thinking about releasing 2.0 very soon. Does anything miss, does anything needs more work before releasing?

Please comment :)

Unrecognized options

I get this error trying to run cache:clear

php bin/console cache:clear

[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized options "level1_fallback, browser_adaptive, block-all-mixed-content" under "nelmio_security.csp.enforce"

Symfony version: 3.0.6
NelmioSecurityBundle version: 1.10.0

Config file:

nelmio_security:
    # prevents framing of the entire site
    clickjacking:
        paths:
            '^/.*': DENY
    # disables content type sniffing for script resources
    content_type:
        nosniff: true

    # Forces Microsoft's XSS-Protection with
    # its block mode
    xss_protection:
        enabled: true
        mode_block: true
    csp:
        #report_logger_service: logger
        hosts: []
        content_types: []
        enforce:
            # see full description below
            level1_fallback: true
            # Only send directives supported by the browser, defaults to false
            # This is a port of https://github.com/twitter/secureheaders/blob/83a564a235c8be1a8a3901373dbc769da32f6ed7/lib/secure_headers/headers/policy_management.rb#L97
            browser_adaptive: false
            report-uri: ['/nelmio/csp/report']
            default-src: [ 'self' ]
            #frame-src: [ 'https://www.youtube.com' ]
            script-src:
                - 'self'
                - maps.googlemaps.com
            img-src:
                - 'self'
                - maps.googlemaps.com
            block-all-mixed-content: false # Default to false, blocks http content over https transport

Is it a config problem?

make the log message for reported CSP violations configurable

With CSP I can define different report-uri's for enforced and for reported CSP policies. It would make sense to also have different log messages (and log levels) for these two.

Normally I should test my CSP policies before I switch them to be enforced. However I could miss something. In that case I'd like to have an alert that I need to change my policy imediately.

This can be easily implemented by defining the same report controller two times with different arguments and make the message and log level configurable with constructor parameters.

Change behavior of Clickjacking Listener

I would like to discuss changing the behavior of Clickjacking Listener to let multiple rules set the header instead of stopping after the first match.

The current implementation returns after the first match: https://github.com/nelmio/NelmioSecurityBundle/blob/master/EventListener/ClickjackingListener.php#L51

This makes this kind of configuration impossible:

# bundle.yml - default deny everything
nelmio_security:
    clickjacking:
        paths:
            '^/.*': DENY
# config.yml - override one path for this app
imports:
    - { resource: "@Bundle/Resources/config/bundle.yml" }

nelmio_security:
    clickjacking:
        paths:
            '^/files/': SAMEORIGIN

Would this change even make sense? It would possible be a BC change so might have to wait for next major version.

FlexibleSSL on remember me cookie not redirecting to https

A site uses flexible SSL for logged users. Index page you can access with both http and https.
On logging to the site with remember me flag to cookies are set:

  • REMEMBER_ME with 1 year expire
  • auth with 1 year expire

The auth cookie's expiration length is set on EventListener/FlexibleSslListener.php by finding the longest all cookies expiration from the Response.

The problem ocurs when after closing the browser (deleting session cookie) trying access http index. On redirect (because found auth cookie with value '1') the cookie auth is reseted again with expiration 0 (till session end), because it cannot be calculate from an empty cookies array in the Response.

# app/config/config.yml
nelmio_security:
    flexible_ssl:
        cookie_name: auth
        unsecured_logout: false

security:
    firewalls:
       main:
            remember_me:
                secure: true
                key: secret_key
                name: REMEMBER_ME
                lifetime: 31536000
                always_remember_me: true
                remember_me_parameter: _remember_me
// EventListener/FlexibleSslListener.php

    public function onPostLoginKernelResponse(FilterResponseEvent $e)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $e->getRequestType()) {
            return;
        }

        $response = $e->getResponse();

        $longestExpire = 0;
        foreach ($response->headers->getCookies() as $cookie) {
            // find longest expiration time
            $longestExpire = max($longestExpire, $cookie->getExpiresTime());
            if (!$cookie->isSecure()) {
                // force existing cookies (remember-me most likely) to be secure
                $response->headers->setCookie(new Cookie(
                    $cookie->getName(),
                    $cookie->getValue(),
                    $cookie->getExpiresTime(),
                    $cookie->getPath(),
                    $cookie->getDomain(),
                    true,
                    $cookie->isHttpOnly()
                ));
            }
        }

        // set the auth cookie
        $response->headers->setCookie(new Cookie(
            $this->cookieName,
            '1',
            $longestExpire,
            '/',
            null,
            false,
            false
        ));

        // force session cookie to be secure
        $params = session_get_cookie_params();
        $response->headers->setCookie(new Cookie(
            session_name(),
            session_id(),
            0,
            $params['path'],
            $params['domain'],
            true,
            $params['httponly']
        ));
    }

A possible solution could be to set auth cookie when no auth cookie exists on the Request.

if (null === $e->getRequest()->cookies->get($this->cookieName)) {
    // set the auth cookie
    $response->headers->setCookie(new Cookie(
        $this->cookieName,
        '1',
        $longestExpire,
        '/',
        null,
        false,
        false
    ));
}

What do you think guys?

Is it an error in config?

  [Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]   
  Unrecognized options "hosts, content_types" under "nelmio_security.csp.report"

I'm using the default configuration. Whenever I'm clearing symfony app's cache, I find this error.

forced_ssl vs access control?

What is the difference between using this bundle's forced_ssl option and:

security:
    access_control:
        - { path: ^/, requires_channel: https }

?

[CSP] Allow nonce passed through header (to support Turbolinks/PJAX)

We are running a Symfony2 application with Turbolinks and want to use CSP. When we use the csp_nonce() method to generate a nonce, it will be different for every request. But since we use Turbolinks, navigating to other pages will just load the new HTML through AJAX and embed it in the current document. When a new page includes a <script> or <style> tag it will be blocked.

So I was thinking about the following solution:

In ContentSecurityPolicyListener:

    public function onKernelRequest(GetResponseEvent $event)
    {
        // ..

        if ($event->getRequest()->headers->has('X-CSP-Nonce')) {
            // @todo maybe add some regex validation
            $this->nonce = $event->getRequest()->headers->get('X-CSP-Nonce');
        }
    }

Then in my HTML I set this:

<meta name="csp_nonce" content="{{ csp_nonce() }}">

And in my app.js I set something like this:

    $.ajaxSetup({
        headers: {
            'X-CSP-NONCE': document.querySelector('meta[name="csp_nonce"]').getAttribute('content'),
        }
    })

This works, but what about security? Am I going to do something really stupid/bad?

HTTP_X_FORWARDED_PROTO not handling at all

I 'm currently using AWS and my hosts SSL handling done by AWS. So when I use forced_ssl, ForcedSslListener simply does redirect loop to same domain which is not expected. Can you add a proper handling for that?

Add Whiltelisted URL's to forced_ssl Configuration

Sometimes there are cases when you want to use SSL across the board except for a few specific URL's. We'd like to be able to use forced_ssl but when certain URL's are requested we want to ignore "forced ssl" and continue on to http/non-secure.

Version 2.2.0 without ua-parser/uap-php

composer.json defines ua-parser/uap-php as a dev-dependency. Since version 2.2.0 (commit #815b5d762ae26db93195abc3c7cc1a9f09f75ee7) NelmioSecurityBundle doesn't work out of the box any more with the default configuration.

This happens because the new configuration setting

nelmio_security:
    csp:
        report_endpoint:
            filters:
                browser_bugs: true # default

requires the ua-parser/uap-php library to be installed. That's somehow inconsistent as the other setting that relies on the ua-parser/uap-php library

nelmio_security:
    csp:
        report/enforce:
            browser_adaptive:
                enabled: false # default

is disabled by default. The solution could be to

  1. disable the browser_bugs filter by default
  2. make the default setting for browser_bugs dependant on the availability of ua-parser/uap-php
  3. require the ua-parser/uap-php library in composer.json

Does this make any sense?

Exclude NelmioSecurityBundle from API routes

Is there a possibility now or could it be added to exclude adding NelmioSecurityBundle info on response to API calls? For instance don't add no-sniff and other stuff to responses generate for ^/api?

please make it possible to report and enforce policies

https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy#Testing_your_policy

It is possible to have some policies enforced and others only reported. It might even be possible to enforce policies and still have them reported (need to test this/read the spec).

In the config however I can only choose to enforce or report all policies. This is a problem for legacy applications where you need to test every policy over a longer time until you can be sure to enforce it without breaking anything.

Request hasPreviousSession and Cookie Session Handler

I configured my app to use Cookie Session Handler and discovered that authentication started breaking. I kept getting "Your session has timed out, or you have disabled cookies.". I traced this issue down to AbstractAuthenticationListener and then to the hasPreviousSession method of Request. I discovered that if I add:

framework:
    session:
        name: session

...the problem disappears. But doing this means that the browser is receiving two cookies named "session". The browser seems to be using the last Set-Cookie: session= when it picks which of the two to send back.

I am wondering if this is how this session handler is meant to be used, or if there is some extra configuration that needs to be done.

Listeners priorities exceeds maximum value

I was working on a debug method for the console to check which listeners and subscribers are available. I also included the priorities of the services and I saw that this bundle had priorities that were set way beyond the maximum or minimum values defined by the Symfony docs.

Quote from: http://symfony.com/doc/current/cookbook/service_container/event_listener.html

There is an additional tag option priority that is optional and defaults to 0. This value
can be from -255 to 255, and the listeners will be executed in the order of their priority 
(highest to lowest). This is useful when you need to guarantee that one listener is 
executed before another.

Is there a reason why the priorities are set so high, because a priority of 10.000 seems exorbitant.

Disable cookie encryption?

I don't want to encrypt my cookies, so I set my config to look like this:

nelmio_security:
    encrypted_cookie:
        names: []

But I get this error:
RuntimeException in Encrypter.php line 27: You need to install mcrypt if you want to encrypt your cookies.

Can I completely disable cookie encryption so that I don't have to install mcrypt?

CookieSessionHandler and PHP7

I'm using Symfony 3 with an PHP7. When using the CookieSessionHandler with signed cookies and no active session I'm getting following error.

Error: session_start(): Failed to initialize storage module: user (path: )

in var/cache/dev/classes.php at line 112

if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
}
if (!session_start()) {
throw new \RuntimeException('Failed to start the session');
}
$this->loadSession();

The issue seems to be caused by CookieSesisonHandler::open(). See also SO-34125849.

As a workaround I just changed the code to this:

// $this->request->cookies->has($this->cookieName);
return true;

Report URI not working in other environments than PROD

Hello,

I'm facing an issue when I try to use the report feature of the bundle in the DEV environment: the blocked content generate an uri without the app_dev.php prefix.

I'm using Symfony 3.1.0 with the 2.0.0 version of the bundle.

routing.yml:

# NelmioSecurityBundle
nelmio_security:
    path:     /csp/report
    defaults: { _controller: nelmio_security.csp_reporter_controller:indexAction }
    methods:  [POST]

config.yml:

nelmio_security:
    csp:
        enforce:
            # see full description below
            level1_fallback: true
            # Only send directives supported by the browser, defaults to false
            # This is a port of https://github.com/twitter/secureheaders/blob/83a564a235c8be1a8a3901373dbc769da32f6ed7/lib/secure_headers/headers/policy_management.rb#L97
            browser_adaptive: false
            report-uri: /csp/report
            connect-src:
                - 'self'
                - 'api.mapbox.com'
                - '*.tiles.mapbox.com'
            default-src:
                - 'self'
            font-src:
                - 'self'
                - 'fonts.gstatic.com'
            img-src:
                - 'self'
                - 'data:' # Allows data: URIs to be used as a content source (@see https://developer.mozilla.org/fr/docs/Web/Security/CSP/CSP_policy_directives#Data) 
                - '*.tiles.mapbox.com'
            script-src:
                - 'self'
                - 'www.google-analytics.com'
                - 'api.tiles.mapbox.com'
            style-src:
                - 'self'
                - 'unsafe-inline' # Because of the FancyBox Javascript library
                - 'fonts.googleapis.com'
                - 'api.tiles.mapbox.com'
            block-all-mixed-content: true # Default to false, blocks http content over https transport
            # upgrade-insecure-requests: true # Default to false, upgrades http requests to https transport
        report:
            # see full description below
            level1_fallback: true
            # Only send directives supported by the browser, defaults to false
            # This is a port of https://github.com/twitter/secureheaders/blob/83a564a235c8be1a8a3901373dbc769da32f6ed7/lib/secure_headers/headers/policy_management.rb#L97
            browser_adaptive: false
            report-uri: /csp/report
            script-src:
                - 'self'

Csp impssible with twig 2.0

Requirements of "nelmio/security-bundle": "^2.1" allow the bundle to be installed with "twig/twig": "^2.1". Unfortunately, NelmioSecurityBundle seems not yet to be ready to be used with twig 2.x.

As soon as I add the following to my configuration

nelmio_security:
    csp:
        enabled: true

and access a page which has {% cspscript %}<script>//...</script>{% endcspscript %} code fragment in it, the following exception is thrown: Type error: Argument 1 passed to Nelmio\SecurityBundle\Twig\Node\CSPNode::__construct() must be an instance of Twig_NodeInterface, instance of Twig_Node given, called in .../vendor/nelmio/security-bundle/Twig/TokenParser/AbstractCSPParser.php on line 43

A quick look in the related classes proved that transmitted CSPNode extends \Twig_Node. While in twig 1.6 Twig_Node implements Twig_NodeInterface as expected, in twig 2.0 Twig_Node implements Countable, IteratorAggregate only.

I have no idea why this changed in twig 2.0, possibly this is a bug in twig instead of nelmio/NelmioSecurityBundle. If not, nelmio/NelmioSecurityBundle should correct the requirements to not use twig 2.0.

CSS and JS files aren't load by the twig templates

Hello,

I'm new with this bundle, it's the first time I use it. Iupload and install it in my project -Symfony 3.2- and after installing the config.yml, l lost the link with my assets(CSS, JS, IMG...).

What happened ? Here my config:

`nelmio_security:
# signs/verifies all cookies
signed_cookie:
names: ['']
# prevents framing of the entire site
clickjacking:
paths:
'^/.
': DENY
# prevents redirections outside the website's domain
external_redirects:
abort: true
log: true

# prevents inline scripts, unsafe eval, external scripts/images/styles/frames, etc
csp:
    hosts: []
    content_types: []
    enforce:
        level1_fallback: false
        browser_adaptive:
            enabled: false
        report-uri: %router.request_context.base_url%/nelmio/csp/report
        default-src:
            - 'none'
        script-src:
            - 'self'
        block-all-mixed-content: true # defaults to false, blocks HTTP content over HTTPS transport
        # upgrade-insecure-requests: true # defaults to false, upgrades HTTP requests to HTTPS transport

# disables content type sniffing for script resources
content_type:
    nosniff: false

# forces Microsoft's XSS-Protection with
# its block mode
xss_protection:
    enabled: true
    mode_block: true

# Send a full URL in the `Referer` header when performing a same-origin request,
# only send the origin of the document to secure destination (HTTPS->HTTPS),
# and send no header to a less secure destination (HTTPS->HTTP).
# If `strict-origin-when-cross-origin` is not supported, use `no-referrer` policy,
# no referrer information is sent along with requests.
referrer_policy:
    enabled: true
    policies:
        - 'no-referrer'
        - 'strict-origin-when-cross-origin'

`

Content security policy blocks everything on iOS Safari v5.1.1

I have my content security policy set as follows:

nelmio_security:
   # prevents framing of the entire site
    clickjacking:
        paths:
            '^/.*': DENY
    # prevents redirections outside the website's domain
    external_redirects:
        log: true
        override: homepage

    # prevents inline scripts, unsafe eval, external scripts/images/styles/frames, etc
    csp:
        report_uri: /nelmio/csp/report
        report_only: false
        default: [ self ]
        frame: [ 'https://www.youtube.com' ]
        script:
            - self
            - 'https://www.google-analytics.com'
            - 'http://www.google-analytics.com'
        img:
            - self
            - 'https://www.google-analytics.com'
            - 'http://www.google-analytics.com'

    # disables content type sniffing for script resources
    content_type:
        nosniff: true

So, the csp setting should not be blocking scripts, css, and javascript from loading on the page. However, on my first-generation iPad, running iOS 5.1.1 (last supported version on that iPad) is not loading any of these assets due to my content security policy; this is using both Chrome and Safari.

My last resort would be disabling the content security policy for any iOS devices; is there a way to do this? However, I would like to be able to make this work across all versions of devices.

Request: Add a controller to log CSP violations

I discovered this bundle only today and it looks incredibly helpful. The biggest omission seems to be a way to log CSP violations. Would that be something you're willing to add? If so I'd be happy to write it.

support public key pinning header

Spec: http://tools.ietf.org/html/draft-ietf-websec-key-pinning-20
A simpler writeup: https://raymii.org/s/articles/HTTP_Public_Key_Pinning_Extension_HPKP.html
Mozilla's take: https://blog.mozilla.org/security/2014/09/02/public-key-pinning/

I might give it a go at implementation, but currently it only truly works in chrome, and even then, we'll need to wait for the next stable build for it to work correctly alongside HSTS due to https://code.google.com/p/chromium/issues/detail?id=444511

I'd submit a first draft at a PR, but i wonder where it should go.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.