rack-protection 1.5.5 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA256:
3
- metadata.gz: 2b7d78da301d9f7fc81ae73e46a389c2b8ce10ab8121f169fd760018ac506d47
4
- data.tar.gz: a91bd28f8624f325d6714262ac11d83e0a347405f14e600780cb1bfd846e5b34
2
+ SHA1:
3
+ metadata.gz: 82bb8eedbee01c6c9183404515dc70cc7135844d
4
+ data.tar.gz: 19f676ac801969dbc0dd7a04dbeb5dc7561c5b76
5
5
  SHA512:
6
- metadata.gz: 0c5de92c0283313c00d50c1f9a219c808ad587caabff81c4d1530abd8f0e7d9c0f3753ad9bab7c06a29ce97b2a717fddc04ced642adff058f3431419286e4da6
7
- data.tar.gz: d3bf5830bf30475871b73ba54ee38f962bd93c2e1f420b59b649d6dcb7f97d89f091d3add3f692ba847ffe5f5c6cade665d522c86220087d977fb3706e41bd58
6
+ metadata.gz: 30b9dfe62c92269b96c52fa344b5d53fe074a87366a556f1321c7b4f93466f89745f2f8d4acc5d190f316e1cef01a846a797e198e7304310bfa57c6a2f7ec99e
7
+ data.tar.gz: a1821675a3324d297c37bae3c7aa5e606e9a879ed097ec163d4148657de18efc918477b062ea176c547393830e93d56e5c3149b20e7bcee63de6dde2101da392
data/Gemfile ADDED
@@ -0,0 +1,13 @@
1
+ source "http://rubygems.org"
2
+ # encoding: utf-8
3
+
4
+ gem 'rake'
5
+
6
+ rack_version = ENV['rack'].to_s
7
+ rack_version = nil if rack_version.empty? or rack_version == 'stable'
8
+ rack_version = {:github => 'rack/rack'} if rack_version == 'master'
9
+ gem 'rack', rack_version
10
+
11
+ gem 'sinatra', path: '..'
12
+
13
+ gemspec
data/License CHANGED
@@ -1,4 +1,7 @@
1
- Copyright (c) 2011 Konstantin Haase
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2011-2017 Konstantin Haase
4
+ Copyright (c) 2015-2017 Zachary Scott
2
5
 
3
6
  Permission is hereby granted, free of charge, to any person obtaining
4
7
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -1,4 +1,4 @@
1
- You should use protection!
1
+ # Rack::Protection
2
2
 
3
3
  This gem protects against typical web attacks.
4
4
  Should work for all Rack apps, including Rails.
@@ -38,43 +38,55 @@ run MyApp
38
38
 
39
39
  Prevented by:
40
40
 
41
- * `Rack::Protection::AuthenticityToken` (not included by `use Rack::Protection`)
42
- * `Rack::Protection::FormToken` (not included by `use Rack::Protection`)
43
- * `Rack::Protection::JsonCsrf`
44
- * `Rack::Protection::RemoteReferrer` (not included by `use Rack::Protection`)
45
- * `Rack::Protection::RemoteToken`
46
- * `Rack::Protection::HttpOrigin`
41
+ * [`Rack::Protection::AuthenticityToken`][authenticity-token] (not included by `use Rack::Protection`)
42
+ * [`Rack::Protection::FormToken`][form-token] (not included by `use Rack::Protection`)
43
+ * [`Rack::Protection::JsonCsrf`][json-csrf]
44
+ * [`Rack::Protection::RemoteReferrer`][remote-referrer] (not included by `use Rack::Protection`)
45
+ * [`Rack::Protection::RemoteToken`][remote-token]
46
+ * [`Rack::Protection::HttpOrigin`][http-origin]
47
47
 
48
48
  ## Cross Site Scripting
49
49
 
50
50
  Prevented by:
51
51
 
