contrast-agent 4.9.1 → 4.13.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (140) hide show
  1. checksums.yaml +4 -4
  2. data/.rspec +0 -1
  3. data/.rspec_parallel +6 -0
  4. data/ext/cs__assess_module/cs__assess_module.c +48 -0
  5. data/ext/cs__assess_module/cs__assess_module.h +7 -0
  6. data/ext/cs__common/cs__common.c +24 -7
  7. data/ext/cs__common/cs__common.h +12 -2
  8. data/ext/cs__contrast_patch/cs__contrast_patch.c +48 -12
  9. data/ext/cs__contrast_patch/cs__contrast_patch.h +5 -4
  10. data/ext/cs__os_information/cs__os_information.c +31 -0
  11. data/ext/cs__os_information/cs__os_information.h +7 -0
  12. data/ext/{cs__protect_kernel → cs__os_information}/extconf.rb +0 -0
  13. data/lib/contrast/agent/assess/contrast_event.rb +1 -2
  14. data/lib/contrast/agent/assess/contrast_object.rb +1 -4
  15. data/lib/contrast/agent/assess/finalizers/hash.rb +0 -1
  16. data/lib/contrast/agent/assess/policy/dynamic_source_factory.rb +2 -0
  17. data/lib/contrast/agent/assess/policy/patcher.rb +0 -1
  18. data/lib/contrast/agent/assess/policy/policy_scanner.rb +0 -2
  19. data/lib/contrast/agent/assess/policy/preshift.rb +29 -12
  20. data/lib/contrast/agent/assess/policy/propagation_method.rb +71 -142
  21. data/lib/contrast/agent/assess/policy/propagation_node.rb +4 -4
  22. data/lib/contrast/agent/assess/policy/propagator/database_write.rb +2 -2
  23. data/lib/contrast/agent/assess/policy/propagator/match_data.rb +31 -11
  24. data/lib/contrast/agent/assess/policy/propagator/remove.rb +4 -9
  25. data/lib/contrast/agent/assess/policy/propagator/split.rb +3 -2
  26. data/lib/contrast/agent/assess/policy/propagator/substitution.rb +1 -0
  27. data/lib/contrast/agent/assess/policy/rewriter_patch.rb +0 -1
  28. data/lib/contrast/agent/assess/policy/source_method.rb +15 -88
  29. data/lib/contrast/agent/assess/policy/trigger/xpath.rb +0 -1
  30. data/lib/contrast/agent/assess/policy/trigger_method.rb +45 -172
  31. data/lib/contrast/agent/assess/policy/trigger_node.rb +52 -19
  32. data/lib/contrast/agent/assess/property/evented.rb +2 -1
  33. data/lib/contrast/agent/assess/property/tagged.rb +15 -132
  34. data/lib/contrast/agent/assess/rule/provider/hardcoded_value_rule.rb +0 -1
  35. data/lib/contrast/agent/deadzone/policy/policy.rb +6 -0
  36. data/lib/contrast/agent/disable_reaction.rb +1 -1
  37. data/lib/contrast/agent/exclusion_matcher.rb +0 -4
  38. data/lib/contrast/agent/inventory/database_config.rb +117 -0
  39. data/lib/contrast/agent/inventory/dependency_usage_analysis.rb +7 -5
  40. data/lib/contrast/agent/inventory/policy/datastores.rb +2 -2
  41. data/lib/contrast/agent/metric_telemetry_event.rb +26 -0
  42. data/lib/contrast/agent/middleware.rb +23 -0
  43. data/lib/contrast/agent/patching/policy/after_load_patch.rb +3 -0
  44. data/lib/contrast/agent/patching/policy/after_load_patcher.rb +17 -12
  45. data/lib/contrast/agent/patching/policy/method_policy.rb +54 -9
  46. data/lib/contrast/agent/patching/policy/module_policy.rb +2 -4
  47. data/lib/contrast/agent/patching/policy/patch.rb +42 -238
  48. data/lib/contrast/agent/patching/policy/patch_status.rb +3 -7
  49. data/lib/contrast/agent/patching/policy/patcher.rb +10 -49
  50. data/lib/contrast/agent/protect/policy/applies_no_sqli_rule.rb +1 -1
  51. data/lib/contrast/agent/protect/rule/no_sqli.rb +7 -53
  52. data/lib/contrast/agent/protect/rule/sql_sample_builder.rb +137 -0
  53. data/lib/contrast/agent/protect/rule/sqli.rb +7 -70
  54. data/lib/contrast/agent/reaction_processor.rb +1 -1
  55. data/lib/contrast/agent/request.rb +9 -4
  56. data/lib/contrast/agent/request_context.rb +51 -33
  57. data/lib/contrast/agent/request_handler.rb +7 -3
  58. data/lib/contrast/agent/rule_set.rb +2 -4
  59. data/lib/contrast/agent/scope.rb +32 -20
  60. data/lib/contrast/agent/startup_metrics_telemetry_event.rb +71 -0
  61. data/lib/contrast/agent/static_analysis.rb +5 -3
  62. data/lib/contrast/agent/telemetry.rb +129 -0
  63. data/lib/contrast/agent/telemetry_event.rb +34 -0
  64. data/lib/contrast/agent/thread_watcher.rb +43 -14
  65. data/lib/contrast/agent/tracepoint_hook.rb +16 -3
  66. data/lib/contrast/agent/version.rb +1 -1
  67. data/lib/contrast/agent.rb +6 -1
  68. data/lib/contrast/api/communication/messaging_queue.rb +12 -6
  69. data/lib/contrast/api/communication/service_lifecycle.rb +4 -1
  70. data/lib/contrast/api/communication/socket_client.rb +4 -4
  71. data/lib/contrast/api/decorators/agent_startup.rb +4 -4
  72. data/lib/contrast/api/decorators/application_startup.rb +6 -5
  73. data/lib/contrast/api/decorators/route_coverage.rb +24 -1
  74. data/lib/contrast/components/agent.rb +5 -2
  75. data/lib/contrast/components/api.rb +34 -0
  76. data/lib/contrast/components/app_context.rb +24 -0
  77. data/lib/contrast/components/assess.rb +13 -3
  78. data/lib/contrast/components/base.rb +2 -2
  79. data/lib/contrast/components/config.rb +91 -11
  80. data/lib/contrast/components/contrast_service.rb +10 -2
  81. data/lib/contrast/components/logger.rb +13 -8
  82. data/lib/contrast/components/scope.rb +9 -28
  83. data/lib/contrast/config/api_configuration.rb +22 -0
  84. data/lib/contrast/config/assess_configuration.rb +1 -0
  85. data/lib/contrast/config/base_configuration.rb +14 -6
  86. data/lib/contrast/config/env_variables.rb +25 -0
  87. data/lib/contrast/config/root_configuration.rb +1 -0
  88. data/lib/contrast/config/service_configuration.rb +2 -1
  89. data/lib/contrast/config.rb +1 -0
  90. data/lib/contrast/configuration.rb +22 -15
  91. data/lib/contrast/extension/assess/array.rb +1 -11
  92. data/lib/contrast/extension/assess/eval_trigger.rb +0 -20
  93. data/lib/contrast/extension/assess/fiber.rb +0 -11
  94. data/lib/contrast/extension/assess/hash.rb +0 -10
  95. data/lib/contrast/extension/assess/kernel.rb +1 -10
  96. data/lib/contrast/extension/assess/marshal.rb +3 -11
  97. data/lib/contrast/extension/assess/regexp.rb +0 -11
  98. data/lib/contrast/extension/assess/string.rb +1 -26
  99. data/lib/contrast/extension/extension.rb +61 -0
  100. data/lib/contrast/framework/grape/support.rb +174 -0
  101. data/lib/contrast/framework/manager.rb +56 -18
  102. data/lib/contrast/framework/rack/support.rb +1 -1
  103. data/lib/contrast/framework/rails/patch/action_controller_live_buffer.rb +9 -6
  104. data/lib/contrast/framework/rails/patch/assess_configuration.rb +0 -1
  105. data/lib/contrast/framework/rails/patch/support.rb +35 -30
  106. data/lib/contrast/framework/rails/railtie.rb +1 -1
  107. data/lib/contrast/framework/rails/rewrite/active_record_named.rb +1 -0
  108. data/lib/contrast/framework/rails/support.rb +60 -13
  109. data/lib/contrast/framework/sinatra/support.rb +1 -1
  110. data/lib/contrast/logger/application.rb +4 -0
  111. data/lib/contrast/logger/log.rb +89 -15
  112. data/lib/contrast/utils/assess/propagation_method_utils.rb +129 -0
  113. data/lib/contrast/utils/assess/property/tagged_utils.rb +142 -0
  114. data/lib/contrast/utils/assess/source_method_utils.rb +83 -0
  115. data/lib/contrast/utils/assess/trigger_method_utils.rb +138 -0
  116. data/lib/contrast/utils/class_util.rb +58 -44
  117. data/lib/contrast/utils/exclude_key.rb +20 -0
  118. data/lib/contrast/utils/io_util.rb +43 -35
  119. data/lib/contrast/utils/lru_cache.rb +45 -0
  120. data/lib/contrast/utils/metrics_hash.rb +59 -0
  121. data/lib/contrast/utils/os.rb +23 -0
  122. data/lib/contrast/utils/patching/policy/patch_utils.rb +232 -0
  123. data/lib/contrast/utils/patching/policy/patcher_utils.rb +54 -0
  124. data/lib/contrast/utils/requests_client.rb +150 -0
  125. data/lib/contrast/utils/ruby_ast_rewriter.rb +16 -13
  126. data/lib/contrast/utils/tag_util.rb +2 -1
  127. data/lib/contrast/utils/telemetry.rb +78 -0
  128. data/lib/contrast/utils/telemetry_identifier.rb +137 -0
  129. data/lib/contrast.rb +19 -1
  130. data/resources/assess/policy.json +208 -7
  131. data/resources/deadzone/policy.json +91 -0
  132. data/ruby-agent.gemspec +12 -2
  133. data/service_executables/VERSION +1 -1
  134. data/service_executables/linux/contrast-service +0 -0
  135. data/service_executables/mac/contrast-service +0 -0
  136. metadata +102 -18
  137. data/ext/cs__protect_kernel/cs__protect_kernel.c +0 -47
  138. data/ext/cs__protect_kernel/cs__protect_kernel.h +0 -12
  139. data/lib/contrast/extension/protect/kernel.rb +0 -39
  140. data/lib/contrast/utils/inventory_util.rb +0 -113
