Coder Social home page Coder Social logo

github / secure_headers Goto Github PK

View Code? Open in Web Editor NEW
3.1K 176.0 253.0 1.59 MB

Manages application of security headers with many safe defaults

License: MIT License

Ruby 100.00%
secure-headers csp hsts referrer-policy rack middleware xframe-options ruby cookie content-security-policy

secure_headers's Introduction

Secure Headers Build + Test

main branch represents 6.x line. See the upgrading to 4.x doc, upgrading to 5.x doc, or upgrading to 6.x doc for instructions on how to upgrade. Bug fixes should go in the 5.x branch for now.

The gem will automatically apply several headers that are related to security. This includes:

It can also mark all http cookies with the Secure, HttpOnly and SameSite attributes. This is on default but can be turned off by using config.cookies = SecureHeaders::OPT_OUT.

secure_headers is a library with a global config, per request overrides, and rack middleware that enables you customize your application settings.

Documentation

Configuration

If you do not supply a default configuration, exceptions will be raised. If you would like to use a default configuration (which is fairly locked down), just call SecureHeaders::Configuration.default without any arguments or block.

All nil values will fallback to their default values. SecureHeaders::OPT_OUT will disable the header entirely.

Word of caution: The following is not a default configuration per se. It serves as a sample implementation of the configuration. You should read more about these headers and determine what is appropriate for your requirements.

