contrast-agent 4.11.0 → 4.14.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (145) hide show
  1. checksums.yaml +4 -4
  2. data/.simplecov +1 -0
  3. data/ext/cs__assess_module/cs__assess_module.c +48 -0
  4. data/ext/cs__assess_module/cs__assess_module.h +7 -0
  5. data/ext/cs__common/cs__common.c +24 -7
  6. data/ext/cs__common/cs__common.h +12 -2
  7. data/ext/cs__contrast_patch/cs__contrast_patch.c +48 -11
  8. data/ext/cs__contrast_patch/cs__contrast_patch.h +5 -2
  9. data/ext/cs__os_information/cs__os_information.c +31 -0
  10. data/ext/cs__os_information/cs__os_information.h +7 -0
  11. data/ext/{cs__protect_kernel → cs__os_information}/extconf.rb +0 -0
  12. data/lib/contrast/agent/assess/contrast_event.rb +1 -1
  13. data/lib/contrast/agent/assess/contrast_object.rb +1 -1
  14. data/lib/contrast/agent/assess/policy/dynamic_source_factory.rb +2 -0
  15. data/lib/contrast/agent/assess/policy/policy_node.rb +6 -6
  16. data/lib/contrast/agent/assess/policy/policy_scanner.rb +5 -0
  17. data/lib/contrast/agent/assess/policy/preshift.rb +19 -6
  18. data/lib/contrast/agent/assess/policy/propagation_method.rb +2 -116
  19. data/lib/contrast/agent/assess/policy/propagation_node.rb +4 -4
  20. data/lib/contrast/agent/assess/policy/propagator/center.rb +1 -1
  21. data/lib/contrast/agent/assess/policy/propagator/database_write.rb +2 -0
  22. data/lib/contrast/agent/assess/policy/propagator/substitution.rb +2 -154
  23. data/lib/contrast/agent/assess/policy/source_method.rb +2 -71
  24. data/lib/contrast/agent/assess/policy/trigger_method.rb +45 -110
  25. data/lib/contrast/agent/assess/policy/trigger_node.rb +62 -21
  26. data/lib/contrast/agent/assess/policy/trigger_validation/xss_validator.rb +1 -1
  27. data/lib/contrast/agent/assess/property/tagged.rb +66 -189
  28. data/lib/contrast/agent/assess/rule/provider/hardcoded_value_rule.rb +40 -6
  29. data/lib/contrast/agent/deadzone/policy/policy.rb +6 -0
  30. data/lib/contrast/agent/inventory/dependency_usage_analysis.rb +1 -0
  31. data/lib/contrast/agent/metric_telemetry_event.rb +26 -0
  32. data/lib/contrast/agent/middleware.rb +14 -62
  33. data/lib/contrast/agent/patching/policy/after_load_patcher.rb +0 -1
  34. data/lib/contrast/agent/patching/policy/method_policy.rb +3 -44
  35. data/lib/contrast/agent/patching/policy/method_policy_extend.rb +111 -0
  36. data/lib/contrast/agent/patching/policy/patch.rb +37 -238
  37. data/lib/contrast/agent/patching/policy/patcher.rb +15 -50
  38. data/lib/contrast/agent/reporting/report.rb +21 -0
  39. data/lib/contrast/agent/reporting/reporter.rb +142 -0
  40. data/lib/contrast/agent/reporting/reporting_events/finding.rb +90 -0
  41. data/lib/contrast/agent/reporting/reporting_events/preflight.rb +25 -0
  42. data/lib/contrast/agent/reporting/reporting_events/preflight_message.rb +56 -0
  43. data/lib/contrast/agent/reporting/reporting_events/reporting_event.rb +37 -0
  44. data/lib/contrast/agent/reporting/reporting_utilities/audit.rb +127 -0
  45. data/lib/contrast/agent/reporting/reporting_utilities/reporter_client.rb +168 -0
  46. data/lib/contrast/agent/reporting/reporting_utilities/reporting_storage.rb +66 -0
  47. data/lib/contrast/agent/request.rb +2 -81
  48. data/lib/contrast/agent/request_context.rb +18 -126
  49. data/lib/contrast/agent/request_context_extend.rb +138 -0
  50. data/lib/contrast/agent/request_handler.rb +7 -3
  51. data/lib/contrast/agent/response.rb +2 -73
  52. data/lib/contrast/agent/rule_set.rb +2 -4
  53. data/lib/contrast/agent/startup_metrics_telemetry_event.rb +94 -0
  54. data/lib/contrast/agent/static_analysis.rb +5 -3
  55. data/lib/contrast/agent/telemetry.rb +137 -0
  56. data/lib/contrast/agent/telemetry_event.rb +33 -0
  57. data/lib/contrast/agent/thread_watcher.rb +66 -11
  58. data/lib/contrast/agent/version.rb +1 -1
  59. data/lib/contrast/agent.rb +21 -1
  60. data/lib/contrast/api/communication/connection_status.rb +10 -7
  61. data/lib/contrast/api/communication/messaging_queue.rb +37 -3
  62. data/lib/contrast/api/communication/response_processor.rb +15 -8
  63. data/lib/contrast/api/communication/service_lifecycle.rb +13 -3
  64. data/lib/contrast/api/communication/socket.rb +6 -8
  65. data/lib/contrast/api/communication/socket_client.rb +29 -12
  66. data/lib/contrast/api/communication/speedracer.rb +37 -1
  67. data/lib/contrast/api/communication/tcp_socket.rb +4 -3
  68. data/lib/contrast/api/communication/unix_socket.rb +1 -0
  69. data/lib/contrast/api/decorators/finding.rb +45 -0
  70. data/lib/contrast/components/api.rb +90 -0
  71. data/lib/contrast/components/app_context.rb +10 -41
  72. data/lib/contrast/components/app_context_extend.rb +78 -0
  73. data/lib/contrast/components/assess.rb +7 -0
  74. data/lib/contrast/components/base.rb +23 -0
  75. data/lib/contrast/components/config.rb +92 -13
  76. data/lib/contrast/components/contrast_service.rb +11 -0
  77. data/lib/contrast/components/sampling.rb +2 -2
  78. data/lib/contrast/config/agent_configuration.rb +1 -1
  79. data/lib/contrast/config/api_configuration.rb +27 -0
  80. data/lib/contrast/config/api_proxy_configuration.rb +14 -0
  81. data/lib/contrast/config/application_configuration.rb +2 -3
  82. data/lib/contrast/config/assess_configuration.rb +3 -2
  83. data/lib/contrast/config/base_configuration.rb +17 -28
  84. data/lib/contrast/config/certification_configuration.rb +15 -0
  85. data/lib/contrast/config/env_variables.rb +18 -0
  86. data/lib/contrast/config/heap_dump_configuration.rb +6 -6
  87. data/lib/contrast/config/inventory_configuration.rb +1 -5
  88. data/lib/contrast/config/protect_rule_configuration.rb +1 -1
  89. data/lib/contrast/config/request_audit_configuration.rb +18 -0
  90. data/lib/contrast/config/root_configuration.rb +1 -0
  91. data/lib/contrast/config/ruby_configuration.rb +6 -6
  92. data/lib/contrast/config/service_configuration.rb +2 -2
  93. data/lib/contrast/config.rb +1 -1
  94. data/lib/contrast/configuration.rb +4 -2
  95. data/lib/contrast/extension/assess/array.rb +5 -7
  96. data/lib/contrast/framework/manager.rb +22 -44
  97. data/lib/contrast/framework/manager_extend.rb +50 -0
  98. data/lib/contrast/framework/rails/patch/action_controller_live_buffer.rb +9 -6
  99. data/lib/contrast/framework/rails/patch/support.rb +31 -29
  100. data/lib/contrast/framework/rails/railtie.rb +1 -1
  101. data/lib/contrast/framework/sinatra/support.rb +2 -1
  102. data/lib/contrast/logger/application.rb +4 -0
  103. data/lib/contrast/logger/log.rb +8 -103
  104. data/lib/contrast/utils/assess/propagation_method_utils.rb +129 -0
  105. data/lib/contrast/utils/assess/property/tagged_utils.rb +165 -0
  106. data/lib/contrast/utils/assess/source_method_utils.rb +83 -0
  107. data/lib/contrast/utils/assess/tracking_util.rb +20 -15
  108. data/lib/contrast/utils/assess/trigger_method_utils.rb +138 -0
  109. data/lib/contrast/utils/class_util.rb +65 -54
  110. data/lib/contrast/utils/exclude_key.rb +20 -0
  111. data/lib/contrast/utils/findings.rb +62 -0
  112. data/lib/contrast/utils/hash_digest.rb +10 -73
  113. data/lib/contrast/utils/hash_digest_extend.rb +86 -0
  114. data/lib/contrast/utils/head_dump_utils_extend.rb +74 -0
  115. data/lib/contrast/utils/heap_dump_util.rb +2 -65
  116. data/lib/contrast/utils/invalid_configuration_util.rb +29 -0
  117. data/lib/contrast/utils/io_util.rb +1 -1
  118. data/lib/contrast/utils/log_utils.rb +108 -0
  119. data/lib/contrast/utils/lru_cache.rb +4 -2
  120. data/lib/contrast/utils/metrics_hash.rb +59 -0
  121. data/lib/contrast/utils/middleware_utils.rb +87 -0
  122. data/lib/contrast/utils/net_http_base.rb +158 -0
  123. data/lib/contrast/utils/object_share.rb +1 -0
  124. data/lib/contrast/utils/os.rb +23 -0
  125. data/lib/contrast/utils/patching/policy/patch_utils.rb +232 -0
  126. data/lib/contrast/utils/patching/policy/patcher_utils.rb +54 -0
  127. data/lib/contrast/utils/request_utils.rb +88 -0
  128. data/lib/contrast/utils/response_utils.rb +97 -0
  129. data/lib/contrast/utils/substitution_utils.rb +167 -0
  130. data/lib/contrast/utils/tag_util.rb +9 -9
  131. data/lib/contrast/utils/telemetry.rb +79 -0
  132. data/lib/contrast/utils/telemetry_client.rb +90 -0
  133. data/lib/contrast/utils/telemetry_identifier.rb +130 -0
  134. data/lib/contrast.rb +19 -1
  135. data/resources/assess/policy.json +12 -6
  136. data/resources/deadzone/policy.json +86 -5
  137. data/ruby-agent.gemspec +7 -6
  138. data/service_executables/VERSION +1 -1
  139. data/service_executables/linux/contrast-service +0 -0
  140. data/service_executables/mac/contrast-service +0 -0
  141. metadata +68 -26
  142. data/ext/cs__protect_kernel/cs__protect_kernel.c +0 -47
  143. data/ext/cs__protect_kernel/cs__protect_kernel.h +0 -12
  144. data/lib/contrast/config/default_value.rb +0 -17
  145. data/lib/contrast/extension/protect/kernel.rb +0 -29