@@ -4,6 +4,7 @@
4
4
  require 'monitor'
5
5
  require 'contrast/components/logger'
6
6
  require 'contrast/components/scope'
7
+ require 'contrast/utils/patching/policy/patch_utils'
7
8
 
8
9
  require 'contrast/agent'
9
10
  require 'contrast/logger/log'
@@ -32,6 +33,8 @@ module Contrast
32
33
  # provides a map for which methods our renamed functions need to call
33
34
  # and how.
34
35
  module Patch
36
+ extend Contrast::Utils::Patching::PatchUtils
37
+
35
38
  class << self
36
39
  include Contrast::Agent::Assess::Policy::SourceMethod
37
40
  include Contrast::Agent::Assess::Policy::PropagationMethod
@@ -57,226 +60,6 @@ module Contrast
57
60
  end
58
61
  end
59
62
 
60
- # THIS IS CALLED FROM C. Do not change the signature lightly.
61
- #
62
- # This method functions to call the infilter methods from our
63
- # patches, allowing for analysis and reporting at the point just
64
- # before the patched code is invoked.
65
- #
66
- # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
67
- # Mapping of the triggers on the given method.
68
- # @param method [Symbol] The method into which we're patching
69
- # @param exception [StandardError] Any exception raised during the
70
- # call of the patched method.
71
- # @param object [Object] The object on which the method is invoked,
72
- # typically what would be returned by self.
73
- # @param args [Array<Object>] The arguments passed to the method
74
- # being invoked.
75
- def apply_pre_patch method_policy, method, exception, object, args
76
- apply_protect(method_policy, method, exception, object, args)
77
- apply_inventory(method_policy, method, exception, object, args)
78
- rescue Contrast::SecurityException => e
79
- # We were told to block something, so we gotta. Don't catch this
80
- # one, let it get back to our Middleware or even all the way out to
81
- # the framework
82
- raise e
83
- rescue StandardError => e
84
- # Anything else was our bad and we gotta catch that to allow for
85
- # normal application flow
86
- logger.error('Unable to apply pre patch to method.', e)
87
- rescue Exception => e # rubocop:disable Lint/RescueException
88
- # This is something like NoMemoryError that we can't
89
- # hope to handle. Nonetheless, shouldn't leak scope.
90
- exit_contrast_scope!
91
- raise e
92
- end
93
-
94
- # THIS IS CALLED FROM C. Do not change the signature lightly.
95
- #
96
- # This method functions to call the infilter methods from our
97
- # patches, allowing for analysis and reporting at the point just
98
- # after the patched code is invoked
99
- #
100
- # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
101
- # Mapping of the triggers on the given method.
102
- # @param preshift [Contrast::Agent::Assess::PreShift] The capture
103
- # of the state of the code just prior to the invocation of the
104
- # patched method.
105
- # @param object [Object] The object on which the method was
106
- # invoked, typically what would be returned by self.
107
- # @param ret [Object] The return of the method that was invoked.
108
- # @param args [Array<Object>] The arguments passed to the method
109
- # being invoked.
110
- # @param block [Proc] The block passed to the method that was
111
- # invoked.
112
- def apply_post_patch method_policy, preshift, object, ret, args, block
113
- apply_assess(method_policy, preshift, object, ret, args, block)
114
- rescue StandardError => e
115
- logger.error('Unable to apply post patch to method.', e)
116
- end
117
-
118
- # Apply the Protect patch which applies to the given method.
119
- #
120
- # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
121
- # Mapping of the triggers on the given method.
122
- # @param method [Symbol] The method into which we're patching
123
- # @param exception [StandardError] Any exception raised during the
124
- # call of the patched method.
125
- # @param object [Object] The object on which the method is invoked,
126
- # typically what would be returned by self.
127
- # @param args [Array<Object>] The arguments passed to the method
128
- # being invoked.
129
- def apply_protect method_policy, method, exception, object, args
130
- return unless ::Contrast::AGENT.enabled?
131
- return unless ::Contrast::PROTECT.enabled?
132
-
133
- apply_trigger_only(method_policy&.protect_node, method, exception, object, args)
134
- end
135
-
136
- # Apply the Inventory patch which applies to the given method.
137
- #
138
- # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
139
- # Mapping of the triggers on the given method.
140
- # @param method [Symbol] The method into which we're patching
141
- # @param exception [StandardError] Any exception raised during the
142
- # call of the patched method.
143
- # @param object [Object] The object on which the method is invoked,
144
- # typically what would be returned by self.
145
- # @param args [Array<Object>] The arguments passed to the method
146
- # being invoked.
147
- def apply_inventory method_policy, method, exception, object, args
148
- return unless ::Contrast::INVENTORY.enabled?
149
-
150
- apply_trigger_only(method_policy&.inventory_node, method, exception, object, args)
151
- end
152
-
153
- # Apply the Assess patches which apply to the given method.
154
- #
155
- # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
156
- # Mapping of the triggers on the given method.
157
- # @param preshift [Contrast::Agent::Assess::PreShift] The capture
158
- # of the state of the code just prior to the invocation of the
159
- # patched method.
160
- # @param object [Object] The object on which the method was
161
- # invoked, typically what would be returned by self.
162
- # @param ret [Object] The return of the method that was invoked.
163
- # @param args [Array<Object>] The arguments passed to the method
164
- # being invoked.
165
- # @param block [Proc] The block passed to the method that was
166
- # invoked.
167
- def apply_assess method_policy, preshift, object, ret, args, block
168
- source_ret = nil
169
- propagated_ret = nil
170
- return ret unless method_policy && ::Contrast::ASSESS.enabled?
171
-
172
- current_context = Contrast::Agent::REQUEST_TRACKER.current
173
- return ret if current_context && !current_context.analyze_request?
174
-
175
- trigger_node = method_policy.trigger_node
176
- if trigger_node
177
- Contrast::Agent::Assess::Policy::TriggerMethod.apply_trigger_rule(trigger_node, object, ret, args)
178
- end
179
- if method_policy.source_node
180
- # If we were given a frozen return, and it was the target of a
181
- # source, and we have frozen sources enabled, we'll need to
182
- # replace the return. Note, this is not the default case.
183
- source_ret = Contrast::Agent::Assess::Policy::SourceMethod.source_patchers(method_policy, object, ret,
184
- args)
185
- end
186
- if method_policy.propagation_node
187
- propagated_ret = Contrast::Agent::Assess::Policy::PropagationMethod.apply_propagation(
188
- method_policy,
189
- preshift,
190
- object,
191
- source_ret || ret,
192
- args,
193
- block)
194
- end
195
- handle_return(propagated_ret, source_ret, ret)
196
- rescue StandardError => e
197
- logger.error('Unable to assess method call.', e)
198
- handle_return(propagated_ret, source_ret, ret)
199
- rescue Exception => e # rubocop:disable Lint/RescueException
200
- logger.error('Unable to assess method call.', e)
201
- handle_return(propagated_ret, source_ret, ret)
202
- raise e
203
- end
204
-
205
- # Generic invocation of the Inventory or Protect patch which apply
206
- # to the given method.
207
- #
208
- # @param trigger_node [Contrast::Agent::Inventory::Policy::TriggerNode]
209
- # Mapping of the specific trigger on the given method.
210
- # @param method [Symbol] The method into which we're patching
211
- # @param exception [StandardError] Any exception raised during the
212
- # call of the patched method.
213
- # @param object [Object] The object on which the method is invoked,
214
- # typically what would be returned by self.
215
- # @param args [Array<Object>] The arguments passed to the method
216
- # being invoked.
217
- def apply_trigger_only trigger_node, method, exception, object, args
218
- return unless trigger_node
219
-
220
- # If that rule only applies in the case of an exception being
221
- # thrown and there's no exception here, move along, or vice versa
222
- return if trigger_node.on_exception && !exception
223
- return if !trigger_node.on_exception && exception
224
-
225
- # Each patch has an applicator that handles logic for it. Think
226
- # of this as being similar to propagator actions, most closely
227
- # resembling CUSTOM - they all have a common interface but their
228
- # own logic based on what's in the method(s) they've been patched
229
- # into.
230
- # Each patch also knows the method of its applicator. Some
231
- # things, like AppliesXxeRule, have different methods depending
232
- # on the library patched. This lets us handle the boilerplate of
233
- # patching while still allowing for custom handling of the
234
- # methods.
235
- applicator_method = trigger_node.applicator_method
236
- # By calling send like this, we can reuse all the patching.
237
- # We `send` to the given method of the given class
238
- # (applicator) since they all accept the same inputs
239
- trigger_node.applicator.send(applicator_method, method, exception, trigger_node.properties, object, args)
240
- end
241
-
242
- # Method to choose which replaced return from the post_patch to
243
- # actually return
244
- #
245
- # @param propagated_ret [Object, nil] The replaced return from the
246
- # propagation patch.
247
- # @param source_ret [Object, nil] The replaced return from the
248
- # source patch.
249
- # @param ret [Object, nil] The original return of the patched
250
- # method.
251
- # @return [Object, nil] The thing to return from the post patch.
252
- def handle_return propagated_ret, source_ret, ret
253
- safe_return = propagated_ret || source_ret || ret
254
- safe_return.rewind if Contrast::Utils::IOUtil.should_rewind?(safe_return)
255
- safe_return
256
- end
257
-
258
- # Given a module and method, construct an expected name for the
259
- # alias by which Contrast will reference the original.
260
- #
261
- # @param patched_class [Module] the module being patched
262
- # @param patched_method [Symbol] the method being patched
263
- # @return [Symbol]
264
- def build_method_name patched_class, patched_method
265
- (Contrast::Utils::ObjectShare::CONTRAST_PATCHED_METHOD_START +
266
- patched_class.cs__name.gsub('::', '_').downcase +
267
- Contrast::Utils::ObjectShare::UNDERSCORE +
268
- patched_method.to_s).to_sym
269
- end
270
-
271
- # Given a method, return a symbol in the format
272
- # <method_start>_unbound_<method_name>
273
- def build_unbound_method_name patcher_method
274
- (Contrast::Utils::ObjectShare::CONTRAST_PATCHED_METHOD_START +
275
- 'unbound' +
276
- Contrast::Utils::ObjectShare::UNDERSCORE +
277
- patcher_method.to_s).to_sym
278
- end
279
-
280
63
  # @param mod [Module] the module in which the patch should be
