GrapeでCSRF対策

セキュリティ試験を受けたらapiでpostしている箇所がcsrf違反でレポートが上がってきました。
apiでcsrfって必要なの?
って感じでしたが実際にレポートあがってきてしまっているしよくよく考えたら必要じゃんってなったので実装します。

ググってみると情報が少ないですね。
みなさんgrapeでcsrfどうしているんでしょう。


gistでサンプル見つけましたが、
jandudulski/auth.rb
Rails5.1.4では動きません。

actionpackのcsrfの実装
をみながら実装してみます。

結果としてはこんな感じになりました。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
module V1
  module RequestForgeryProtectionHelper
    def session
      env['rack.session']
    end

    def protect_against_forgery
      unless verified_request?
        Rails.logger.error("[API] Can't verify CSRF token authenticity.")
        error!(
          {
            result: 401,
            status: 'error',
            type: 'csrf_error',
            message: "Can't verify CSRF token authenticity."
          }, 401
        )
      end
    end

    def verified_request?
      !protect_against_forgery? || request.get? || request.head? ||
        authenticity_token_valid?
    end

    def authenticity_token_valid?
      encoded_masked_token = request.headers['X-CSRF-Token'] || request.headers['X-Csrf-Token']
      return false if encoded_masked_token.blank?
      masked_token = Base64.strict_decode64(encoded_masked_token)

      anonymous_controller = ApplicationController.new
      if masked_token.length == ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH
        anonymous_controller.send(:compare_with_real_token, masked_token, session)
      elsif masked_token.length == ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH * 2
        csrf_token = anonymous_controller.send(:unmask_token, masked_token)

        anonymous_controller.send(:compare_with_real_token, csrf_token, session)
      else
        false # Token is malformed.
      end
    end

    def protect_against_forgery?
      allow_forgery_protection = Rails.configuration.action_controller.allow_forgery_protection
      allow_forgery_protection.nil? || allow_forgery_protection
    end
  end
end
1
2
3
4
5
6
7
8
9
module V1
  class Root < Grape::API
    helpers RequestForgeryProtectionHelper

    before do
      protect_against_forgery
    end
  end
end

クライアント側

1
2
3
4
5
6
var token = $( 'meta[name="csrf-token"]' ).attr( 'content' );
$.ajaxSetup({
  beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'X-CSRF-Token', token );
  }
});

Comments