@@ -0,0 +1,87 @@
1
+ # Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ module Contrast
5
+ module Utils
6
+ # helper methods for Contrast::Agent::Middleware
7
+ # including disclaimers, deprecation notices, error handling, setup
8
+ module MiddlewareUtils
9
+ private
10
+
11
+ def setup_agent
12
+ ::Contrast::SETTINGS.reset_state
13
+
14
+ inform_deprecations
15
+ telemetry_disclaimer
16
+
17
+ if ::Contrast::CONFIG.invalid?
18
+ ::Contrast::AGENT.disable!
19
+ logger.error('!!! CONFIG FILE IS INVALID - DISABLING CONTRAST AGENT !!!')
20
+ elsif ::Contrast::AGENT.disabled?
21
+ logger.warn('Contrast disabled by configuration. Continuing without instrumentation.')
22
+ else
23
+ ::Contrast::AGENT.enable!
24
+ end
25
+ end
26
+
27
+ SECURITY_EXCEPTION_MARKER = 'Contrast::SecurityException'
28
+ # We're only going to suppress SecurityExceptions indicating a blocked attack. And, only if the
29
+ # config.agent.ruby.exceptions.capture? is set
30
+ def handle_exception exception
31
+ if security_exception?(exception)
32
+ exception_control = ::Contrast::AGENT.exception_control
33
+ raise exception unless exception_control[:enable]
34
+
35
+ [exception_control[:status], {}, [exception_control[:message]]]
36
+ else
37
+ logger.debug('Re-throwing original error', exception)
38
+ raise exception
39
+ end
40
+ end
41
+
42
+ # Is the given exception one raised by our Protect code?
43
+ #
44
+ # @param exception [Exception]
45
+ # @return [Boolean]
46
+ def security_exception? exception
47
+ exception.is_a?(Contrast::SecurityException) || exception.message&.include?(SECURITY_EXCEPTION_MARKER)
48
+ end
49
+
50
+ # As we deprecate support to prepare to remove dead code, we need to inform our users still relying on the now
51
+ # deprecated and soon to be removed functionality. This method handles doing that by leveraging the standard
52
+ # Kernel#warn approach
53
+ def inform_deprecations
54
+ # Ruby 2.5 is currently in security maintenance, meaning int is only receiving updates for security issues. It
55
+ # will move to eol on 31 March 2021. As such, we can remove support for it in Q3. We'll begin the deprecation
56
+ # warnings now so that customers have time to reach out if they'll be impacted.
57
+ # TODO: RUBY-715 remove this part of the method, leaving it empty if there are no other deprecations, when we
58
+ # drop 2.5 support.
59
+ return unless RUBY_VERSION < '2.6.0'
60
+
61
+ Kernel.warn('[Contrast Security] [DEPRECATION] Support for Ruby 2.5 will be removed in April 2021. '\
62
+ 'Please contact Customer Support prior if you require continued support.')
63
+ end
64
+
65
+ # Displays Telemetry disclaimer if Telemetry is enabled.
66
+ # if .telemetry file doesn't exist we create one and then show the disclaimer.
67
+ # if the file already exists we do nothing.
68
+ def telemetry_disclaimer
69
+ return unless Contrast::Agent::Telemetry.enabled?
70
+ return unless Contrast::Utils::Telemetry.create_telemetry_file
71
+
72
+ logger.info Contrast::Utils::Telemetry.disclaimer
73
+ $stdout.print Contrast::Utils::Telemetry.disclaimer
74
+ true
75
+ end
76
+
77
+ def application_code env
78
+ logger.trace_with_time('application') do
79
+ app.call(env)
80
+ end
81
+ rescue Contrast::SecurityException => e
82
+ logger.trace('Security Exception raised during application lifecycle to prevent an attack', e)
83
+ raise e
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,158 @@
1
+ # Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ require 'net/http'
5
+ require 'contrast/components/logger'
6
+ require 'contrast/utils/object_share'
7
+ require 'socket'
8
+
9
+ module Contrast
10
+ module Utils
11
+ # This module creates a Net::HTTP client base to be used by different services
12
+ # All HTTP clients reporting to Telemetry or TS should inherit from this
13
+ class NetHttpBase
14
+ include Contrast::Components::Logger::InstanceMethods
15
+ # This method initializes the Net::HTTP client we'll need. it will validate
16
+ # the connection and make the first request. If connection is valid and response
17
+ # is available then the open connection is returned.
18
+ #
19
+ # @param service_name [String] Name of service used in logging messages
20
+ # @param url [String]
21
+ # @param use_proxy [Boolean] flag used to indicate proxy connections [default = false]
22
+ # @param use_custom_cert [Boolean] flag used to indicate whether the client is to use
23
+ # self signed certificates provided by config [default = false]
24
+ # @return [Net::HTTP, nil] Return open connection or nil
25
+ def initialize_connection service_name, url, use_proxy = false, use_custom_cert = false
26
+ return unless url
27
+
28
+ addr = URI(url)
29
+ # the proxy is enabled only if there is provided url even if the enable is set to true
30
+ return if addr.host.nil? || addr.port.nil? || addr.scheme != 'https'
31
+
32
+ proxy_addr = URI(Contrast::API.proxy_url) if proxy_enabled?
33
+ net_http_client = initialize_client addr, proxy_addr, use_proxy, use_custom_cert
34
+ return if net_http_client.nil?
35
+
36
+ net_http_client.start
37
+ return unless net_http_client.started?
38
+
39
+ logger.warn("Starting #{ service_name } connection test")
40
+ return unless connection_verified? net_http_client
41
+
42
+ net_http_client
43
+ rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, OpenSSL::SSL::SSLError => e
44
+ logger.warn("#{ service_name } connection failed", e.message)
45
+ nil
46
+ end
47
+
48
+ # Validates connection with assigned domain.
49
+ # If connection is running, SSL certificate of the endpoint is valid, Ip address is resolvable
50
+ # and response is received without peer's reset or refuse of connection,
51
+ # then validation returns true. Error handling is in place so that the work of the agent will continue as
52
+ # normal without Telemetry.
53
+ #
54
+ # @param client [Net::HTTP]
55
+ # @return [Boolean] true | false
56
+ def connection_verified? client
57
+ return @_connection_verified unless @_connection_verified.nil?
58
+ return false if client.nil?
59
+
60
+ # Before RUBY 2.7 there is no #ipaddr
61
+ ipaddr = if RUBY_VERSION < '2.7.0'
62
+ socket = TCPSocket.open(client.address, client.port)
63
+ ipaddr = socket.peeraddr[3]
64
+ socket.close
65
+ ipaddr
66
+ else
67
+ client.ipaddr
68
+ end
69
+ response = client.request(Net::HTTP::Get.new(client.address))
70
+ verify_cert = OpenSSL::SSL.verify_certificate_identity(client.peer_cert, client.address)
71
+ resolved = resolved? client.address, ipaddr
72
+ @_connection_verified = if resolved && response && verify_cert
73
+ true
74
+ else
75
+ false
76
+ end
77
+ rescue OpenSSL::SSL::SSLError, Resolv::ResolvError, Errno::ECONNRESET, Errno::ECONNREFUSED,
78
+ Errno::ETIMEDOUT, Errno::ESHUTDOWN, Errno::EHOSTDOWN, Errno::EHOSTUNREACH, Errno::EISCONN,
79
+ Errno::ECONNABORTED, Errno::ENETRESET, Errno::ENETUNREACH => e
80
+
81
+ logger.warn("#{ service_name } connection failed", e.message)
82
+ false
83
+ end
84
+
85
+ private
86
+
87
+ # Resolves the address of the assigned domain to array of corresponding IPs (if more than one)
88
+ # and runs a matcher to see if current connection IP is in the list.
89
+ # This is called within #verify_connection, if called on it's own there will be no
90
+ # error handling.
91
+ #
92
+ # @param address [String] Human friendly address of assigned domain
93
+ # @param ipaddr [String] Machine friendly IP address of the assigned domain
94
+ # @return[Boolean] true if both addresses are resolved | false if one of the addresses
95
+ # is non-resolvable
96
+ def resolved? address, ipaddr
97
+ return @_resolved unless @_resolved.nil?
98
+
99
+ @_resolved = if (addresses = Resolv.getaddresses address)
100
+ addresses.any? { |addr| addr.include?(ipaddr) }
101
+ else
102
+ false
103
+ end
104
+ end
105
+
106
+ # if the configuration for the use of self-signed certificates is enabled
107
+ # and required for this client then assign the files and keys to the client
108
+ #
109
+ # @param client [Net::HTTP]
110
+ def assign_cert client
111
+ if Contrast::API.certification_ca_file
112
+ client.ca_file = OpenSSL::X509::Certificate.new(File.read(Contrast::API.certification_ca_file)).to_s
113
+ elsif Contrast::API.certification_cert_file
114
+ client.cert = OpenSSL::X509::Certificate.new(File.read(Contrast::API.certification_cert_file)).to_s
115
+ elsif Contrast::API.certification_key_file
116
+ client.key = OpenSSL::PKey::RSA.new(File.read(Contrast::API.certification_key_file)).to_s
117
+ end
118
+ rescue Errno::ENOENT => e
119
+ logger.error('Custom certificates failed', e.message)
120
+ end
121
+
122
+ # sets default setting for client validation of certificates and
123
+ # timeout options
124
+ #
125
+ # @param addr [URI::Generic] uri of assigned domain
126
+ # @param proxy_addr [URI::Generic | nil] uri of proxy
127
+ # @param use_proxy [Boolean] flag used to indicate proxy connections [default = false]
128
+ # @param use_custom_cert [Boolean] flag used to indicate whether the client is to use
129
+ # self signed certificates provided by config [default = false]
130
+ # @return [Net::HTTP]
131
+ def initialize_client addr, proxy_addr, use_proxy, use_custom_cert
132
+ initialize_client = if proxy_enabled? && use_proxy
133
+ Net::HTTP.new(addr.host, nil, proxy_addr&.host, proxy_addr&.port)
134
+ else
135
+ Net::HTTP.new(addr.host, addr.port)
136
+ end
137
+ assign_cert(initialize_client) if use_custom_cert && Contrast::API.certification_enabled?
138
+ initialize_client.use_ssl = true
139
+ initialize_client.verify_mode = OpenSSL::SSL::VERIFY_PEER
140
+ initialize_client.verify_depth = 5
141
+ # open connection timeout in ms
142
+ # if connection reaches timeout this will produce Net::OpenTimeout error
143
+ initialize_client.open_timeout = 10
144
+ # if we can't read the response or a chunk within time this will cause a
145
+ # Net::ReadTimeout error when the request is made
146
+ initialize_client.read_timeout = 10
147
+ initialize_client
148
+ end
149
+
150
+ # Check if proxy is enabled
151
+ #
152
+ # @return @_proxy_enabled [Boolean] True if proxy is enabled and url is present else false
153
+ def proxy_enabled?
154
+ @_proxy_enabled ||= Contrast::API.proxy_enabled? && !Contrast::API.proxy_url.nil? if @_proxy_enabled.nil?
155
+ end
156
+ end
157
+ end
158
+ end
@@ -30,6 +30,7 @@ module Contrast
30
30
  SEMICOLON = ';'