281
64
  # placed.
282
65
  # @param methods [Array(Symbol)] all the instance or singleton
@@ -290,6 +73,11 @@ module Contrast
290
73
  # we've already patched this class, don't do it again
291
74
  return true if methods.include?(cs_method_name)
292
75
 
76
+ # that method is within Contrast definition so it should be skipped
77
+ method = mod.instance_method(method_policy.method_name) if method_policy.instance_method
78
+ method = mod.singleton_method(method_policy.method_name) unless method_policy.instance_method
79
+ return true if method.owner <= Contrast
80
+
293
81
  begin
294
82
  contrast_define_method(mod, method_policy, cs_method_name)
295
83
  rescue NameError => e
@@ -338,7 +126,7 @@ module Contrast
338
126
  underlying_method_name = build_unbound_method_name(method_name).to_sym
339
127
 
340
128
  target_module = Module.cs__const_get(target_module_name)
341
-
129
+ target_module = target_module.cs__singleton_class if %i[prepend_singleton prepend].include? impl
342
130
  target_module = target_module.cs__singleton_class if %i[alias_singleton prepend].include? impl
343
131
 
344
132
  visibility = if target_module.private_instance_methods(false).include?(method_name)
@@ -355,6 +143,30 @@ module Contrast
355
143
  ERR
356
144
  end
357
145
 
146
+ reflect_implementation impl, target_module, unbound_method, visibility
147
+ # Ougai::Logger.create_item_with_2args calls Hash#[]=, so we
148
+ # can't invoke this logging method or we'll seg fault as we'd
149
+ # change the method definition mid-call
150
+ # if method_name != :[]= &&
151
+ # Contrast::Agent::Logger.defined!
152
+ # logger.trace(
153
+ # 'Registered C-defined patch',
154
+ # implementation: impl,
155
+ # module: target_mod,
156
+ # method: method_name,
157
+ # visibility: visibility)
158
+ # end
159
+ underlying_method_name
160
+ end
161
+
162
+ # @param impl [Symbol] Strategy for applying the patch: { :alias_instance, :alias_singleton, or :prepend }:
163
+ # @param target_module [Module] The targeted module
164
+ # @param unbound_method [UnboundMethod] An unbound method, to be patched into target_module.
165
+ # @param visibility [Symbol] method visibility
166
+ def reflect_implementation impl, target_module, unbound_method, visibility
167
+ method_name = unbound_method.name.to_sym # rubocop:disable Security/Module/Name -- ruby built in attribute.
168
+ underlying_method_name = build_unbound_method_name(method_name).to_sym
169
+
358
170
  case impl
359
171
  when :alias_instance, :alias_singleton
360
172
  # Core to patching. Ignore define method usage cop.
@@ -365,27 +177,19 @@ module Contrast
365
177
  target_module.send(:define_method, method_name, unbound_method.bind(target_module))
366
178
  end
367
179
  target_module.send(visibility, method_name) # e.g., module.private(:my_method)
368
- when :prepend
369
- prepending_module = Module.new
370
- prepending_module.send(:define_method, method_name, unbound_method.bind(target_module))
371
- prepending_module.send(visibility, method_name)
180
+ when :prepend_instance, :prepend_singleton
181
+
182
+ unless target_module.instance_methods(false).include? underlying_method_name
183
+
184
+ prepending_module = Module.new
185
+ prepending_module.send(:define_method, method_name, unbound_method.bind(target_module))
186
+ prepending_module.send(visibility, method_name)
187
+
188
+ end
372
189
  # This prepends to the singleton class (it patches a class method)
373
190
  target_module.prepend prepending_module
374
191
  # rubocop:enable Performance/Kernel/DefineMethod
375
192
  end
376
- # Ougai::Logger.create_item_with_2args calls Hash#[]=, so we
377
- # can't invoke this logging method or we'll seg fault as we'd
378
- # change the method definition mid-call
379
- # if method_name != :[]= &&
380
- # Contrast::Agent::Logger.defined!
381
- # logger.trace(
382
- # 'Registered C-defined patch',
383
- # implementation: impl,
384
- # module: target_module_name,
385
- # method: method_name,
386
- # visibility: visibility)
387
- # end
388
- underlying_method_name
389
193
  end
390
194
 
391
195
  # @return [Boolean]
@@ -15,13 +15,9 @@ module Contrast
15
15
  # @param mod [Module] the Module for which the status is asked
16
16
  # @return [Contrast::Agent::Patching::Policy::PatchStatus]
17
17
  def get_status mod
18
- if mod.cs__const_defined?(status_key, false)
19
- mod.cs__const_get(status_key, false)
20
- else
21
- s = new
22
- mod.cs__const_set(status_key, s)
23
- s
24
- end
18
+ return mod.cs__const_get(status_key) if mod.cs__const_defined?(status_key, false)
19
+
20
+ mod.cs__const_set(status_key, new)
25
21
  end
26
22
 
27
23
  # Allows our C patches to look up the :MethodPolicy for a given
@@ -10,6 +10,7 @@ require 'contrast/agent/patching/policy/module_policy'
10
10
  require 'contrast/components/logger'
11
11
  require 'contrast/components/scope'
12
12
  require 'contrast/utils/class_util'
13
+ require 'contrast/utils/patching/policy/patcher_utils'
13
14
 
14
15
  # assess
15
16
  require 'contrast/agent/assess/policy/policy'
@@ -44,6 +45,7 @@ module Contrast
44
45
  # and how.
45
46
  module Patcher
46
47
  extend Contrast::Agent::Patching::Policy::AfterLoadPatcher
48
+ extend Contrast::Utils::Patching::PatcherUtils
47
49
  extend Contrast::Components::Logger::InstanceMethods
48
50
  extend Contrast::Components::Scope::InstanceMethods
49
51
 
@@ -54,7 +56,8 @@ module Contrast
54
56
  def patch
55
57
  catchup_after_load_patches
56
58
  catchup_loaded_methods
57
- Contrast::Agent::Assess::Policy::RewriterPatch.rewrite_interpolations if RUBY_VERSION < '2.6.0' # TODO: RUBY-714 remove guard w/ EOL of 2.5
59
+ # TODO: RUBY-714 remove guard w/ EOL of 2.5
60
+ Contrast::Agent::Assess::Policy::RewriterPatch.rewrite_interpolations if RUBY_VERSION < '2.6.0'
58
61
  end
59
62
 
60
63
  # Hook to only monkeypatch Contrast. This will not trigger any
@@ -76,47 +79,6 @@ module Contrast
76
79
  end
77
80
  end
78
81
 
