Skip to content

Instantly share code, notes, and snippets.

@shimadama
Last active December 21, 2021 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shimadama/1d6b8373f6a7be3c73985961760fac34 to your computer and use it in GitHub Desktop.
Save shimadama/1d6b8373f6a7be3c73985961760fac34 to your computer and use it in GitHub Desktop.
悪意のあるQueryStringを含むリクエストをrack_attackで防御
# frozen_string_literal: true
class Rack::Attack
class Request < ::Rack::Request
def remote_ip
@remote_ip ||= (env['HTTP_CF_CONNECTING_IP'] || env['action_dispatch.remote_ip'] || ip).to_s
end
def allowed_ip?
allowed_ips = ['127.0.0.1', '::1']
allowed_ips.include?(remote_ip)
end
end
# NOTE: ローカル開発環境で挙動を確認するには下記をコメントアウトする
safelist('allow from localhost', &:allowed_ip?)
# オフィス内 IP などの safelist IP アドレスの設定
Rails.application.config.trusted_ip_addresses do |ip|
safelist_ip(ip)
end
blocklist('block access if UNION is included in params') do |req|
req.env['QUERY_STRING'].match?(/UNION/i)
end
# 後で追記する
end
# frozen_string_literal: true
# ブロックされたイベントをログに記録
ActiveSupport::Notifications.subscribe('blocklist.rack_attack') do |_name, _start, _finish, _request_id, payload|
request = payload[:request]
request_headers = { 'CF-RAY' => request.env['HTTP_CF_RAY'] }
# ログ出力情報
# ip, path, headers, url
Rails.logger.info "[Rack::Attack][Blocked] remote_ip: #{request.remote_ip}, path: #{request.path}, headers: #{request_headers.inspect}, url: #{request.url}"
# Slack通知
# Slack通知の処理を書く
# logを流すだけのチャンネルを作成し、そこで確認できるようにした感じです
# 不要だと思ったら書かなくていいです
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment