Class: Datadog::AppSec::Contrib::Excon::SSRFDetectionMiddleware

Inherits:
Excon::Middleware::Base
  • Object
show all
Defined in:
lib/datadog/appsec/contrib/excon/ssrf_detection_middleware.rb

Overview

AppSec Middleware for Excon

Constant Summary collapse

REDIRECT_STATUS_CODES =
(300..399).freeze
SAMPLE_BODY_KEY =
:__datadog_appsec_sample_downstream_body

Instance Method Summary collapse

Instance Method Details

#request_call(data) ⇒ Object



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
49
50
51
# File 'lib/datadog/appsec/contrib/excon/ssrf_detection_middleware.rb', line 20

def request_call(data)
  context = AppSec.active_context
  return super unless context && AppSec.rasp_enabled?

  url = request_url(data)
  headers = normalize_headers(data[:headers])
  # @type var ephemeral_data: ::Datadog::AppSec::Context::input_data
  ephemeral_data = {
    'server.io.net.url' => url,
    'server.io.net.request.method' => data[:method].to_s.upcase,
    'server.io.net.request.headers' => headers
  }

  is_redirect = context.state[:downstream_redirect_url] == url
  if is_redirect
    context.state.delete(:downstream_redirect_url)
    data[SAMPLE_BODY_KEY] = true
  else
    mark_body_sampling!(data, context: context)
  end

  if !is_redirect && data[SAMPLE_BODY_KEY]
    body = parse_body(data[:body], content_type: headers['content-type'])
    ephemeral_data['server.io.net.request.body'] = body if body
  end

  timeout = Datadog.configuration.appsec.waf_timeout
  result = context.run_rasp(Ext::RASP_SSRF, {}, ephemeral_data, timeout, phase: Ext::RASP_REQUEST_PHASE)
  handle(result, context: context) if result.match?

  super
end

#response_call(data) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/datadog/appsec/contrib/excon/ssrf_detection_middleware.rb', line 53

def response_call(data)
  context = AppSec.active_context
  return super unless context && AppSec.rasp_enabled?

  headers = normalize_headers(data.dig(:response, :headers))
  # @type var ephemeral_data: ::Datadog::AppSec::Context::input_data
  ephemeral_data = {
    'server.io.net.response.status' => data.dig(:response, :status).to_s,
    'server.io.net.response.headers' => headers
  }

  is_redirect = REDIRECT_STATUS_CODES.cover?(data.dig(:response, :status)) && headers.key?('location')
  if is_redirect && data[SAMPLE_BODY_KEY]
    context.state[:downstream_redirect_url] = URI.join(request_url(data), headers['location']).to_s
  end

  if !is_redirect && data[SAMPLE_BODY_KEY]
    body = parse_body(data.dig(:response, :body), content_type: headers['content-type'])
    ephemeral_data['server.io.net.response.body'] = body if body
  end

  timeout = Datadog.configuration.appsec.waf_timeout
  result = context.run_rasp(Ext::RASP_SSRF, {}, ephemeral_data, timeout, phase: Ext::RASP_RESPONSE_PHASE)
  handle(result, context: context) if result.match?

  super
end