79
- # This method is called by TracePointHook to instrument a specific class during a require
80
- # or eval of dynamic class definition
81
- def patch_specific_module mod
82
- with_contrast_scope do
83
- mod_name = mod.cs__name
84
- return unless Contrast::Utils::ClassUtil.truly_defined?(mod_name)
85
- return if ::Contrast::AGENT.skip_instrumentation?(mod_name)
86
-
87
- load_patches_for_module(mod_name)
88
-
89
- return unless all_module_names.any?(mod_name)
90
-
91
- module_data = Contrast::Agent::ModuleData.new(mod, mod_name)
92
- patch_into_module(module_data)
93
- all_module_names.delete(mod_name) if status_type.get_status(mod).patched?
94
- rescue StandardError => e
95
- logger.error('Unable to patch module', e, module: mod_name)
96
- end
97
- end
98
-
99
- # We did it, team. We found a patcher(s) that applies to the given
100
- # class (or module) and the given method. Time to do some tracking.
101
- #
102
- # @param mod [Module] the module in which the patch should be
103
- # placed.
104
- # @param methods [Array(Symbol)] all the instance or singleton
105
- # methods in this mod.
106
- # @param method_policy [Contrast::Agent::Patching::Policy::MethodPolicy]
107
- # the policy that applies to the given method_name.
108
- # @return [Boolean] if patched, either by this invocation or a
109
- # previous, or not
110
- def patch_method mod, methods, method_policy
111
- return false unless methods&.any? # don't even build the name if there are no methods
112
-
113
- if Contrast::Utils::ClassUtil.prepended_method?(mod, method_policy)
114
- Contrast::Agent::Patching::Policy::Patch.instrument_with_prepend(mod, method_policy)
115
- else
116
- Contrast::Agent::Patching::Policy::Patch.instrument_with_alias(mod, methods, method_policy)
117
- end
118
- end
119
-
120
82
  private
121
83
 
122
84
  POLICIES = [
@@ -176,12 +138,13 @@ module Contrast
176
138
  # @param redo_patch [Boolean] a trigger to force patching regardless of the state of the
177
139
  # Contrast::Agent::Patching::Policy::PatchStatus status on the Module
178
140
  def patch_into_module module_data, redo_patch = false
179
- status = status_type.get_status(module_data.mod)
141
+ status = Contrast::Agent::Patching::Policy::PatchStatus.get_status(module_data.mod)
180
142
  return if (status&.patched? || status&.patching?) && !redo_patch
181
143
 
182
144
  # Begin patching our sources into the given module. Any patcher that has the name of the module will be
183
145
  # evaluated for patching. Find all the patchers that apply to this class, sorted by type.
184
146
  module_policy = Contrast::Agent::Patching::Policy::ModulePolicy.create_module_policy(module_data.mod_name)
147
+
185
148
  # If there's nothing to match, then set that status and exit
186
149
  if module_policy.empty?
187
150
  status.no_patch!
@@ -191,8 +154,8 @@ module Contrast
191
154
  status.patching!
192
155
  num_applied_patches = patch_into_instance_methods(module_data, module_policy)
193
156
  num_applied_patches += patch_into_singleton_methods(module_data, module_policy)
194
- if adjust_for_prepend(module_data) || module_policy.num_expected_patches == num_applied_patches
195
157
 
158
+ if adjust_for_prepend(module_data) || module_policy.num_expected_patches == num_applied_patches
196
159
  status.patched!
197
160
  else
198
161
  status.partial_patch!
@@ -244,6 +207,7 @@ module Contrast
244
207
  def patch_into_instance_methods module_data, module_policy
245
208
  mod = module_data.mod
246
209
  methods = all_instance_methods(mod, true)
210
+ methods.delete(:initialize) if mod.to_s.starts_with?('RSpec') && mod.to_s.include?('Matchers')
247
211
  patch_into_methods(mod, methods, module_policy, true)
248
212
  end
249
213
 
@@ -258,8 +222,7 @@ module Contrast
258
222
  patch_into_methods(mod, methods, module_policy, false)
259
223
  end
260
224
 
261
- # We've found the patchers that apply to this class (or module). Now we'll
262
- # filter on the given method.
225
+ # We've found the patchers that apply to this class (or module). Now we'll filter on the given method.
263
226
  #
264
227
  # @param mod [Module] The module from which to retrieve instance methods.
265
228
  # @param methods [Array<Symbol>] The names of all the methods in in this module
@@ -276,8 +239,7 @@ module Contrast
276
239
  is_instance_method)
277
240
  next if method_policy.empty?
278
241
 
279
- patched = patch_method(mod, methods, method_policy)
280
- count += 1 if patched
242
+ count += 1 if patch_method(mod, methods, method_policy)
281
243
  end
282
244
  count
283
245
  end