31
31
  SINGLE_QUOTE = '\''
32
32
  SLASH = '/'
33
+ SPACE = ' '
33
34
  UNDERSCORE = '_'
34
35
  DOUBLE_UNDERSCORE = '__'
35
36
  AT = '@'
@@ -2,6 +2,7 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  require 'contrast/components/scope'
5
+ require 'cs__os_information/cs__os_information'
5
6
 
6
7
  module Contrast
7
8
  module Utils
@@ -31,6 +32,28 @@ module Contrast
31
32
  zombie_pid_list.split("\n")
32
33
  end
33
34
  end
35
+
36
+ # Check current OS type
37
+ # returns true if check is correct or false if not
38
+ def windows?
39
+ (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
40
+ end
41
+
42
+ def mac?
43
+ RUBY_PLATFORM.include? 'darwin'
44
+ end
45
+
46
+ def unix?
47
+ !windows?
48
+ end
49
+
50
+ def linux?
51
+ unix? and !mac?
52
+ end
53
+
54
+ def jruby?
55
+ RUBY_ENGINE == 'jruby'
56
+ end
34
57
  end
35
58
  end
36
59
  end
@@ -0,0 +1,232 @@
1
+ # Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ module Contrast
5
+ module Utils
6
+ module Patching
7
+ # This module will include all methods for different patch applies from Patch module
8
+ # and some other module methods from the same place, so we can ease the main module
9
+ module PatchUtils
10
+ # Method to choose which replaced return from the post_patch to
11
+ # actually return
12
+ #
13
+ # @param propagated_ret [Object, nil] The replaced return from the
14
+ # propagation patch.
15
+ # @param source_ret [Object, nil] The replaced return from the
16
+ # source patch.
17
+ # @param ret [Object, nil] The original return of the patched
18
+ # method.
19
+ # @return [Object, nil] The thing to return from the post patch.
20
+ def handle_return propagated_ret, source_ret, ret
21
+ safe_return = propagated_ret || source_ret || ret
22
+ safe_return.rewind if Contrast::Utils::IOUtil.should_rewind?(safe_return)
23
+ safe_return
24
+ end
25
+
26
+ # Given a module and method, construct an expected name for the
27
+ # alias by which Contrast will reference the original.
28
+ #
29
+ # @param patched_class [Module] the module being patched
30
+ # @param patched_method [Symbol] the method being patched
31
+ # @return [Symbol]
32
+ def build_method_name patched_class, patched_method
33
+ (Contrast::Utils::ObjectShare::CONTRAST_PATCHED_METHOD_START +
34
+ patched_class.cs__name.gsub('::', '_').downcase +
35
+ Contrast::Utils::ObjectShare::UNDERSCORE +
36
+ patched_method.to_s).to_sym
37
+ end
38
+
39
+ # Given a method, return a symbol in the format
40
+ # <method_start>_unbound_<method_name>
41
+ def build_unbound_method_name patcher_method
42
+ (Contrast::Utils::ObjectShare::CONTRAST_PATCHED_METHOD_START +
43
+ 'unbound' +
44
+ Contrast::Utils::ObjectShare::UNDERSCORE +
45
+ patcher_method.to_s).to_sym
46
+ end
47
+
48
+ # ===== PATCH APPLIERS =====
49
+ # THIS IS CALLED FROM C. Do not change the signature lightly.
50
+ #
51
+ # This method functions to call the infilter methods from our
52
+ # patches, allowing for analysis and reporting at the point just
53
+ # before the patched code is invoked.
54
+ #
55
+ # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
56
+ # Mapping of the triggers on the given method.
57
+ # @param method [Symbol] The method into which we're patching
58
+ # @param exception [StandardError] Any exception raised during the
59
+ # call of the patched method.
60
+ # @param object [Object] The object on which the method is invoked,
61
+ # typically what would be returned by self.
62
+ # @param args [Array<Object>] The arguments passed to the method
63
+ # being invoked.
64
+ def apply_pre_patch method_policy, method, exception, object, args
65
+ apply_protect(method_policy, method, exception, object, args)
66
+ apply_inventory(method_policy, method, exception, object, args)
67
+ rescue Contrast::SecurityException => e
68
+ # We were told to block something, so we gotta. Don't catch this
69
+ # one, let it get back to our Middleware or even all the way out to
70
+ # the framework
71
+ raise e
72
+ rescue StandardError => e
73
+ # Anything else was our bad and we gotta catch that to allow for
74
+ # normal application flow
75
+ logger.error('Unable to apply pre patch to method.', e)
76
+ rescue Exception => e # rubocop:disable Lint/RescueException
77
+ # This is something like NoMemoryError that we can't
78
+ # hope to handle. Nonetheless, shouldn't leak scope.
79
+ exit_contrast_scope!
80
+ raise e
81
+ end
82
+
83
+ # THIS IS CALLED FROM C. Do not change the signature lightly.
84
+ #
85
+ # This method functions to call the infilter methods from our
86
+ # patches, allowing for analysis and reporting at the point just
87
+ # after the patched code is invoked
88
+ #
89
+ # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
90
+ # Mapping of the triggers on the given method.
91
+ # @param preshift [Contrast::Agent::Assess::PreShift] The capture
92
+ # of the state of the code just prior to the invocation of the
93
+ # patched method.
94
+ # @param object [Object] The object on which the method was
95
+ # invoked, typically what would be returned by self.
96
+ # @param ret [Object] The return of the method that was invoked.
97
+ # @param args [Array<Object>] The arguments passed to the method
98
+ # being invoked.
99
+ # @param block [Proc] The block passed to the method that was
100
+ # invoked.
101
+ def apply_post_patch method_policy, preshift, object, ret, args, block
102
+ apply_assess(method_policy, preshift, object, ret, args, block)
103
+ rescue StandardError => e
104
+ logger.error('Unable to apply post patch to method.', e)
105
+ end
106
+
107
+ # Apply the Protect patch which applies to the given method.
108
+ #
109
+ # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
110
+ # Mapping of the triggers on the given method.
111
+ # @param method [Symbol] The method into which we're patching
112
+ # @param exception [StandardError] Any exception raised during the
113
+ # call of the patched method.
114
+ # @param object [Object] The object on which the method is invoked,
115
+ # typically what would be returned by self.
116
+ # @param args [Array<Object>] The arguments passed to the method
117
+ # being invoked.
118
+ def apply_protect method_policy, method, exception, object, args
119
+ return unless ::Contrast::AGENT.enabled?
120
+ return unless ::Contrast::PROTECT.enabled?
121
+
122
+ apply_trigger_only(method_policy&.protect_node, method, exception, object, args)
123
+ end
124
+
125
+ # Apply the Inventory patch which applies to the given method.
126
+ #
127
+ # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
128
+ # Mapping of the triggers on the given method.
129
+ # @param method [Symbol] The method into which we're patching
130
+ # @param exception [StandardError] Any exception raised during the
131
+ # call of the patched method.
132
+ # @param object [Object] The object on which the method is invoked,
133
+ # typically what would be returned by self.
134
+ # @param args [Array<Object>] The arguments passed to the method
135
+ # being invoked.
136
+ def apply_inventory method_policy, method, exception, object, args
137
+ return unless ::Contrast::INVENTORY.enabled?
138
+
139
+ apply_trigger_only(method_policy&.inventory_node, method, exception, object, args)
140
+ end
141
+
142
+ # Apply the Assess patches which apply to the given method.
143
+ #
144
+ # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
145
+ # Mapping of the triggers on the given method.
146
+ # @param preshift [Contrast::Agent::Assess::PreShift] The capture
147
+ # of the state of the code just prior to the invocation of the
148
+ # patched method.
149
+ # @param object [Object] The object on which the method was
150
+ # invoked, typically what would be returned by self.
151
+ # @param ret [Object] The return of the method that was invoked.
152
+ # @param args [Array<Object>] The arguments passed to the method
153
+ # being invoked.
154
+ # @param block [Proc] The block passed to the method that was
155
+ # invoked.
156
+ def apply_assess method_policy, preshift, object, ret, args, block
157
+ source_ret = nil
158
+ propagated_ret = nil
159
+ return ret unless method_policy && ::Contrast::ASSESS.enabled?
160
+
161
+ current_context = Contrast::Agent::REQUEST_TRACKER.current
162
+ return ret if current_context && !current_context.analyze_request?
163
+
164
+ trigger_node = method_policy.trigger_node
165
+ if trigger_node
166
+ Contrast::Agent::Assess::Policy::TriggerMethod.apply_trigger_rule(trigger_node, object, ret, args)
167
+ end
168
+ if method_policy.source_node
169
+ # If we were given a frozen return, and it was the target of a
170
+ # source, and we have frozen sources enabled, we'll need to
171
+ # replace the return. Note, this is not the default case.
172
+ source_ret = Contrast::Agent::Assess::Policy::SourceMethod.source_patchers(method_policy, object, ret, args)
173
+ end
174
+ if method_policy.propagation_node
175
+ propagated_ret = Contrast::Agent::Assess::Policy::PropagationMethod.apply_propagation(
176
+ method_policy,
177
+ preshift,
178
+ object,
179
+ source_ret || ret,
180
+ args,
181
+ block)
182
+ end
183
+ handle_return(propagated_ret, source_ret, ret)
184
+ rescue StandardError => e
185
+ logger.error('Unable to assess method call.', e)
186
+ handle_return(propagated_ret, source_ret, ret)
187
+ rescue Exception => e # rubocop:disable Lint/RescueException
188
+ logger.error('Unable to assess method call.', e)
189
+ handle_return(propagated_ret, source_ret, ret)
190
+ raise e
191
+ end
192
+
193
+ # Generic invocation of the Inventory or Protect patch which apply
194
+ # to the given method.
195
+ #
196
+ # @param trigger_node [Contrast::Agent::Inventory::Policy::TriggerNode]
197
+ # Mapping of the specific trigger on the given method.
198
+ # @param method [Symbol] The method into which we're patching
199
+ # @param exception [StandardError] Any exception raised during the
200
+ # call of the patched method.
201
+ # @param object [Object] The object on which the method is invoked,
202
+ # typically what would be returned by self.
203
+ # @param args [Array<Object>] The arguments passed to the method
204
+ # being invoked.
205
+ def apply_trigger_only trigger_node, method, exception, object, args
206
+ return unless trigger_node
207
+
208
+ # If that rule only applies in the case of an exception being
209
+ # thrown and there's no exception here, move along, or vice versa
210
+ return if trigger_node.on_exception && !exception
211
+ return if !trigger_node.on_exception && exception
212
+
213
+ # Each patch has an applicator that handles logic for it. Think
214
+ # of this as being similar to propagator actions, most closely
215
+ # resembling CUSTOM - they all have a common interface but their
216
+ # own logic based on what's in the method(s) they've been patched
217
+ # into.
218
+ # Each patch also knows the method of its applicator. Some
219
+ # things, like AppliesXxeRule, have different methods depending
220
+ # on the library patched. This lets us handle the boilerplate of
221
+ # patching while still allowing for custom handling of the
222
+ # methods.
223
+ applicator_method = trigger_node.applicator_method
224
+ # By calling send like this, we can reuse all the patching.
225
+ # We `send` to the given method of the given class
226
+ # (applicator) since they all accept the same inputs
227
+ trigger_node.applicator.send(applicator_method, method, exception, trigger_node.properties, object, args)
228
+ end
229
+ end
230
+ end
231
+ end
232
+ end
@@ -0,0 +1,54 @@
1
+ # Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ module Contrast
5
+ module Utils
6
+ module Patching
7
+ # This module will include patch methods from Patcher module
8
+ # in case of need to add new logic to the Patcher
9
+ # please do it here
10
+ module PatcherUtils
11
+ # This method is called by TracePointHook to instrument a specific class during a require
12
+ # or eval of dynamic class definition
13
+ def patch_specific_module mod
14
+ with_contrast_scope do
15
+ mod_name = mod.cs__name
16
+ return unless Contrast::Utils::ClassUtil.truly_defined?(mod_name)
17
+ return if ::Contrast::AGENT.skip_instrumentation?(mod_name)
18
+
19
+ load_patches_for_module(mod_name)
20
+
21
+ return if all_module_names.none?(mod_name)
22
+
23
+ module_data = Contrast::Agent::ModuleData.new(mod, mod_name)
24
+ patch_into_module(module_data)
25
+ all_module_names.delete(mod_name) if status_type.get_status(mod).patched?
26
+ rescue StandardError => e
27
+ logger.error('Unable to patch module', e, module: mod_name)
28
+ end
29
+ end
30
+
31
+ # We did it, team. We found a patcher(s) that applies to the given
32
+ # class (or module) and the given method. Time to do some tracking.
33
+ #
34
+ # @param mod [Module] the module in which the patch should be
35
+ # placed.
36
+ # @param methods [Array(Symbol)] all the instance or singleton
37
+ # methods in this mod.
38
+ # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
39
+ # the policy that applies to the given method_name.
40
+ # @return [Boolean] if patched, either by this invocation or a
41
+ # previous, or not
42
+ def patch_method mod, methods, method_policy
43
+ return false unless methods&.any? # don't even build the name if there are no methods
44
+
45
+ if Contrast::Utils::ClassUtil.prepended_method?(mod, method_policy)
46
+ Contrast::Agent::Patching::Policy::Patch.instrument_with_prepend(mod, method_policy)
47
+ else
48
+ Contrast::Agent::Patching::Policy::Patch.instrument_with_alias(mod, methods, method_policy)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,88 @@
1
+ # Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ module Contrast
5
+ module Utils
6
+ # used in Contrast::Agent::Request
7
+ module RequestUtils
8
+ # Return a flattened hash of params with realized paths for keys, in
9
+ # addition to a separate, valueless, entry for each nest key.
10
+ # See RUBY-621 for more details.
11
+ # { key : { nested_key : ['x','y','z' ] } }
12
+ # becomes
13
+ # {
14
+ # key[nested_key][0] : 'x'
15
+ # key[nested_key][1] : 'y'
16
+ # key[nested_key][2] : 'z'
17
+ # key : ''
18
+ # nested_key : ''
19
+ # }
20
+ def normalize_params val, prefix: nil
21
+ # In non-recursive invocations, val should always be a Hash
22
+ # (rather than breaking this out into two methods)
23
+ case val
24
+ when Tempfile
25
+ # Skip if it's the auto-generated value from rails when it handles
26
+ # file uploads. The file name will still be sent to SR for analysis.
27
+ {}
28
+ when Hash
29
+ res = val.each_with_object({}) do |(k, v), hash|
30
+ k = Contrast::Utils::StringUtils.force_utf8(k)
31
+ nested_prefix = prefix.nil? ? k : "#{ prefix }[#{ k }]"
32
+ hash[k] = Contrast::Utils::ObjectShare::EMPTY_STRING
33
+ hash.merge! normalize_params(v, prefix: nested_prefix)
34
+ end
35
+ res[prefix] = Contrast::Utils::ObjectShare::EMPTY_STRING if prefix
36
+ res
37
+ when Enumerable
38
+ idx = 0
39
+ res = {}
40
+ while idx < val.length
41
+ res.merge! normalize_params(val[idx], prefix: "#{ prefix }[#{ idx }]")
42
+ idx += 1
43
+ end
44
+ res[prefix] = Contrast::Utils::ObjectShare::EMPTY_STRING if prefix
45
+ res
46
+ else
47
+ { prefix => Contrast::Utils::StringUtils.force_utf8(val) }
48
+ end
49
+ end
50
+
51
+ def read_body body
52
+ return body if body.is_a?(String)
53
+
54
+ begin
55
+ can_rewind = Contrast::Utils::DuckUtils.quacks_to?(body, :rewind)
56
+ # if we are after a middleware that failed to rewind
57
+ body.rewind if can_rewind
58
+ body.read
59
+ rescue StandardError => e
60
+ logger.error('Error in attempt to read body', message: e.message)
61
+ logger.trace('With Stack', e)
62
+ body.to_s
63
+ ensure
64
+ # be a good citizen and rewind
65
+ body.rewind if can_rewind
66
+ end
67
+ end
68
+
69
+ def traverse_parsed_multipart multipart_data, current_names
70
+ return current_names unless multipart_data
71
+
72
+ multipart_data.each_value do |data_value|
73
+ next unless data_value.is_a?(Hash)
74
+
75
+ tempfile = data_value[:tempfile]
76
+ if tempfile.nil?
77
+ traverse_parsed_multipart(data_value, current_names)
78
+ else
79
+ name = data_value[:name].to_s
80
+ file_name = data_value[:filename].to_s
81
+ current_names[name] = file_name
82
+ end
83
+ end
84
+ current_names
85
+ end
86
+ end
87
+ end
88
+ end