52
- * `Rack::Protection::EscapedParams` (not included by `use Rack::Protection`)
53
- * `Rack::Protection::XSSHeader` (Internet Explorer only)
52
+ * [`Rack::Protection::EscapedParams`][escaped-params] (not included by `use Rack::Protection`)
53
+ * [`Rack::Protection::XSSHeader`][xss-header] (Internet Explorer and Chrome only)
54
+ * [`Rack::Protection::ContentSecurityPolicy`][content-security-policy]
54
55
 
55
56
  ## Clickjacking
56
57
 
57
58
  Prevented by:
58
59
 
59
- * `Rack::Protection::FrameOptions`
60
+ * [`Rack::Protection::FrameOptions`][frame-options]
60
61
 
61
62
  ## Directory Traversal
62
63
 
63
64
  Prevented by:
64
65
 
65
- * `Rack::Protection::PathTraversal`
66
+ * [`Rack::Protection::PathTraversal`][path-traversal]
66
67
 
67
68
  ## Session Hijacking
68
69
 
69
70
  Prevented by:
70
71
 
71
- * `Rack::Protection::SessionHijacking`
72
+ * [`Rack::Protection::SessionHijacking`][session-hijacking]
73
+
74
+ ## Cookie Tossing
75
+
76
+ Prevented by:
77
+ * [`Rack::Protection::CookieTossing`][cookie-tossing] (not included by `use Rack::Protection`)
72
78
 
73
79
  ## IP Spoofing
74
80
 
75
81
  Prevented by:
76
82
 
77
- * `Rack::Protection::IPSpoofing`
83
+ * [`Rack::Protection::IPSpoofing`][ip-spoofing]
84
+
85
+ ## Helps to protect against protocol downgrade attacks and cookie hijacking
86
+
87
+ Prevented by:
88
+
89
+ * [`Rack::Protection::StrictTransport`][strict-transport] (not included by `use Rack::Protection`)
78
90
 
79
91
  # Installation
80
92
 