@@ -309,6 +271,5 @@ require 'contrast/extension/module'
309
271
  require 'contrast/extension/assess'
310
272
  require 'contrast/extension/inventory'
311
273
  require 'contrast/extension/protect'
312
- require 'contrast/extension/protect/kernel'
313
274
 
314
275
  require 'cs__contrast_patch/cs__contrast_patch'
@@ -14,7 +14,7 @@ module Contrast
14
14
  # infilter methods of the rule should be invoked.
15
15
  module AppliesNoSqliRule
16
16
  extend Contrast::Agent::Protect::Policy::RuleApplicator
17
-
17
+ DATABASE_NOSQL = 'MongoDB'
18
18
  class << self
19
19
  def invoke method, _exception, properties, _object, args
20
20
  return unless valid_input?(args)
@@ -2,6 +2,7 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  require 'contrast/agent/protect/rule/base_service'
5
+ require 'contrast/agent/protect/rule/sql_sample_builder'
5
6
 
6
7
  module Contrast
7
8
  module Agent
@@ -9,6 +10,12 @@ module Contrast
9
10
  module Rule
10
11
  # The Ruby implementation of the Protect NoSQL Injection rule.
11
12
  class NoSqli < Contrast::Agent::Protect::Rule::BaseService
13
+ # Generate a sample for the No-SQL injection detection rule, allowing for reporting to and rendering
14
+ # by TeamServer
15
+ include SqlSampleBuilder::NoSqliSample
16
+ # Defining build_attack_with_match method
17
+ include SqlSampleBuilder::AttackBuilder
18
+
12
19
  NAME = 'nosql-injection'
13
20
  BLOCK_MESSAGE = 'NoSQLi rule triggered. Response blocked.'
14
21
 
@@ -31,40 +38,6 @@ module Contrast
31
38
  raise Contrast::SecurityException.new(self, BLOCK_MESSAGE) if blocked?
32
39
  end
33
40
 
34
- def build_attack_with_match context, input_analysis_result, result, query_string, **kwargs
35
- if mode == Contrast::Api::Settings::ProtectionRule::Mode::NO_ACTION ||
36
- mode == Contrast::Api::Settings::ProtectionRule::Mode::PERMIT
37
-
38
- return result
39
- end
40
-
41
- attack_string = input_analysis_result.value
42
- regexp = Regexp.new(Regexp.escape(attack_string), Regexp::IGNORECASE)
43
- return unless query_string.match?(regexp)
44
-
45
- scanner = select_scanner
46
- ss = StringScanner.new(query_string)
47
- length = attack_string.length
48
- while ss.scan_until(regexp)
49
- # the pos of StringScanner is at the end of the regexp (input string),
50
- # we need the beginning
51
- idx = ss.pos - attack_string.length
52
- last_boundary, boundary = scanner.crosses_boundary(query_string, idx, input_analysis_result.value)
53
- next unless last_boundary && boundary
54
-
55
- kwargs[:start_idx] = idx
56
- kwargs[:end_idx] = idx + length
57
- kwargs[:boundary_overrun_idx] = boundary
58
- kwargs[:input_boundary_idx] = last_boundary
59
-
60
- result ||= build_attack_result(context)
61
- update_successful_attack_response(context, input_analysis_result, result, query_string)
62
- append_sample(context, input_analysis_result, result, query_string, **kwargs)
63
- end
64
-
65
- result
66
- end
67
-
68
41
  protected
69
42
 
70
43
  def find_attacker context, potential_attack_string, **kwargs
@@ -79,25 +52,6 @@ module Contrast
79
52
  end
80
53
  super(context, potential_attack_string, **kwargs)
81
54
  end
82
-
83
- def build_sample context, input_analysis_result, candidate_string, **kwargs
84
- input = input_analysis_result.value
85
-
86
- sample = build_base_sample(context, input_analysis_result)
87
- sample.no_sqli = Contrast::Api::Dtm::NoSqlInjectionDetails.new
88
- sample.no_sqli.query = Contrast::Utils::StringUtils.protobuf_safe_string(candidate_string)
89
- sample.no_sqli.start_idx = sample.no_sqli.query.index(input).to_i
90
- sample.no_sqli.boundary_overrun_idx = sample.no_sqli.start_idx + input.length
91
- sample.no_sqli.input_boundary_idx = kwargs[:boundary].to_i
92
- sample.no_sqli.input_boundary_idx = kwargs[:last_boundary].to_i
93
- sample
94
- end
95
-
96
- private
97
-
98
- def select_scanner
99
- @_select_scanner ||= Contrast::Agent::Protect::Rule::NoSqli::MongoNoSqlScanner.new
100
- end
101
55
  end
102
56
  end
103
57
  end