Last active
December 21, 2021 20:45
-
-
Save shimadama/1d6b8373f6a7be3c73985961760fac34 to your computer and use it in GitHub Desktop.
悪意のあるQueryStringを含むリクエストをrack_attackで防御
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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