1
0
Fork 0
mirror of https://github.com/sinatra/sinatra synced 2023-03-27 23:18:01 -04:00
sinatra/rack-protection/lib/rack/protection/authenticity_token.rb
Vasiliy 8ae87a87f3
Setup Rubocop (#1537)
* Initialize rubocop

* Style/StringLiterals: prefer single quotes

* Style/AndOr: use `&&` and `||`, instead of `and` and `or`

* Style/HashSyntax: use new hash syntax

* Layout/EmptyLineAfterGuardClause: add empty lines after guard clause

* Style/SingleLineMethods: temporary disable

It breaks layout of the code, it is better to fix it manually

* Style/Proc: prefer `proc` vs `Proc.new`

* Disable Lint/AmbiguousBlockAssociation

It affects proc definitions for sinatra DSL

* Disable Style/CaseEquality

* Lint/UnusedBlockArgument: put underscore in front of it

* Style/Alias: prefer alias vs alias_method in a class body

* Layout/EmptyLineBetweenDefs: add empty lines between defs

* Style/ParallelAssignment: don't use parallel assigment

* Style/RegexpLiteral: prefer %r for regular expressions

* Naming/UncommunicativeMethodParamName: fix abbrevs

* Style/PerlBackrefs: disable cop

* Layout/SpaceAfterComma: add missing spaces

* Style/Documentation: disable cop

* Style/FrozenStringLiteralComment: add frozen_string_literal

* Layout/AlignHash: align hash

* Layout/ExtraSpacing: allow for alignment

* Layout/SpaceAroundOperators: add missing spaces

* Style/Not: prefer `!` instead of `not`

* Style/GuardClause: add guard conditions

* Style/MutableConstant: freeze contants

* Lint/IneffectiveAccessModifier: disable cop

* Lint/RescueException: disable cop

* Style/SpecialGlobalVars: disable cop

* Layout/DotPosition: fix position of dot for multiline method chains

* Layout/SpaceInsideArrayLiteralBrackets: don't use spaces inside arrays

* Layout/SpaceInsideBlockBraces: add space for blocks

* Layout/SpaceInsideHashLiteralBraces: add spaces for hashes

* Style/FormatString: use format string syntax

* Style/StderrPuts: `warn` is preferable to `$stderr.puts`

* Bundler/DuplicatedGem: disable cop

* Layout/AlignArray: fix warning

* Lint/AssignmentInCondition: remove assignments from conditions

* Layout/IndentHeredoc: disable cop

* Layout/SpaceInsideParens: remove extra spaces

* Lint/UnusedMethodArgument: put underscore in front of unused arg

* Naming/RescuedExceptionsVariableName: use `e` for exceptions

* Style/CommentedKeyword: put comments before the method

* Style/FormatStringToken: disable cop

* Style/MultilineIfModifier: move condition before the method

* Style/SignalException: prefer `raise` to `fail`

* Style/SymbolArray: prefer %i for array of symbols

* Gemspec/OrderedDependencies: Use alphabetical order for dependencies

* Lint/UselessAccessModifier: disable cop

* Naming/HeredocDelimiterNaming: change delimiter's name

* Style/ClassCheck: prefer `is_a?` to `kind_of?`

* Style/ClassVars: disable cop

* Style/Encoding: remove coding comment

* Style/RedundantParentheses: remove extra parentheses

* Style/StringLiteralsInInterpolation: prefer singl quotes

* Layout/AlignArguments: fix alignment

* Layout/ClosingHeredocIndentation: align heredoc

* Layout/EmptyLineAfterMagicComment: add empty line

* Set RubyVersion for rubocop

* Lint/UselessAssignment: disable cop

* Style/EmptyLiteral: disable cop

Causes test failures

* Minor code-style fixes with --safe-auto-correct option

* Disable the rest of the cops that cause warnings

It would be easier to re-enable them in separate PRs

* Add rubocop check to the default Rake task

* Update to rubocop 1.32.0

* Rubocop updates for rack-protection and sinatra-contrib

* Disable Style/SlicingWithRange cop

* Make suggested updates

Co-authored-by: Jordan Owens <jkowens@gmail.com>
2022-07-31 08:56:44 -04:00

255 lines
7.9 KiB
Ruby

# frozen_string_literal: true
require 'rack/protection'
require 'securerandom'
require 'openssl'
require 'base64'
module Rack
module Protection
##
# Prevented attack:: CSRF
# Supported browsers:: all
# More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery
#
# This middleware only accepts requests other than <tt>GET</tt>,
# <tt>HEAD</tt>, <tt>OPTIONS</tt>, <tt>TRACE</tt> if their given access
# token matches the token included in the session.
#
# It checks the <tt>X-CSRF-Token</tt> header and the <tt>POST</tt> form
# data.
#
# It is not OOTB-compatible with the {rack-csrf}[https://rubygems.org/gems/rack_csrf] gem.
# For that, the following patch needs to be applied:
#
# Rack::Protection::AuthenticityToken.default_options(key: "csrf.token", authenticity_param: "_csrf")
#
# == Options
#
# [<tt>:authenticity_param</tt>] the name of the param that should contain
# the token on a request. Default value:
# <tt>"authenticity_token"</tt>
#
# [<tt>:key</tt>] the name of the param that should contain
# the token in the session. Default value:
# <tt>:csrf</tt>
#
# [<tt>:allow_if</tt>] a proc for custom allow/deny logic. Default value:
# <tt>nil</tt>
#
# == Example: Forms application
#
# To show what the AuthenticityToken does, this section includes a sample
# program which shows two forms. One with, and one without a CSRF token
# The one without CSRF token field will get a 403 Forbidden response.
#
# Install the gem, then run the program:
#
# gem install 'rack-protection'
# ruby server.rb
#
# Here is <tt>server.rb</tt>:
#
# require 'rack/protection'
#
# app = Rack::Builder.app do
# use Rack::Session::Cookie, secret: 'secret'
# use Rack::Protection::AuthenticityToken
#
# run -> (env) do
# [200, {}, [
# <<~EOS
# <!DOCTYPE html>
# <html lang="en">
# <head>
# <meta charset="UTF-8" />
# <title>rack-protection minimal example</title>
# </head>
# <body>
# <h1>Without Authenticity Token</h1>
# <p>This takes you to <tt>Forbidden</tt></p>
# <form action="" method="post">
# <input type="text" name="foo" />
# <input type="submit" />
# </form>
#
# <h1>With Authenticity Token</h1>
# <p>This successfully takes you to back to this form.</p>
# <form action="" method="post">
# <input type="hidden" name="authenticity_token" value="#{Rack::Protection::AuthenticityToken.token(env['rack.session'])}" />
# <input type="text" name="foo" />
# <input type="submit" />
# </form>
# </body>
# </html>
# EOS
# ]]
# end
# end
#
# Rack::Handler::WEBrick.run app
#
# == Example: Customize which POST parameter holds the token
#
# To customize the authenticity parameter for form data, use the
# <tt>:authenticity_param</tt> option:
# use Rack::Protection::AuthenticityToken, authenticity_param: 'your_token_param_name'
class AuthenticityToken < Base
TOKEN_LENGTH = 32
default_options authenticity_param: 'authenticity_token',
key: :csrf,
allow_if: nil
def self.token(session, path: nil, method: :post)
new(nil).mask_authenticity_token(session, path: path, method: method)
end
def self.random_token
SecureRandom.urlsafe_base64(TOKEN_LENGTH, padding: false)
end
def accepts?(env)
session = session(env)
set_token(session)
safe?(env) ||
valid_token?(env, env['HTTP_X_CSRF_TOKEN']) ||
valid_token?(env, Request.new(env).params[options[:authenticity_param]]) ||
options[:allow_if]&.call(env)
rescue StandardError
false
end
def mask_authenticity_token(session, path: nil, method: :post)
set_token(session)
token = if path && method
per_form_token(session, path, method)
else
global_token(session)
end
mask_token(token)
end
GLOBAL_TOKEN_IDENTIFIER = '!real_csrf_token'
private_constant :GLOBAL_TOKEN_IDENTIFIER
private
def set_token(session)
session[options[:key]] ||= self.class.random_token
end
# Checks the client's masked token to see if it matches the
# session token.
def valid_token?(env, token)
return false if token.nil? || !token.is_a?(String) || token.empty?
session = session(env)
begin
token = decode_token(token)
rescue ArgumentError # encoded_masked_token is invalid Base64
return false
end
# See if it's actually a masked token or not. We should be able
# to handle any unmasked tokens that we've issued without error.
if unmasked_token?(token)
compare_with_real_token(token, session)
elsif masked_token?(token)
token = unmask_token(token)
compare_with_global_token(token, session) ||
compare_with_real_token(token, session) ||
compare_with_per_form_token(token, session, Request.new(env))
else
false # Token is malformed
end
end
# Creates a masked version of the authenticity token that varies
# on each request. The masking is used to mitigate SSL attacks
# like BREACH.
def mask_token(token)
one_time_pad = SecureRandom.random_bytes(token.length)
encrypted_token = xor_byte_strings(one_time_pad, token)
masked_token = one_time_pad + encrypted_token
encode_token(masked_token)
end
# Essentially the inverse of +mask_token+.
def unmask_token(masked_token)
# Split the token into the one-time pad and the encrypted
# value and decrypt it
token_length = masked_token.length / 2
one_time_pad = masked_token[0...token_length]
encrypted_token = masked_token[token_length..]
xor_byte_strings(one_time_pad, encrypted_token)
end
def unmasked_token?(token)
token.length == TOKEN_LENGTH
end
def masked_token?(token)
token.length == TOKEN_LENGTH * 2
end
def compare_with_real_token(token, session)
secure_compare(token, real_token(session))
end
def compare_with_global_token(token, session)
secure_compare(token, global_token(session))
end
def compare_with_per_form_token(token, session, request)
secure_compare(token,
per_form_token(session, request.path.chomp('/'), request.request_method))
end
def real_token(session)
decode_token(session[options[:key]])
end
def global_token(session)
token_hmac(session, GLOBAL_TOKEN_IDENTIFIER)
end
def per_form_token(session, path, method)
token_hmac(session, "#{path}##{method.downcase}")
end
def encode_token(token)
Base64.urlsafe_encode64(token)
end
def decode_token(token)
Base64.urlsafe_decode64(token)
end
def token_hmac(session, identifier)
OpenSSL::HMAC.digest(
OpenSSL::Digest.new('SHA256'),
real_token(session),
identifier
)
end
def xor_byte_strings(s1, s2)
s2 = s2.dup
size = s1.bytesize
i = 0
while i < size
s2.setbyte(i, s1.getbyte(i) ^ s2.getbyte(i))
i += 1
end
s2
end
end
end
end