@@ -88,3 +100,19 @@ use Rack::Protection, instrumenter: ActiveSupport::Notifications
88
100
  ```
89
101
 
90
102
  The instrumenter is passed a namespace (String) and environment (Hash). The namespace is 'rack.protection' and the attack type can be obtained from the environment key 'rack.protection.attack'.
103
+
104
+ [authenticity-token]: http://www.sinatrarb.com/protection/authenticity_token
105
+ [content-security-policy]: http://www.sinatrarb.com/protection/content_security_policy
106
+ [cookie-tossing]: http://www.sinatrarb.com/protection/cookie_tossing
107
+ [escaped-params]: http://www.sinatrarb.com/protection/escaped_params
108
+ [form-token]: http://www.sinatrarb.com/protection/form_token
109
+ [frame-options]: http://www.sinatrarb.com/protection/frame_options
110
+ [http-origin]: http://www.sinatrarb.com/protection/http_origin
111
+ [ip-spoofing]: http://www.sinatrarb.com/protection/ip_spoofing
112
+ [json-csrf]: http://www.sinatrarb.com/protection/json_csrf
113
+ [path-traversal]: http://www.sinatrarb.com/protection/path_traversal
114
+ [remote-referrer]: http://www.sinatrarb.com/protection/remote_referrer
115
+ [remote-token]: http://www.sinatrarb.com/protection/remote_token
116
+ [session-hijacking]: http://www.sinatrarb.com/protection/session_hijacking
117
+ [strict-transport]: http://www.sinatrarb.com/protection/strict_transport
118
+ [xss-header]: http://www.sinatrarb.com/protection/xss_header
data/Rakefile CHANGED
@@ -11,6 +11,33 @@ end
11
11
  desc "run specs"
12
12
  task(:spec) { ruby '-S rspec spec' }
13
13
 
14
+ namespace :doc do
15
+ task :readmes do
16
+ Dir.glob 'lib/rack/protection/*.rb' do |file|
17
+ excluded_files = %w[lib/rack/protection/base.rb lib/rack/protection/version.rb]
18
+ next if excluded_files.include?(file)
19
+ doc = File.read(file)[/^ module Protection(\n)+( #[^\n]*\n)*/m].scan(/^ *#(?!#) ?(.*)\n/).join("\n")
20
+ file = "doc/#{file[4..-4].tr("/_", "-")}.rdoc"
21
+ Dir.mkdir "doc" unless File.directory? "doc"
22
+ puts "writing #{file}"
23
+ File.open(file, "w") { |f| f << doc }
24
+ end
25
+ end
26
+
27
+ task :index do
28
+ doc = File.read("README.md")
29
+ file = "doc/rack-protection-readme.md"
30
+ Dir.mkdir "doc" unless File.directory? "doc"
31
+ puts "writing #{file}"
32
+ File.open(file, "w") { |f| f << doc }
33
+ end
34
+
35
+ task :all => [:readmes, :index]
36
+ end
37
+
38
+ desc "generate documentation"
39
+ task :doc => 'doc:all'
40
+
14
41
  desc "generate gemspec"
15
42
  task 'rack-protection.gemspec' do
16
43
  require 'rack/protection/version'
@@ -19,13 +46,10 @@ task 'rack-protection.gemspec' do
19
46
  # fetch data
20
47
  fields = {
21
48
  :authors => `git shortlog -sn`.force_encoding('utf-8').scan(/[^\d\s].*/),
22
- :email => `git shortlog -sne`.force_encoding('utf-8').scan(/[^<]+@[^>]+/),
23
- :files => `git ls-files`.force_encoding('utf-8').split("\n").reject { |f| f =~ /^(\.|Gemfile)/ }
49
+ :email => ["mail@zzak.io", "konstantin.haase@gmail.com"],
50
+ :files => %w(License README.md Rakefile Gemfile rack-protection.gemspec) + Dir['lib/**/*']
24
51
  }
25
52
 
26
- # double email :(
27
- fields[:email].delete("konstantin.haase@gmail.com")
28
-
29
53
  # insert data
30
54
  fields.each do |field, values|
31
55
  updated = " s.#{field} = ["
@@ -1,4 +1,6 @@
1
1
  require 'rack/protection'
2
+ require 'securerandom'
3
+ require 'base64'
2
4
 
3
5
  module Rack
4
6
  module Protection
@@ -10,21 +12,120 @@ module Rack
10
12
  # Only accepts unsafe HTTP requests if a given access token matches the token
11
13
  # included in the session.
12
14
  #
13
- # Compatible with Rails and rack-csrf.
15
+ # Compatible with rack-csrf.
14
16
  #
15
17
  # Options:
16
18
  #
17
19
  # authenticity_param: Defines the param's name that should contain the token on a request.
18
- #
19
20
  class AuthenticityToken < Base
20
- default_options :authenticity_param => 'authenticity_token'
21
+ TOKEN_LENGTH = 32
22
+
23
+ default_options :authenticity_param => 'authenticity_token',
24
+ :allow_if => nil
25
+
26
+ def self.token(session)
27
+ self.new(nil).mask_authenticity_token(session)
28
+ end
29
+
30
+ def self.random_token
31
+ SecureRandom.base64(TOKEN_LENGTH)
32
+ end
21
33
 
22
34
  def accepts?(env)
23
35
  session = session env
24
- token = session[:csrf] ||= session['_csrf_token'] || random_string
36
+ set_token(session)
37
+
25
38
  safe?(env) ||
26
- secure_compare(env['HTTP_X_CSRF_TOKEN'].to_s, token) ||
27
- secure_compare(Request.new(env).params[options[:authenticity_param]].to_s, token)
39
+ valid_token?(session, env['HTTP_X_CSRF_TOKEN']) ||
40
+ valid_token?(session, Request.new(env).params[options[:authenticity_param]]) ||
41
+ ( options[:allow_if] && options[:allow_if].call(env) )
42
+ end
43
+
44
+ def mask_authenticity_token(session)
45
+ token = set_token(session)
46
+ mask_token(token)
47
+ end
48
+
49
+ private
50
+
51
+ def set_token(session)
52
+ session[:csrf] ||= self.class.random_token
53
+ end
54
+
55
+ # Checks the client's masked token to see if it matches the
56
+ # session token.
57
+ def valid_token?(session, token)
58
+ return false if token.nil? || token.empty?
59
+
60
+ begin
61
+ token = decode_token(token)
62
+ rescue ArgumentError # encoded_masked_token is invalid Base64
63
+ return false
64
+ end
65
+
66
+ # See if it's actually a masked token or not. We should be able
67
+ # to handle any unmasked tokens that we've issued without error.
68
+
69
+ if unmasked_token?(token)
70
+ compare_with_real_token token, session
71
+
72
+ elsif masked_token?(token)
73
+ token = unmask_token(token)
74
+
75
+ compare_with_real_token token, session
76
+
77
+ else
78
+ false # Token is malformed
79
+ end
80
+ end
81
+
82
+ # Creates a masked version of the authenticity token that varies
83
+ # on each request. The masking is used to mitigate SSL attacks
84
+ # like BREACH.
85
+ def mask_token(token)
86
+ token = decode_token(token)
87
+ one_time_pad = SecureRandom.random_bytes(token.length)
88
+ encrypted_token = xor_byte_strings(one_time_pad, token)
89
+ masked_token = one_time_pad + encrypted_token
90
+ encode_token(masked_token)
91
+ end
92
+
93
+ # Essentially the inverse of +mask_token+.
94
+ def unmask_token(masked_token)
95
+ # Split the token into the one-time pad and the encrypted
96
+ # value and decrypt it
97
+ token_length = masked_token.length / 2
98
+ one_time_pad = masked_token[0...token_length]
99
+ encrypted_token = masked_token[token_length..-1]
100
+ xor_byte_strings(one_time_pad, encrypted_token)
101
+ end
102
+
103
+ def unmasked_token?(token)
104
+ token.length == TOKEN_LENGTH
105
+ end
106
+
107
+ def masked_token?(token)
108
+ token.length == TOKEN_LENGTH * 2
109
+ end
110
+
111
+ def compare_with_real_token(token, session)
112
+ secure_compare(token, real_token(session))
113
+ end
114
+
115
+ def real_token(session)
116
+ decode_token(session[:csrf])
117
+ end
118
+
119
+ def encode_token(token)
120
+ Base64.strict_encode64(token)
121
+ end
122
+
123
+ def decode_token(token)
124
+ Base64.strict_decode64(token)
125
+ end
126
+
127
+ def xor_byte_strings(s1, s2)
128
+ s1.bytes.zip(s2.bytes).map { |(c1,c2)| c1 ^ c2 }.pack('c*')
28
129
  end
29
130
  end
30
131
  end
@@ -1,4 +1,5 @@
1
1
  require 'rack/protection'
2
+ require 'rack/utils'
2
3
  require 'digest'
3
4
  require 'logger'
4
5
  require 'uri'
@@ -110,28 +111,8 @@ module Rack
110
111
  options[:encryptor].hexdigest value.to_s
111
112
  end
112
113
 
113
- # The implementations of secure_compare and bytesize are taken from
114
- # Rack::Utils to be able to support rack older than XXXX.
115
114
  def secure_compare(a, b)
116
- return false unless bytesize(a) == bytesize(b)
117
-
118
- l = a.unpack("C*")
119
-
120
- r, i = 0, -1
121
- b.each_byte { |v| r |= v ^ l[i+=1] }
122
- r == 0
123
- end
124
-
125
- # Return the bytesize of String; uses String#size under Ruby 1.8 and
126
- # String#bytesize under 1.9.
127
- if ''.respond_to?(:bytesize)
128
- def bytesize(string)
129
- string.bytesize
130
- end
131
- else
132
- def bytesize(string)
133
- string.size
134
- end
115
+ Rack::Utils.secure_compare(a.to_s, b.to_s)
135
116
  end
136
117
 
137
118
  alias default_reaction deny
@@ -0,0 +1,80 @@
1
+ # -*- coding: utf-8 -*-
2
+ require 'rack/protection'
3
+
4
+ module Rack
5
+ module Protection
6
+ ##
7
+ # Prevented attack:: XSS and others
8
+ # Supported browsers:: Firefox 23+, Safari 7+, Chrome 25+, Opera 15+
9
+ #
10
+ # Description:: Content Security Policy, a mechanism web applications
11
+ # can use to mitigate a broad class of content injection
12
+ # vulnerabilities, such as cross-site scripting (XSS).
13
+ # Content Security Policy is a declarative policy that lets
14
+ # the authors (or server administrators) of a web application
15
+ # inform the client about the sources from which the
16
+ # application expects to load resources.
17
+ #
18
+ # More info:: W3C CSP Level 1 : https://www.w3.org/TR/CSP1/ (deprecated)
19
+ # W3C CSP Level 2 : https://www.w3.org/TR/CSP2/ (current)
20
+ # W3C CSP Level 3 : https://www.w3.org/TR/CSP3/ (draft)
21
+ # https://developer.mozilla.org/en-US/docs/Web/Security/CSP
22
+ # http://caniuse.com/#search=ContentSecurityPolicy
23
+ # http://content-security-policy.com/
24
+ # https://securityheaders.io
25
+ # https://scotthelme.co.uk/csp-cheat-sheet/
26
+ # http://www.html5rocks.com/en/tutorials/security/content-security-policy/
27
+ #
28
+ # Sets the 'Content-Security-Policy[-Report-Only]' header.
29
+ #
30
+ # Options: ContentSecurityPolicy configuration is a complex topic with
31
+ # several levels of support that has evolved over time.
32
+ # See the W3C documentation and the links in the more info
33
+ # section for CSP usage examples and best practices. The
34
+ # CSP3 directives in the 'NO_ARG_DIRECTIVES' constant need to be
35
+ # presented in the options hash with a boolean 'true' in order
36
+ # to be used in a policy.
37
+ #
38
+ class ContentSecurityPolicy < Base
39
+ default_options default_src: :none, script_src: "'self'",
40
+ img_src: "'self'", style_src: "'self'",
41
+ connect_src: "'self'", report_only: false
42
+
43
+ DIRECTIVES = %i(base_uri child_src connect_src default_src
44
+ font_src form_action frame_ancestors frame_src
45
+ img_src manifest_src media_src object_src
46
+ plugin_types referrer reflected_xss report_to
47
+ report_uri require_sri_for sandbox script_src
48
+ style_src worker_src).freeze
49
+
50
+ NO_ARG_DIRECTIVES = %i(block_all_mixed_content disown_opener
51
+ upgrade_insecure_requests).freeze
52
+
53
+ def csp_policy
54
+ directives = []
55
+
56
+ DIRECTIVES.each do |d|
57
+ if options.key?(d)
58
+ directives << "#{d.to_s.sub(/_/, '-')} #{options[d]}"
59
+ end
60
+ end
61
+
62
+ # Set these key values to boolean 'true' to include in policy
63
+ NO_ARG_DIRECTIVES.each do |d|
64
+ if options.key?(d) && options[d].is_a?(TrueClass)
65
+ directives << d.to_s.sub(/_/, '-')
66
+ end
67
+ end
68
+
69
+ directives.compact.sort.join('; ')
70
+ end
71
+
72
+ def call(env)
73
+ status, headers, body = @app.call(env)
74
+ header = options[:report_only] ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy'
75
+ headers[header] ||= csp_policy if html? headers
76
+ [status, headers, body]
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,75 @@
1
+ require 'rack/protection'
2
+ require 'pathname'
3
+
4
+ module Rack
5
+ module Protection
6
+ ##
7
+ # Prevented attack:: Cookie Tossing
8
+ # Supported browsers:: all
9
+ # More infos:: https://github.com/blog/1466-yummy-cookies-across-domains
10
+ #
11
+ # Does not accept HTTP requests if the HTTP_COOKIE header contains more than one
12
+ # session cookie. This does not protect against a cookie overflow attack.
13
+ #
14
+ # Options:
15
+ #
16
+ # session_key:: The name of the session cookie (default: 'rack.session')
17
+ class CookieTossing < Base
18
+ default_reaction :deny
19
+
20
+ def call(env)
21
+ status, headers, body = super
22
+ response = Rack::Response.new(body, status, headers)
23
+ request = Rack::Request.new(env)
24
+ remove_bad_cookies(request, response)
25
+ response.finish
26
+ end
27
+
28
+ def accepts?(env)
29
+ cookie_header = env['HTTP_COOKIE']
30
+ cookies = Rack::Utils.parse_query(cookie_header, ';,') { |s| s }
31
+ cookies.each do |k, v|
32
+ if k == session_key && Array(v).size > 1
33
+ bad_cookies << k
34
+ elsif k != session_key && Rack::Utils.unescape(k) == session_key
35
+ bad_cookies << k
36
+ end
37
+ end
38
+ bad_cookies.empty?
39
+ end
40
+
41
+ def remove_bad_cookies(request, response)
42
+ return if bad_cookies.empty?
43
+ paths = cookie_paths(request.path)
44
+ bad_cookies.each do |name|
45
+ paths.each { |path| response.set_cookie name, empty_cookie(request.host, path) }
46
+ end
47
+ end
48
+
49
+ def redirect(env)
50
+ request = Request.new(env)
51
+ warn env, "attack prevented by #{self.class}"
52
+ [302, {'Content-Type' => 'text/html', 'Location' => request.path}, []]
53
+ end
54
+
55
+ def bad_cookies
56
+ @bad_cookies ||= []
57
+ end
58
+
59
+ def cookie_paths(path)
60
+ path = '/' if path.to_s.empty?
61
+ paths = []
62
+ Pathname.new(path).descend { |p| paths << p.to_s }
63
+ paths
64
+ end
65
+
66
+ def empty_cookie(host, path)
67
+ {:value => '', :domain => host, :path => path, :expires => Time.at(0)}
68
+ end
69
+
70
+ def session_key
71
+ @session_key ||= options[:session_key]
72
+ end
73
+ end
74
+ end
75
+ end
@@ -1,5 +1,6 @@
1
1
  require 'rack/protection'
2
2
  require 'rack/utils'
3
+ require 'tempfile'
3
4
 
4
5
  begin
5
6
  require 'escape_utils'
@@ -66,6 +67,7 @@ module Rack
66
67
  when Hash then escape_hash(object)
67
68
  when Array then object.map { |o| escape(o) }
68
69
  when String then escape_string(object)
70
+ when Tempfile then object
69
71
  else nil
70
72
  end
71
73
  end
@@ -13,7 +13,7 @@ module Rack
13
13
  # This middleware is not used when using the Rack::Protection collection,
14
14
  # since it might be a security issue, depending on your application
15
15
  #
16
- # Compatible with Rails and rack-csrf.
16
+ # Compatible with rack-csrf.
17
17
  class FormToken < AuthenticityToken
18
18
  def accepts?(env)
19
19
  env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" or super
@@ -10,9 +10,16 @@ module Rack
10
10
  #
11
11
  # Does not accept unsafe HTTP requests when value of Origin HTTP request header
12
12
  # does not match default or whitelisted URIs.
13
+ #
14
+ # If you want to whitelist a specific domain, you can pass in as the `:origin_whitelist` option:
15
+ #
16
+ # use Rack::Protection, origin_whitelist: ["http://localhost:3000", "http://127.0.01:3000"]
17
+ #
18
+ # The `:allow_if` option can also be set to a proc to use custom allow/deny logic.
13
19
  class HttpOrigin < Base
14
20
  DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 }
15
21
  default_reaction :deny
22
+ default_options :allow_if => nil
16
23
 
17
24
  def base_url(env)
18
25
  request = Rack::Request.new(env)
@@ -24,6 +31,7 @@ module Rack
24
31
  return true if safe? env
25
32
  return true unless origin = env['HTTP_ORIGIN']
26
33
  return true if base_url(env) == origin
34
+ return true if options[:allow_if] && options[:allow_if].call(env)
27
35
  Array(options[:origin_whitelist]).include? origin
28
36
  end
29
37
 
@@ -5,21 +5,30 @@ module Rack
5
5
  ##
6
6
  # Prevented attack:: CSRF
7
7
  # Supported browsers:: all
8
- # More infos:: http://flask.pocoo.org/docs/security/#json-security
8
+ # More infos:: http://flask.pocoo.org/docs/0.10/security/#json-security
9
+ # http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
9
10
  #
10
- # JSON GET APIs are vulnerable to being embedded as JavaScript while the
11
+ # JSON GET APIs are vulnerable to being embedded as JavaScript when the
11
12
  # Array prototype has been patched to track data. Checks the referrer
12
13
  # even on GET requests if the content type is JSON.
14
+ #
15
+ # If request includes Origin HTTP header, defers to HttpOrigin to determine
16
+ # if the request is safe. Please refer to the documentation for more info.
17
+ #
18
+ # The `:allow_if` option can be set to a proc to use custom allow/deny logic.
13
19
  class JsonCsrf < Base
20
+ default_options :allow_if => nil
21
+
14
22
  alias react deny
15
23
 
16
24
  def call(env)
17
25
  request = Request.new(env)
18
26
  status, headers, body = app.call(env)
19
27
 
20
- if has_vector? request, headers
28
+ if has_vector?(request, headers)
21
29
  warn env, "attack prevented by #{self.class}"
22
- react(env) or [status, headers, body]
30
+
31
+ react_and_close(env, body) or [status, headers, body]
23
32
  else
24
33
  [status, headers, body]
25
34
  end
@@ -27,9 +36,22 @@ module Rack
27
36
 
28
37
  def has_vector?(request, headers)
29
38
  return false if request.xhr?
39
+ return false if options[:allow_if] && options[:allow_if].call(request.env)
30
40
  return false unless headers['Content-Type'].to_s.split(';', 2).first =~ /^\s*application\/json\s*$/
31
41
  origin(request.env).nil? and referrer(request.env) != request.host
32
42
  end
43
+
44
+ def react_and_close(env, body)
45
+ reaction = react(env)
46
+
47
+ close_body(body) if reaction
48
+
49
+ reaction
50
+ end
51
+
52
+ def close_body(body)
53
+ body.close if body.respond_to?(:close)
54
+ end
33
55
  end
34
56
  end
35
57
  end
@@ -10,7 +10,7 @@ module Rack
10
10
  # Only accepts unsafe HTTP requests if a given access token matches the token
11
11
  # included in the session *or* the request comes from the same origin.
12
12
  #
13
- # Compatible with Rails and rack-csrf.
13
+ # Compatible with rack-csrf.
14
14
  class RemoteToken < AuthenticityToken
15
15
  default_reaction :deny
16
16
 
@@ -0,0 +1,39 @@
1
+ require 'rack/protection'
2
+
3
+ module Rack
4
+ module Protection
5
+ ##
6
+ # Prevented attack:: Protects against against protocol downgrade attacks and cookie hijacking.
7
+ # Supported browsers:: all
8
+ # More infos:: https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security
9
+ #
10
+ # browser will prevent any communications from being sent over HTTP
11
+ # to the specified domain and will instead send all communications over HTTPS.
12
+ # It also prevents HTTPS click through prompts on browsers.
13
+ #
14
+ # Options:
15
+ #
16
+ # max_age:: How long future requests to the domain should go over HTTPS; specified in seconds
17
+ # include_subdomains:: If all present and future subdomains will be HTTPS
18
+ # preload:: Allow this domain to be included in browsers HSTS preload list. See https://hstspreload.appspot.com/
19
+
20
+ class StrictTransport < Base
21
+ default_options :max_age => 31_536_000, :include_subdomains => false, :preload => false
22
+
23
+ def strict_transport
24
+ @strict_transport ||= begin
25
+ strict_transport = 'max-age=' + options[:max_age].to_s
26
+ strict_transport += '; includeSubDomains' if options[:include_subdomains]
27
+ strict_transport += '; preload' if options[:preload]
28
+ strict_transport.to_str
29
+ end
30
+ end
31
+
32
+ def call(env)
33
+ status, headers, body = @app.call(env)
34
+ headers['Strict-Transport-Security'] ||= strict_transport
35
+ [status, headers, body]
36
+ end
37
+ end
38
+ end
39
+ end