SecureHeaders::Configuration.default do |config|
  config.cookies = {
    secure: true, # mark all cookies as "Secure"
    httponly: true, # mark all cookies as "HttpOnly"
    samesite: {
      lax: true # mark all cookies as SameSite=lax
    }
  }
  # Add "; preload" and submit the site to hstspreload.org for best protection.
  config.hsts = "max-age=#{1.week.to_i}"
  config.x_frame_options = "DENY"
  config.x_content_type_options = "nosniff"
  config.x_xss_protection = "1; mode=block"
  config.x_download_options = "noopen"
  config.x_permitted_cross_domain_policies = "none"
  config.referrer_policy = %w(origin-when-cross-origin strict-origin-when-cross-origin)
  config.csp = {
    # "meta" values. these will shape the header, but the values are not included in the header.
    preserve_schemes: true, # default: false. Schemes are removed from host sources to save bytes and discourage mixed content.
    disable_nonce_backwards_compatibility: true, # default: false. If false, `unsafe-inline` will be added automatically when using nonces. If true, it won't. See #403 for why you'd want this.

    # directive values: these values will directly translate into source directives
    default_src: %w('none'),
    base_uri: %w('self'),
    child_src: %w('self'), # if child-src isn't supported, the value for frame-src will be set.
    connect_src: %w(wss:),
    font_src: %w('self' data:),
    form_action: %w('self' github.com),
    frame_ancestors: %w('none'),
    img_src: %w(mycdn.com data:),
    manifest_src: %w('self'),
    media_src: %w(utoob.com),
    object_src: %w('self'),
    sandbox: true, # true and [] will set a maximally restrictive setting
    plugin_types: %w(application/x-shockwave-flash),
    script_src: %w('self'),
    script_src_elem: %w('self'),
    script_src_attr: %w('self'),
    style_src: %w('unsafe-inline'),
    style_src_elem: %w('unsafe-inline'),
    style_src_attr: %w('unsafe-inline'),
    worker_src: %w('self'),
    upgrade_insecure_requests: true, # see https://www.w3.org/TR/upgrade-insecure-requests/
    report_uri: %w(https://report-uri.io/example-csp)
  }
  # This is available only from 3.5.0; use the `report_only: true` setting for 3.4.1 and below.
  config.csp_report_only = config.csp.merge({
    img_src: %w(somewhereelse.com),
    report_uri: %w(https://report-uri.io/example-csp-report-only)
  })
end

Deprecated Configuration Values

Default values

All headers except for PublicKeyPins and ClearSiteData have a default value. The default set of headers is:

Content-Security-Policy: default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
Strict-Transport-Security: max-age=631138519
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Frame-Options: sameorigin
X-Permitted-Cross-Domain-Policies: none
X-Xss-Protection: 1; mode=block

API configurations

Which headers you decide to use for API responses is entirely a personal choice. Things like X-Frame-Options seem to have no place in an API response and would be wasting bytes. While this is true, browsers can do funky things with non-html responses. At the minimum, we suggest CSP:

SecureHeaders::Configuration.override(:api) do |config|
  config.csp = { default_src: 'none' }
  config.hsts = SecureHeaders::OPT_OUT
  config.x_frame_options = SecureHeaders::OPT_OUT
  config.x_content_type_options = SecureHeaders::OPT_OUT
  config.x_xss_protection = SecureHeaders::OPT_OUT
  config.x_permitted_cross_domain_policies = SecureHeaders::OPT_OUT
end

However, I would consider these headers anyways depending on your load and bandwidth requirements.

Acknowledgements

This project originated within the Security team at Twitter. An archived fork from the point of transition is here: https://github.com/twitter-archive/secure_headers.

Contributors include:

  • Neil Matatall @oreoshake
  • Chris Aniszczyk
  • Artur Dryomov
  • Bjørn Mæland
  • Arthur Chiu
  • Jonathan Viney
  • Jeffrey Horn
  • David Collazo
  • Brendon Murphy
  • William Makley
  • Reed Loden
  • Noah Kantrowitz
  • Wyatt Anderson
  • Salimane Adjao Moustapha
  • Francois Chagnon
  • Jeff Hodges
  • Ian Melven
  • Darío Javier Cravero
  • Logan Hasson
  • Raul E Rangel
  • Steve Agalloco
  • Nate Collings
  • Josh Kalderimis
  • Alex Kwiatkowski
  • Julich Mera
  • Jesse Storimer
  • Tom Daniels
  • Kolja Dummann
  • Jean-Philippe Doyle
  • Blake Hitchcock
  • vanderhoorn
  • orthographic-pedant
  • Narsimham Chelluri

If you've made a contribution and see your name missing from the list, make a PR and add it!

Similar libraries

secure_headers's People

Contributors

anglinb avatar bemurphy avatar caniszczyk avatar carlosantoniodasilva avatar ggalmazor avatar ghiculescu avatar jackmc avatar jacobbednarz avatar jmera avatar keithamus avatar koenpunt avatar kyfast avatar lalithr95 avatar lgarron avatar mastahyeti avatar mnoack avatar naiyt avatar nchelluri avatar oreoshake avatar paulfri avatar petergoldstein avatar ptoomey3 avatar rcaught avatar reedloden avatar srisa avatar stefansundin avatar stve avatar theverything avatar vcsjones avatar xssc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

secure_headers's Issues

CSP reports from Chrome not parsed correctly

Problem:
Chrome sets the mime type application/csp-report and this prevents the ActionDispatch::ParamsParser middleware from parsing the post body and merging it into the params array. This means that using a forward_endpoint will not work since the forwarded params array will be empty.

Solution:

ActionDispatch::ParamsParser::DEFAULT_PARSERS["application/csp-report"] = :json

Add support for X-Permitted-Cross-Domain-Policies

HTTP header used for informing Adobe products as to how to handle cross domain policies.

https://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/xdomain.html

https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html

Specifies the meta-policy. The default value is master-only for all policy files except socket policy files, where the default is all. Allowed values are:

  • none: No policy files are allowed anywhere on the target server, including this master policy file.
  • master-only: Only this master policy file is allowed.
  • by-content-type: [HTTP/HTTPS only] Only policy files served with Content-Type: text/x-cross-domain-policy are allowed.
  • by-ftp-filename: [FTP only] Only policy files whose file names are crossdomain.xml (i.e. URLs ending in /crossdomain.xml) are allowed.
  • all: All policy files on this target domain are allowed.

CSP headers are sent to Safari 5 again

Issue #55 seems to have gotten undone somehow from secure_headers 0.4.3 to 0.5.0. CSP headers are sent to Safari 5.1 (7534.48.3) when I use 0.5.0 but not if I switch back to 0.4.3.

/content_security_policy/forward_report 404s, when consider_all_requests_local = false

A browser detecting a CSP violation tries to post that violation to the secure_headers CSP end point on our server (ie. /content_security_policy/forward_report), but it 404s on that endpoint when in a non-development environment.

We did however, notice that setting consider_all_requests_local = true in the settings for that non-development environment would enable that end-point and allow the browser to post the violations to the server, but of course we don't want that as our production environment solution.

So is anyone else seeing this behaviour?

FYI, we're using:

  • rails: 3.2.15
  • secure_headers: 1.0.0

Also:

> RAILS_ENV=staging bundle exec rake routes |grep content_security_policy
  content_security_policy_forward_report POST   /content_security_policy/forward_report(.:format)                                     content_security_policy#scribe

> echo "Rails.application.routes.recognize_path('/content_security_policy/forward_report')" | RAILS_ENV=staging bundle exec rails c
Loading staging environment (Rails 3.2.15)
Switch to inspect mode.
Rails.application.routes.recognize_path('/content_security_policy/forward_report')
{:controller=>"application", :action=>"render_error_404", :not_found=>"content_security_policy/forward_report"}

Implement cross browser automated testing

Test to ensure CSP policy enforcement is working as expected.

default-src 'self'; 

Try to load an image, stylesheet, etc

This will also work as a test that will signal when Firefox has fixed the inline style CSP bug (add bugzilla reference)

Add before filter to set all headers, option to `ensure_security_headers`

There have been a few cases where this unnecessary abstraction caused confusion. It's a before_filter and that should be the main interface, or at least an option.

before_filter :set_all_security_headers
skip_before_filter :set_csp_header if crazy_stuff?
skip_before_filter :set_x_frame_options_header if stuff_needs_to_be_framed?

Heroku error

Hi!
I've added secureheaders to an app I'm developing, and while it works fine in my development environment, when I deploy it to heroku I get this error:

Error Message:
SecureHeaders::STSBuildError: max-age must be a number. 99 was supplied.

Where:
devise/sessions#new
[PROJECT_ROOT]/vendor/bundle/ruby/1.9.1/gems/secure_headers-0.3.0/lib/secure_headers/headers/strict_transport_security.rb, line 45

Any ideas of what is happening?

Thanks in advance!

With csp: false, an img-src directive is being added

Hi,
setting csp: false while configuring ensure_security_headers results in having "img-src chrome-extension" in the X-WebKit-CSP-Report-Only header on Chrome.
Which produce warnings in the console when loading any image from elsewhere than chrome extensions.
I think -but I may be wrong- that this is not the intended effect when setting csp to false.
what do you think?
cheers
Vincent

Remove forwarder code

The csp forwarder has multiple issues and has been annoying to maintain. Fork it out into a separate gem and let it go it's own direction

Don`t add FF_CSP_ENDPOINT route when forwarding is not defined

Currently a route to content_security_policy#scribe is always added, even in cases when forwarding is not set up. Instead of NOOP

  def scribe
    csp = ::SecureHeaders::Configuration.csp || {}

    forward_endpoint = csp[:forward_endpoint]
    if forward_endpoint
      forward_params_to(forward_endpoint)
    end

    head :ok

can the route not be installed in the first place ?

Sinatra support/usage?

I'm sorry if this is straight forward, but I can't seem to get this to work under Sinatra.

uninitialized constant SecureHeaders (NameError)

I created an initializer following the suggestion in the readme. However when I start the rails server, I get:
/config/initializers/secure_headers.rb:1:in `<top (required)>': uninitialized constant SecureHeaders (NameError)

Drop all UA sniffing

Given that the plan is to only support the standard CSP header in #73, the only other piece that uses UA sniffing is the X-Content-Type-Options support. It's probably fine to send this to safari/firefox/other as well. This would close #72

Allow CSP headers to be built w/o a request object

Currently there is UA sniffing and SSL detection, but this should also be allowed to be provided as options. This allows pre-configured headers for the various scenarios so they aren't generated per request.

Add default csp report endpoint

Most people will want to do something pretty custom with their reports. Some will log directly to a public endpoint. Some will implement and endpoint and send it to various sources. A question on stackoverflow got me thinking about this.

However, there should be something built in to do some basic aggregation/display with no effort. A few ideas:

  • Store in db, create UI for viewing/visualizing, perhaps with search (requires extra config/infra). Should this be restricted to Rails.env.development?
  • Log to separate log file in human readable format
  • Serialize to JSON for use with other visualization tools
  • Hook into growl/browser if violations are unexpected? (tangental)

With a UI, it would be nice to have:

  • Policy validator (should this be built into config initialization?)
  • Policy adjustment suggestions (restrict/loosen, redundant)
  • Indication that inline script, eval script, mixed-content, etc are allowed. With the goal to eliminate all issues.

Supporting this could actually add functionality useful in a prod scenario

  • Add a value to the config file that takes a block and yields the JSON hash
  • Specify a class name that implements csp_report (essentially no different from a custom endpoint implementation, but pluggable)

I don't think it's wise to try and build something production-ready. And of course, this should involve no code changes other than a configuration tweak.

Secure_headers gem takes over 1 second to load

I'm working to get our rails boot time down, as we've been running into issues where the app's boot time exceeds the 60 seconds allowed for by Heroku. In doing this, I've noticed that secure_headers is the slowest loading gem by a large margin. Using bumbler, I tracked down the five slowest gems to these:

 427.33  rocket_pants
 632.43  rails
 651.41  delayed_job
 959.41  newrelic_rpm
1439.04  secure_headers

I've fixed our boot time and am moving on, but I thought I'd let you know how slow the gem takes to load; it would be great to speed it up some how.

Support procs as config values

A use case came up where I had to jank around the need for the report-uri to be determined per request. The API supports this but the recommended config requires adding some jank to emulate this.

This seems like a good use case to accept anything that is callable for a config value, at least for CSP.

Support sending the X-Content-Type-Options header for Chrome extension installs

While IE has special handling of the X-Content-Type-Options header for the general "don't ignore the content-type and try to sniff", Chrome also respects the header but for a very specific use case.

http://developer.chrome.com/extensions/hosting.html

A server that hosts .crx files must use appropriate HTTP headers, so that users can install the file by clicking a link to it.

Google Chrome considers a file to be installable if either of the following is true:

  • The file has the content type application/x-chrome-extension
  • The file suffix is .crx and both of the following are true:
    • The file is not served with the HTTP header X-Content-Type-Options: nosniff
    • The file is served with one of the following content types:
      • empty string
      • "text/plain"
      • "application/octet-stream"
      • "unknown/unknown"
      • "application/unknown"
      • "/"

Would be awesome if this gem supported that specific case somehow...

The StrictTransportSecurity header is raising a TypeError when max_age is a Fixnum

I am seeing the following error:

TypeError: can't convert Fixnum into String

From: [GEM_ROOT]/gems/secure_headers-0.4.1/lib/secure_headers/headers/strict_transport_security.rb, line 32

With the following configuration:

::SecureHeaders::Configuration.configure do |config|
  config.hsts = {:max_age => 99, :include_subdomains => true}
  config.x_frame_options = 'DENY'
  config.x_content_type_options = "nosniff"
  config.x_xss_protection = {:value => 1, :mode => 'block'}
  config.csp = false
end

Support separate report_uris for public and forwarded requests

In the case of doing firefox forwarding, you may have to send the report to a host that does not match the report_uri. In this case, we need to support two separate report_uris.

Consider just using forward_endpoint and don't allow the override of the endpoint? That seems to be what people think forward_endpoint is anyways.

Clear Rails 4 default headers

Was tweaking a policy for a rails 4 site to NOT apply some of the X headers, but naturally they were applied due to the new default headers feature.

It seems using secure_headers means you don't want to use the built-in feature.

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.