contrast-agent 3.10.2 → 3.11.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (266) hide show
  1. checksums.yaml +4 -4
  2. data/.simplecov +5 -2
  3. data/ext/build_funchook.rb +13 -17
  4. data/ext/cs__assess_active_record_named/cs__active_record_named.c +5 -12
  5. data/ext/cs__assess_active_record_named/extconf.rb +3 -0
  6. data/ext/cs__assess_array/cs__assess_array.c +3 -5
  7. data/ext/cs__assess_array/extconf.rb +3 -0
  8. data/ext/cs__assess_basic_object/cs__assess_basic_object.c +10 -4
  9. data/ext/cs__assess_basic_object/extconf.rb +3 -0
  10. data/ext/cs__assess_fiber_track/cs__assess_fiber_track.c +4 -3
  11. data/ext/cs__assess_fiber_track/cs__assess_fiber_track.h +3 -3
  12. data/ext/cs__assess_fiber_track/extconf.rb +3 -0
  13. data/ext/cs__assess_hash/cs__assess_hash.c +40 -17
  14. data/ext/cs__assess_hash/cs__assess_hash.h +4 -6
  15. data/ext/cs__assess_hash/extconf.rb +3 -0
  16. data/ext/cs__assess_kernel/cs__assess_kernel.c +10 -8
  17. data/ext/cs__assess_kernel/cs__assess_kernel.h +1 -0
  18. data/ext/cs__assess_kernel/extconf.rb +3 -0
  19. data/ext/cs__assess_marshal_module/cs__assess_marshal_module.c +3 -6
  20. data/ext/cs__assess_marshal_module/extconf.rb +3 -0
  21. data/ext/cs__assess_module/cs__assess_module.c +13 -9
  22. data/ext/cs__assess_module/extconf.rb +3 -0
  23. data/ext/cs__assess_regexp/cs__assess_regexp.c +13 -9
  24. data/ext/cs__assess_regexp/cs__assess_regexp.h +1 -0
  25. data/ext/cs__assess_regexp/extconf.rb +3 -0
  26. data/ext/cs__assess_string/cs__assess_string.c +5 -8
  27. data/ext/cs__assess_string/cs__assess_string.h +2 -1
  28. data/ext/cs__assess_string/extconf.rb +3 -0
  29. data/ext/cs__assess_string_interpolation26/cs__assess_string_interpolation26.c +2 -2
  30. data/ext/cs__assess_string_interpolation26/cs__assess_string_interpolation26.h +3 -3
  31. data/ext/cs__assess_string_interpolation26/extconf.rb +3 -0
  32. data/ext/cs__assess_yield_track/cs__assess_yield_track.h +1 -1
  33. data/ext/cs__assess_yield_track/extconf.rb +3 -0
  34. data/ext/cs__common/cs__common.c +79 -0
  35. data/ext/cs__common/cs__common.h +34 -0
  36. data/ext/cs__common/extconf.rb +9 -8
  37. data/ext/cs__contrast_patch/cs__contrast_patch.h +1 -6
  38. data/ext/cs__contrast_patch/extconf.rb +3 -0
  39. data/ext/cs__protect_kernel/cs__protect_kernel.c +20 -11
  40. data/ext/cs__protect_kernel/extconf.rb +3 -0
  41. data/ext/extconf_common.rb +10 -8
  42. data/funchook/autom4te.cache/output.0 +1 -13
  43. data/funchook/autom4te.cache/requests +44 -45
  44. data/funchook/autom4te.cache/traces.0 +0 -3
  45. data/funchook/config.log +378 -217
  46. data/funchook/config.status +23 -24
  47. data/funchook/configure +1 -13
  48. data/funchook/src/Makefile +7 -7
  49. data/funchook/src/config.h +2 -2
  50. data/funchook/src/decoder.o +0 -0
  51. data/funchook/src/distorm.o +0 -0
  52. data/funchook/src/funchook.o +0 -0
  53. data/funchook/src/funchook_io.o +0 -0
  54. data/funchook/src/funchook_syscall.o +0 -0
  55. data/funchook/src/funchook_unix.o +0 -0
  56. data/funchook/src/funchook_x86.o +0 -0
  57. data/funchook/src/instructions.o +0 -0
  58. data/funchook/src/insts.o +0 -0
  59. data/funchook/src/libfunchook.dylib +0 -0
  60. data/funchook/src/mnemonics.o +0 -0
  61. data/funchook/src/operands.o +0 -0
  62. data/funchook/src/os_func.o +0 -0
  63. data/funchook/src/os_func_unix.o +0 -0
  64. data/funchook/src/prefix.o +0 -0
  65. data/funchook/src/printf_base.o +0 -0
  66. data/funchook/src/textdefs.o +0 -0
  67. data/funchook/src/wstring.o +0 -0
  68. data/funchook/test/Makefile +2 -2
  69. data/funchook/test/funchook_test +0 -0
  70. data/funchook/test/libfunchook_test.so +0 -0
  71. data/funchook/test/libfunchook_test.so.dSYM/Contents/Info.plist +20 -0
  72. data/funchook/test/libfunchook_test.so.dSYM/Contents/Resources/DWARF/libfunchook_test.so +0 -0
  73. data/funchook/test/test_main.o +0 -0
  74. data/funchook/test/x86_64_test.o +0 -0
  75. data/lib/contrast.rb +1 -0
  76. data/lib/contrast/agent.rb +21 -15
  77. data/lib/contrast/agent/assess.rb +1 -2
  78. data/lib/contrast/agent/assess/adjusted_span.rb +3 -1
  79. data/lib/contrast/agent/assess/contrast_event.rb +16 -62
  80. data/lib/contrast/agent/assess/events/event_factory.rb +25 -0
  81. data/lib/contrast/agent/assess/events/source_event.rb +83 -0
  82. data/lib/contrast/agent/assess/insulator.rb +0 -4
  83. data/lib/contrast/agent/assess/policy/patcher.rb +5 -2
  84. data/lib/contrast/agent/assess/policy/policy_node.rb +0 -7
  85. data/lib/contrast/agent/assess/policy/policy_scanner.rb +1 -1
  86. data/lib/contrast/agent/assess/policy/preshift.rb +1 -1
  87. data/lib/contrast/agent/assess/policy/propagation_method.rb +65 -33
  88. data/lib/contrast/agent/assess/policy/propagation_node.rb +2 -1
  89. data/lib/contrast/agent/assess/policy/propagator.rb +1 -0
  90. data/lib/contrast/agent/assess/policy/propagator/match_data.rb +80 -0
  91. data/lib/contrast/agent/assess/policy/propagator/select.rb +35 -22
  92. data/lib/contrast/agent/assess/policy/propagator/split.rb +26 -6
  93. data/lib/contrast/agent/assess/policy/propagator/substitution.rb +2 -0
  94. data/lib/contrast/agent/assess/policy/rewriter_patch.rb +37 -26
  95. data/lib/contrast/agent/assess/policy/source_method.rb +20 -20
  96. data/lib/contrast/agent/assess/policy/source_node.rb +0 -15
  97. data/lib/contrast/agent/assess/policy/trigger_method.rb +29 -40
  98. data/lib/contrast/agent/assess/policy/trigger_node.rb +3 -6
  99. data/lib/contrast/agent/assess/policy/trigger_validation/ssrf_validator.rb +2 -31
  100. data/lib/contrast/agent/assess/properties.rb +5 -3
  101. data/lib/contrast/agent/assess/rule/base.rb +1 -5
  102. data/lib/contrast/agent/assess/rule/csrf/csrf_applicator.rb +2 -22
  103. data/lib/contrast/agent/assess/rule/csrf/csrf_watcher.rb +5 -1
  104. data/lib/contrast/agent/assess/rule/provider/hardcoded_value_rule.rb +2 -2
  105. data/lib/contrast/agent/assess/rule/redos.rb +4 -4
  106. data/lib/contrast/agent/assess/tag.rb +24 -14
  107. data/lib/contrast/agent/at_exit_hook.rb +16 -13
  108. data/lib/contrast/agent/class_reopener.rb +14 -4
  109. data/lib/contrast/agent/deadzone/policy/policy.rb +2 -2
  110. data/lib/contrast/agent/disable_reaction.rb +3 -4
  111. data/lib/contrast/agent/exclusion_matcher.rb +8 -48
  112. data/lib/contrast/agent/feature_state.rb +45 -75
  113. data/lib/contrast/agent/logger.rb +173 -0
  114. data/lib/contrast/agent/middleware.rb +87 -250
  115. data/lib/contrast/agent/module_data.rb +2 -1
  116. data/lib/contrast/agent/patching/policy/after_load_patch.rb +2 -1
  117. data/lib/contrast/agent/patching/policy/after_load_patcher.rb +21 -4
  118. data/lib/contrast/agent/patching/policy/method_policy.rb +3 -3
  119. data/lib/contrast/agent/patching/policy/module_policy.rb +0 -25
  120. data/lib/contrast/agent/patching/policy/patch.rb +96 -23
  121. data/lib/contrast/agent/patching/policy/patcher.rb +19 -19
  122. data/lib/contrast/agent/patching/policy/policy.rb +7 -7
  123. data/lib/contrast/agent/patching/policy/policy_node.rb +2 -10
  124. data/lib/contrast/agent/patching/policy/trigger_node.rb +1 -4
  125. data/lib/contrast/agent/protect/rule/base.rb +14 -33
  126. data/lib/contrast/agent/protect/rule/base_service.rb +3 -1
  127. data/lib/contrast/agent/protect/rule/cmd_injection.rb +10 -13
  128. data/lib/contrast/agent/protect/rule/csrf.rb +2 -1
  129. data/lib/contrast/agent/protect/rule/csrf/csrf_evaluator.rb +11 -14
  130. data/lib/contrast/agent/protect/rule/default_scanner.rb +0 -13
  131. data/lib/contrast/agent/protect/rule/deserialization.rb +2 -0
  132. data/lib/contrast/agent/protect/rule/http_method_tampering.rb +2 -2
  133. data/lib/contrast/agent/protect/rule/no_sqli.rb +4 -4
  134. data/lib/contrast/agent/protect/rule/path_traversal.rb +5 -4
  135. data/lib/contrast/agent/protect/rule/sqli.rb +1 -0
  136. data/lib/contrast/agent/protect/rule/unsafe_file_upload.rb +2 -0
  137. data/lib/contrast/agent/protect/rule/xss.rb +2 -0
  138. data/lib/contrast/agent/protect/rule/xxe.rb +10 -4
  139. data/lib/contrast/agent/railtie.rb +2 -8
  140. data/lib/contrast/agent/reaction_processor.rb +5 -5
  141. data/lib/contrast/agent/request.rb +9 -12
  142. data/lib/contrast/agent/request_context.rb +12 -14
  143. data/lib/contrast/agent/request_handler.rb +35 -0
  144. data/lib/contrast/agent/response.rb +33 -30
  145. data/lib/contrast/agent/rewriter.rb +22 -10
  146. data/lib/contrast/agent/rule_set.rb +49 -0
  147. data/lib/contrast/agent/scope.rb +0 -6
  148. data/lib/contrast/agent/service_heartbeat.rb +1 -2
  149. data/lib/contrast/agent/settings_state.rb +10 -74
  150. data/lib/contrast/agent/socket_client.rb +17 -11
  151. data/lib/contrast/agent/static_analysis.rb +42 -0
  152. data/lib/contrast/agent/thread.rb +1 -1
  153. data/lib/contrast/agent/tracepoint_hook.rb +1 -5
  154. data/lib/contrast/agent/version.rb +1 -1
  155. data/lib/contrast/api.rb +1 -1
  156. data/lib/contrast/api/decorators.rb +14 -0
  157. data/lib/contrast/api/decorators/application_settings.rb +37 -0
  158. data/lib/contrast/api/decorators/application_update.rb +66 -0
  159. data/lib/contrast/api/decorators/exclusion.rb +20 -0
  160. data/lib/contrast/api/decorators/input_analysis.rb +17 -0
  161. data/lib/contrast/api/decorators/server_features.rb +24 -0
  162. data/lib/contrast/api/speedracer.rb +27 -23
  163. data/lib/contrast/api/tcp_socket.rb +0 -2
  164. data/lib/contrast/components/agent.rb +27 -22
  165. data/lib/contrast/components/app_context.rb +18 -43
  166. data/lib/contrast/components/config.rb +7 -5
  167. data/lib/contrast/components/contrast_service.rb +0 -4
  168. data/lib/contrast/components/heap_dump.rb +12 -8
  169. data/lib/contrast/components/interface.rb +11 -10
  170. data/lib/contrast/components/logger.rb +3 -68
  171. data/lib/contrast/components/sampling.rb +22 -11
  172. data/lib/contrast/components/settings.rb +18 -5
  173. data/lib/contrast/config/base_configuration.rb +1 -0
  174. data/lib/contrast/config/default_value.rb +1 -0
  175. data/lib/contrast/config/protect_rule_configuration.rb +0 -14
  176. data/lib/contrast/extensions/framework/rails/action_controller_inheritance.rb +39 -0
  177. data/lib/contrast/extensions/framework/rails/active_record_named.rb +13 -8
  178. data/lib/contrast/extensions/ruby_core/assess.rb +1 -2
  179. data/lib/contrast/extensions/ruby_core/assess/assess_extension.rb +27 -22
  180. data/lib/contrast/extensions/ruby_core/assess/erb.rb +0 -8
  181. data/lib/contrast/extensions/ruby_core/assess/exec_trigger.rb +6 -8
  182. data/lib/contrast/extensions/ruby_core/assess/fiber.rb +88 -100
  183. data/lib/contrast/extensions/ruby_core/assess/hash.rb +32 -15
  184. data/lib/contrast/extensions/ruby_core/assess/kernel.rb +28 -27
  185. data/lib/contrast/extensions/ruby_core/assess/regexp.rb +74 -196
  186. data/lib/contrast/extensions/ruby_core/assess/string.rb +15 -7
  187. data/lib/contrast/extensions/ruby_core/assess/tilt_template_trigger.rb +29 -24
  188. data/lib/contrast/extensions/ruby_core/assess/xpath_library_trigger.rb +2 -2
  189. data/lib/contrast/extensions/ruby_core/eval_trigger.rb +0 -1
  190. data/lib/contrast/extensions/ruby_core/inventory/datastores.rb +2 -2
  191. data/lib/contrast/extensions/ruby_core/protect/applies_command_injection_rule.rb +9 -20
  192. data/lib/contrast/extensions/ruby_core/protect/applies_deserialization_rule.rb +9 -19
  193. data/lib/contrast/extensions/ruby_core/protect/applies_no_sqli_rule.rb +10 -27
  194. data/lib/contrast/extensions/ruby_core/protect/applies_path_traversal_rule.rb +13 -21
  195. data/lib/contrast/extensions/ruby_core/protect/applies_sqli_rule.rb +11 -23
  196. data/lib/contrast/extensions/ruby_core/protect/applies_xxe_rule.rb +62 -78
  197. data/lib/contrast/extensions/ruby_core/protect/rule_applicator.rb +50 -0
  198. data/lib/contrast/framework/base_support.rb +10 -0
  199. data/lib/contrast/framework/manager.rb +28 -2
  200. data/lib/contrast/framework/platform_version.rb +1 -0
  201. data/lib/contrast/framework/rails_support.rb +16 -0
  202. data/lib/contrast/framework/sinatra_support.rb +12 -2
  203. data/lib/contrast/framework/view_technologies_descriptor.rb +1 -0
  204. data/lib/contrast/tasks/service.rb +2 -8
  205. data/lib/contrast/utils/assess/sampling_util.rb +4 -9
  206. data/lib/contrast/utils/assess/tracking_util.rb +7 -1
  207. data/lib/contrast/utils/boolean_util.rb +2 -2
  208. data/lib/contrast/utils/cache.rb +0 -11
  209. data/lib/contrast/utils/class_util.rb +20 -1
  210. data/lib/contrast/utils/gemfile_reader.rb +5 -3
  211. data/lib/contrast/utils/hash_digest.rb +0 -4
  212. data/lib/contrast/utils/heap_dump_util.rb +12 -11
  213. data/lib/contrast/utils/invalid_configuration_util.rb +1 -1
  214. data/lib/contrast/utils/inventory_util.rb +2 -2
  215. data/lib/contrast/utils/io_util.rb +1 -11
  216. data/lib/contrast/utils/job_servers_running.rb +2 -2
  217. data/lib/contrast/utils/object_share.rb +1 -27
  218. data/lib/contrast/utils/os.rb +1 -25
  219. data/lib/contrast/utils/rack_assess_session_cookie.rb +3 -3
  220. data/lib/contrast/utils/rails_assess_configuration.rb +3 -3
  221. data/lib/contrast/utils/service_response_util.rb +27 -53
  222. data/lib/contrast/utils/service_sender_util.rb +9 -5
  223. data/lib/contrast/utils/sinatra_helper.rb +0 -6
  224. data/lib/contrast/utils/stack_trace_utils.rb +86 -182
  225. data/lib/contrast/utils/string_utils.rb +18 -2
  226. data/lib/contrast/utils/tag_util.rb +11 -1
  227. data/lib/contrast/utils/thread_tracker.rb +2 -2
  228. data/lib/contrast/utils/timer.rb +0 -40
  229. data/resources/assess/policy.json +33 -21
  230. data/resources/protect/policy.json +9 -9
  231. data/ruby-agent.gemspec +6 -3
  232. metadata +76 -51
  233. data/ext/cs__assess_regexp_track/cs__assess_regexp_track.c +0 -63
  234. data/ext/cs__assess_regexp_track/cs__assess_regexp_track.h +0 -29
  235. data/ext/cs__assess_regexp_track/extconf.rb +0 -2
  236. data/funchook/src/libfunchook.so +0 -0
  237. data/lib/contrast/agent/assess/frozen_properties.rb +0 -41
  238. data/lib/contrast/agent/logger_manager.rb +0 -116
  239. data/lib/contrast/delegators.rb +0 -9
  240. data/lib/contrast/delegators/application_update.rb +0 -32
  241. data/lib/contrast/utils/comment_range.rb +0 -19
  242. data/lib/contrast/utils/environment_util.rb +0 -81
  243. data/lib/contrast/utils/performs_logging.rb +0 -152
  244. data/resources/factory-bot-spec/spec_helper.rb +0 -30
  245. data/resources/rubocops/kernel/catch_cop.rb +0 -37
  246. data/resources/rubocops/kernel/require_cop.rb +0 -37
  247. data/resources/rubocops/kernel/require_relative_cop.rb +0 -33
  248. data/resources/rubocops/module/autoload_cop.rb +0 -37
  249. data/resources/rubocops/module/const_defined_cop.rb +0 -37
  250. data/resources/rubocops/module/const_get_cop.rb +0 -37
  251. data/resources/rubocops/module/const_set_cop.rb +0 -37
  252. data/resources/rubocops/module/constants_cop.rb +0 -37
  253. data/resources/rubocops/module/name_cop.rb +0 -37
  254. data/resources/rubocops/object/class_cop.rb +0 -37
  255. data/resources/rubocops/object/freeze_cop.rb +0 -37
  256. data/resources/rubocops/object/frozen_cop.rb +0 -37
  257. data/resources/rubocops/object/is_a_cop.rb +0 -37
  258. data/resources/rubocops/object/method_cop.rb +0 -37
  259. data/resources/rubocops/object/respond_to_cop.rb +0 -37
  260. data/resources/rubocops/object/singleton_class_cop.rb +0 -37
  261. data/resources/rubocops/regexp/spelling_cop.rb +0 -44
  262. data/resources/rubocops/thread/new_cop.rb +0 -39
  263. data/resources/ruby-spec/ancestors_spec.rb +0 -70
  264. data/resources/ruby-spec/modulo_spec.rb +0 -831
  265. data/resources/ruby-spec/parameters_spec.rb +0 -261
  266. data/resources/ruby-spec/ruby_spec_spec_helper.rb +0 -35
@@ -2,7 +2,6 @@
2
2
  # frozen_string_literal: true
3
3
 
4
4
  cs__scoped_require 'contrast/agent/settings_state'
5
- cs__scoped_require 'contrast/extensions/ruby_core/module'
6
5
  cs__scoped_require 'contrast/utils/boolean_util'
7
6
 
8
7
  module Contrast
@@ -35,57 +34,69 @@ module Contrast
35
34
  end
36
35
 
37
36
  def inventory_enabled?
38
- !false?(CONFIG.root.inventory.enable)
37
+ @_inventory_enabled = !false?(CONFIG.root.inventory.enable) if @_inventory_enabled.nil?
38
+ @_inventory_enabled
39
39
  end
40
40
 
41
41
  def protect_forcibly_enabled?
42
- true?(CONFIG.root.protect.enable)
42
+ @_protect_forcibly_enabled = true?(CONFIG.root.protect.enable) if @_protect_forcibly_enabled.nil?
43
+ @_protect_forcibly_enabled
43
44
  end
44
45
 
45
46
  def protect_forcibly_disabled?
46
- false?(CONFIG.root.protect.enable)
47
+ @_protect_forcibly_disabled = false?(CONFIG.root.protect.enable) if @_protect_forcibly_disabled.nil?
48
+ @_protect_forcibly_disabled
47
49
  end
48
50
 
49
51
  def assess_forcibly_enabled?
50
- true?(CONFIG.root.assess.enable)
52
+ @_assess_forcibly_enabled = true?(CONFIG.root.assess.enable) if @_assess_forcibly_enabled.nil?
53
+ @_assess_forcibly_enabled
51
54
  end
52
55
 
53
56
  def assess_forcibly_disabled?
54
- false?(CONFIG.root.assess.enable)
57
+ @_assess_forcibly_disabled = false?(CONFIG.root.assess.enable) if @_assess_forcibly_disabled.nil?
58
+ @_assess_forcibly_disabled
55
59
  end
56
60
 
57
61
  def assess_track_frozen_sources?
58
- !false?(CONFIG.root.agent.ruby.track_frozen_sources)
62
+ @_assess_track_frozen_sources = !false?(CONFIG.root.agent.ruby.track_frozen_sources) if @_assess_track_frozen_sources.nil?
63
+ @_assess_track_frozen_sources
59
64
  end
60
65
 
61
66
  def scan_response?
62
- !false?(CONFIG.root.assess.enable_scan_response)
67
+ @_scan_response = !false?(CONFIG.root.assess.enable_scan_response) if @_scan_response.nil?
68
+ @_scan_response
63
69
  end
64
70
 
65
71
  def omit_body?
66
- true?(CONFIG.root.agent.omit_body)
72
+ @_omit_body = true?(CONFIG.root.agent.omit_body) if @_omit_body.nil?
73
+ @_omit_body
67
74
  end
68
75
 
69
76
  def require_scanning_enabled?
70
- !false?(CONFIG.root.agent.ruby.require_scan)
71
- end
72
-
73
- def heap_dump_enabled?
74
- true?(CONFIG.root.agent.heap_dump.enable)
77
+ @_require_scanning_enabled = !false?(CONFIG.root.agent.ruby.require_scan) if @_require_scanning_enabled.nil?
78
+ @_require_scanning_enabled
75
79
  end
76
80
 
77
81
  def service_forcibly_disabled?
78
- false?(CONFIG.root.agent.start_bundled_service)
82
+ @_service_forcibly_disabled = false?(CONFIG.root.agent.start_bundled_service) if @_service_forcibly_disabled.nil?
83
+ @_service_forcibly_disabled
79
84
  end
80
85
 
81
86
  def report_any_command_execution?
82
- ctrl = protect_rule_config[Contrast::Agent::Protect::Rule::CmdInjection::NAME]
83
- true?(ctrl.disable_system_commands)
87
+ if @_report_any_command_execution.nil?
88
+ ctrl = protect_rule_config[Contrast::Agent::Protect::Rule::CmdInjection::NAME]
89
+ @_report_any_command_execution = true?(ctrl.disable_system_commands)
90
+ end
91
+ @_report_any_command_execution
84
92
  end
85
93
 
86
94
  def report_custom_code_sysfile_access?
87
- ctrl = protect_rule_config[Contrast::Agent::Protect::Rule::PathTraversal::NAME]
88
- true?(ctrl.detect_custom_code_accessing_system_files)
95
+ if @_report_custom_code_sysfile_access.nil?
96
+ ctrl = protect_rule_config[Contrast::Agent::Protect::Rule::PathTraversal::NAME]
97
+ @_report_custom_code_sysfile_access = true?(ctrl.detect_custom_code_accessing_system_files)
98
+ end
99
+ @_report_custom_code_sysfile_access
89
100
  end
90
101
 
91
102
  # Determines if the Process we're currently in matches that of the
@@ -138,14 +149,6 @@ module Contrast
138
149
  SETTINGS.exclusion_matchers
139
150
  end
140
151
 
141
- def url_exclusions
142
- exclusions.select(&:url?)
143
- end
144
-
145
- def input_exclusions
146
- exclusions.select(&:input?)
147
- end
148
-
149
152
  def code_exclusions
150
153
  exclusions.select(&:code?)
151
154
  end
@@ -235,36 +238,9 @@ module Contrast
235
238
  include Contrast::Components::Interface
236
239
  access_component :config
237
240
 
238
- def heap_dump_control
239
- {
240
- path: File.absolute_path(CONFIG.root.agent.heap_dump.path),
241
- count: CONFIG.root.agent.heap_dump.count.to_i,
242
- window: CONFIG.root.agent.heap_dump.window_ms.to_f / 1000,
243
- delay: CONFIG.root.agent.heap_dump.delay_ms.to_f / 1000,
244
- clean: true?(CONFIG.root.agent.heap_dump.clean)
245
- }
246
- end
247
-
248
- DEFAULT_SAMPLING_ENABLED = false
249
- DEFAULT_SAMPLING_BASELINE = 5
250
- DEFAULT_SAMPLING_REQUEST_FREQUENCY = 5
251
- DEFAULT_SAMPLING_RESPONSE_FREQUENCY = 25
252
- DEFAULT_SAMPLING_WINDOW_MS = 180_000 # 3 minutes, arbitrary value from Java agent
253
- def sampling_control settings = @sampling_features
254
- cas = CONFIG.root.assess&.sampling
255
-
256
- {
257
- enabled: true?([cas&.enable, settings&.enabled, DEFAULT_SAMPLING_ENABLED] .reject(&:nil?).first),
258
- baseline: [cas&.baseline, settings&.baseline, DEFAULT_SAMPLING_BASELINE] .map(&:to_i).find(&:positive?),
259
- request_frequency: [cas&.request_frequency, settings&.request_frequency, DEFAULT_SAMPLING_REQUEST_FREQUENCY] .map(&:to_i).find(&:positive?),
260
- response_frequency: [cas&.response_frequency, settings&.response_frequency, DEFAULT_SAMPLING_RESPONSE_FREQUENCY].map(&:to_i).find(&:positive?),
261
- window: [cas&.window_ms, settings&.window_ms, DEFAULT_SAMPLING_WINDOW_MS] .map(&:to_i).find(&:positive?)
262
- }
263
- end
264
-
265
241
  DEFAULT_LOG_FILENAME = 'contrast_service.log'
266
242
  def service_control
267
- {
243
+ @_service_control ||= {
268
244
  host: CONFIG.root.agent.service.host || Contrast::Configuration::DEFAULT_HOST,
269
245
  port: CONFIG.root.agent.service.port || Contrast::Configuration::DEFAULT_PORT,
270
246
  socket_path: CONFIG.root.agent.service.socket,
@@ -273,7 +249,7 @@ module Contrast
273
249
  end
274
250
 
275
251
  def exception_control
276
- {
252
+ @_exception_control ||= {
277
253
  enable: true?(CONFIG.root.agent.ruby.exceptions.capture),
278
254
  status: CONFIG.root.agent.ruby.exceptions.override_status || 403,
279
255
  message: CONFIG.root.agent.ruby.exceptions.override_message || Contrast::Utils::ObjectShare::OVERRIDE_MESSAGE
@@ -298,35 +274,25 @@ module Contrast
298
274
  # methods for logging state.
299
275
  module Logging
300
276
  include Contrast::Components::Interface
301
- access_component :config
302
-
303
- FALLBACK = STDOUT
304
- LOG_INFO_RULE_SETTINGS = 'Current rule settings:'
305
- # Utility method to log the current mode of all the rules
306
- def log_rule_modes
307
- return unless logger&.info?
308
-
309
- logger.info(LOG_INFO_RULE_SETTINGS)
310
- PROTECT.rules.each { |k, v| logger.info(".. protect:\t#{ k } (#{ v.mode })") }
311
- ASSESS.rules.each { |k, v| logger.info(".. assess: \t#{ k } (#{ v.enabled? })") }
312
- end
277
+ access_component :config, :logging
313
278
 
314
279
  ENV_KEYS = %w[HOME PWD RACK_ENV RAILS_ENV RUBY_VERSION GEM_HOME GEM_PATH].cs__freeze
315
280
  # Utility method to log some current ruby and rails information from environment
316
281
  def log_environment
317
282
  return unless logger.info?
318
283
 
319
- logger.info "AGENT_VERSION=#{ Contrast::Agent::VERSION }"
284
+ logger.info('Process environment information',
285
+ p_id: Process.pid,
286
+ pp_id: Process.ppid,
287
+ agent_version: Contrast::Agent::VERSION)
320
288
  ENV.each do |env_key, env_value|
321
289
  env_key = env_key.to_s
322
290
  next unless ENV_KEYS.include?(env_key) ||
323
291
  (env_key.start_with?(Contrast::Components::Config::CONTRAST_ENV_MARKER) &&
324
292
  !env_key.start_with?(Contrast::Components::Config::CONTRAST_ENV_MARKER + 'API'))
325
293
 
326
- logger.info "#{ env_key }=#{ env_value }"
294
+ logger.info('Environment settings', key: env_key, value: env_value)
327
295
  end
328
- logger.info "PARENT_PROCESS_ID=#{ Process.ppid }"
329
- logger.info "PROCESS_ID=#{ Process.pid }"
330
296
  end
331
297
 
332
298
  def log_configuration
@@ -334,7 +300,7 @@ module Contrast
334
300
 
335
301
  loggable = CONFIG.raw.send(:load_config)
336
302
  loggable.delete('api')
337
- logger.info "LOCAL CONFIGURATION: #{ JSON.pretty_generate(loggable) }"
303
+ logger.info('Current configuration', configruation: JSON.pretty_generate(loggable))
338
304
  end
339
305
 
340
306
  FRAMEWORKS = %w[rails sinatra grape].cs__freeze
@@ -350,7 +316,9 @@ module Contrast
350
316
  return unless logger.debug?
351
317
 
352
318
  Gem.loaded_specs.each_pair do |_name, gem_spec|
353
- logger.debug { "GEM LOADED: #{ gem_spec.name }=#{ gem_spec.version }" }
319
+ logger.debug('Gem loaded',
320
+ gem_name: gem_spec.name,
321
+ gem_version: gem_spec.version.to_s)
354
322
  end
355
323
  end
356
324
 
@@ -358,7 +326,9 @@ module Contrast
358
326
  gem_spec = Gem.loaded_specs[gem_name]
359
327
  return unless gem_spec
360
328
 
361
- logger.info { "GEM LOADED: #{ gem_spec.name }=#{ gem_spec.version }" }
329
+ logger.info('Gem loaded',
330
+ gem_name: gem_spec.name,
331
+ gem_version: gem_spec.version.to_s)
362
332
  end
363
333
  end
364
334
 
@@ -0,0 +1,173 @@
1
+ # Copyright (c) 2020 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ cs__scoped_require 'logger'
5
+ cs__scoped_require 'ougai'
6
+ cs__scoped_require 'singleton'
7
+
8
+ cs__scoped_require 'contrast/extensions/ruby_core/module'
9
+ cs__scoped_require 'contrast/components/interface'
10
+
11
+ module Contrast
12
+ module Ougai
13
+ # Our decorator for the Ougai logger allowing for timing and with_level
14
+ # methods.
15
+ module Logger
16
+ # Log the message at the given level.
17
+ #
18
+ # @param level [String] the name of the method to use. Should be one of
19
+ # trace, debug, info, warn, error
20
+ # @param message [String] the message to log
21
+ def with_level level, message
22
+ send(level.to_sym, message)
23
+ end
24
+
25
+ # Log, at the debug level, the action with a message including the time
26
+ # it took for the wrapped function to complete.
27
+ #
28
+ # @param msgs [Array<Object>] the arguments to pass to the logger.
29
+ # msgs[0] will be modified to include the elapsed time.
30
+ # @param block [Block, Proc] the block to execute
31
+ def debug_with_time *msgs, &block
32
+ log_with_time(:debug, *msgs, &block)
33
+ end
34
+
35
+ # Log, at the trace level, the action with a message including the time
36
+ # it took for the wrapped function to complete.
37
+ #
38
+ # @param msgs [Array<Object>] the arguments to pass to the logger.
39
+ # msgs[0] will be modified to include the elapsed time.
40
+ # @param block [Block, Proc] the block to execute
41
+ def trace_with_time *msgs, &block
42
+ log_with_time(:trace, *msgs, &block)
43
+ end
44
+
45
+ private
46
+
47
+ def log_with_time level, *msgs
48
+ a = Contrast::Utils::Timer.now_ms
49
+ ret = yield if block_given?
50
+ z = Contrast::Utils::Timer.now_ms
51
+ msgs[0] = "#{ msgs[0] }: pid=#{ Process.pid }, elapsed=#{ z - a }ms"
52
+ send(level, *msgs)
53
+ ret
54
+ end
55
+ end
56
+ end
57
+ end
58
+
59
+ module Contrast
60
+ module Agent
61
+ # This class functions to serve as a wrapper around our logging, as we need
62
+ # to be able to dynamically update level based on updates to TeamServer.
63
+ class Logger
64
+ include Singleton
65
+ include Contrast::Components::Interface
66
+ access_component :config
67
+
68
+ DEFAULT_NAME = 'contrast.log'
69
+ DEFAULT_LEVEL = ::Ougai::Logging::Severity::INFO
70
+ VALID_LEVELS = ::Ougai::Logging::Severity::SEV_LABEL
71
+ STDOUT_STR = 'STDOUT'
72
+ STDERR_STR = 'STDERR'
73
+
74
+ attr_reader :previous_path,
75
+ :previous_level
76
+
77
+ def initialize
78
+ update
79
+ rescue StandardError => e
80
+ logger.error('Unable to initialize regular logger in LoggerManager.', e)
81
+ end
82
+
83
+ # Given new settings from TeamServer, update our logging to use the new
84
+ # file and level, assuming they weren't set by local configuration.
85
+ #
86
+ # @param log_file [String] the file to which to log
87
+ # @param log_level [String] the level at which to log
88
+ def update log_file = nil, log_level = nil
89
+ config = CONFIG.root.agent.logger
90
+
91
+ config_path = config.path&.length.to_i.positive? ? config.path : nil
92
+ config_level = config.level&.length&.positive? ? config.level : nil
93
+
94
+ # config > settings > default
95
+ path = valid_path(config_path || log_file)
96
+ level_const = valid_level(config_level || log_level)
97
+
98
+ # don't needlessly recreate logger
99
+ return if @_logger && (path == previous_path) && (level_const == previous_level)
100
+
101
+ @previous_path = path
102
+ @previous_level = level_const
103
+
104
+ @_logger = build(path: path, level_const: level_const)
105
+
106
+ logger.debug('Initialized new contrast agent logger')
107
+ rescue StandardError => e
108
+ logger.error('Unable to process update to LoggerManager.', e)
109
+ end
110
+
111
+ def logger
112
+ @_logger
113
+ end
114
+
115
+ # StringIO is a valid path because it logs directly to a string buffer
116
+ def write_permission? path
117
+ return false if path.nil?
118
+ return true if path.is_a?(StringIO)
119
+ return File.writable?(path) if File.exist?(path)
120
+
121
+ dir_name = File.dirname(File.absolute_path(path))
122
+ File.writable?(dir_name)
123
+ end
124
+
125
+ private
126
+
127
+ def build path: STDOUT_STR, level_const: DEFAULT_LEVEL
128
+ logger = case path
129
+ when STDOUT_STR, STDERR_STR
130
+ ::Ougai::Logger.new(Object.cs__const_get(path))
131
+ else
132
+ ::Ougai::Logger.new(path)
133
+ end
134
+ logger.extend(Contrast::Ougai::Logger)
135
+ logger.progname = 'Contrast Agent'
136
+ logger.level = level_const
137
+ logger.formatter.datetime_format = '%Y-%m-%dT%H:%M:%S.%L%z'
138
+ logger
139
+ end
140
+
141
+ def valid_path path
142
+ path = path.nil? ? Contrast::Utils::ObjectShare::EMPTY_STRING : path
143
+ return path if path == STDOUT_STR
144
+ return path if path == STDERR_STR
145
+
146
+ path = DEFAULT_NAME if path.empty?
147
+ if write_permission?(path)
148
+ path
149
+ else
150
+ if File.directory?(path)
151
+ logger.error('Unable to create log in directory. Writing to standard out instead', path: path)
152
+ else
153
+ logger.error('Unable to write to log file. Writing to standard out instead', path: path)
154
+ end
155
+
156
+ STDOUT_STR
157
+ end
158
+ end
159
+
160
+ def valid_level level
161
+ level ||= DEFAULT_LEVEL
162
+ level = level.upcase
163
+ if VALID_LEVELS.include?(level)
164
+ Object.cs__const_get("::Ougai::Logging::Severity::#{ level }")
165
+ else
166
+ DEFAULT_LEVEL
167
+ end
168
+ rescue StandardError
169
+ DEFAULT_LEVEL
170
+ end
171
+ end
172
+ end
173
+ end
@@ -7,10 +7,11 @@ cs__scoped_require 'rack'
7
7
 
8
8
  cs__scoped_require 'contrast/security_exception'
9
9
  cs__scoped_require 'contrast/utils/object_share'
10
- cs__scoped_require 'contrast/utils/gemfile_reader'
11
10
  cs__scoped_require 'contrast/agent/service_heartbeat'
12
11
  cs__scoped_require 'contrast/components/interface'
13
12
  cs__scoped_require 'contrast/utils/heap_dump_util'
13
+ cs__scoped_require 'contrast/agent/request_handler'
14
+ cs__scoped_require 'contrast/agent/static_analysis'
14
15
 
15
16
  cs__scoped_require 'contrast/utils/timer'
16
17
  cs__scoped_require 'contrast/utils/freeze_util'
@@ -19,331 +20,167 @@ cs__scoped_require 'contrast/utils/service_response_util'
19
20
 
20
21
  module Contrast
21
22
  module Agent
22
- # This class allows the Agent to plug into the Rack middleware stack,
23
- # providing hooks to relevant application events, such as request start and
24
- # application code.
23
+ # This class allows the Agent to plug into the Rack middleware stack. When the
24
+ # application is first started, we initialize ourselves as a rack middleware
25
+ # inside of #initialize. Afterwards, we process each http request and response
26
+ # as it goes through the middleware stack inside of #call.
25
27
  class Middleware
26
28
  include Contrast::Components::Interface
27
- access_component :contrast_service, :logging, :agent, :analysis, :config, :scope
29
+ access_component :agent, :logging, :scope
28
30
 
29
31
  attr_reader :app
30
32
 
31
- LOG_DEBUG_MIDDLEWARE_ENV = 'middleware: log environment'
32
- LOG_DEBUG_MIDDLEWARE_LIB = 'middleware: instrument shared libraries'
33
- LOG_DEBUG_MIDDLEWARE_START = 'middleware: startup agent'
34
- LOG_DEBUG_MIDDLEWARE_SERVICE = 'middleware: starting service'
35
-
36
- # allows the Agent to function as a middleware
33
+ # Allows the Agent to function as a middleware. We perform all our one-time whole-app routines in here
34
+ # since we're only going to be initialized a single time. Our initializatoin order is:
35
+ # - log environment, configuration, and all libraries
36
+ # - start the service sending thread, responsible for sending and processing messages
37
+ # - start the heartbeat thread, which triggers service startup
38
+ # - start instrumenting libraries and do a 'catchup' patch for everything we didn't see get loaded
39
+ # - enable TracePoint, which handles all class loads and required instrumentation going forward
37
40
  #
38
41
  # @param app [Rack::Application] the application to be instrumented
39
42
  # @param _legacy_param [nil] was a flag we no longer need, but Sinatra may call it
40
- def initialize app, _legacy_param = nil
41
- @app = app
42
43
 
44
+ def initialize app, _legacy_param = nil
45
+ @app = app # THIS MUST BE FIRST AND ALWAYS SET!
43
46
  # TODO: RUBY-545 nomenclature here needs to be updated.
44
- # enabled/initialized are really only reflective of whether we were
45
- # able to parse the config, which is the bare minimum for the agent
46
- # to do anything.
47
+ # enabled/initialized are really only reflective of whether we were able to parse the config,
48
+ # which is the bare minimum for the agent to do anything.
47
49
  unless AGENT.enabled?
48
- logger.error('Contrast middleware initializer detected an early-stage setup failure (likely config parse). Disabling.')
49
- # ensure the agent is disabled (probably redundant)
50
- AGENT.disable!
50
+ logger.error(
51
+ 'Contrast middleware initializer detected an early-stage setup failure (likely config parse). Disabling.')
52
+ AGENT.disable! # ensure the agent is disabled (probably redundant)
51
53
  return
52
54
  end
55
+ agent_startup_routine
56
+ end
53
57
 
54
- logger.debug_with_time(LOG_DEBUG_MIDDLEWARE_ENV) do
58
+ def agent_startup_routine
59
+ logger.debug_with_time('middleware: log environment') do
55
60
  settings.log_environment
56
61
  settings.log_configuration
57
62
  settings.log_specific_libraries
58
63
  settings.log_all_libraries
59
64
  end
60
65
 
61
- # Initialization order should be:
62
- # - start separate service sending threads
63
- # - start heartbeat thread, which triggers service startup
64
- # - start patching to achieve instrumentation
65
-
66
- logger.debug_with_time(LOG_DEBUG_MIDDLEWARE_SERVICE) do
67
- # get threads ready to poll for messages on the queue
68
- run_service_sender_thread
69
-
70
- # sends first message to service, which triggers service startup
71
- run_service_heartbeat_thread
66
+ logger.debug_with_time('middleware: starting service') do
67
+ run_service_threads
72
68
  end
73
69
 
74
- # Default instrumentation
75
- logger.debug_with_time(LOG_DEBUG_MIDDLEWARE_LIB) do
76
- AGENT.run_instrumentation
70
+ logger.debug_with_time('middleware: instrument shared libraries and patch') do
71
+ instrument_and_patch
77
72
  end
78
73
 
74
+ AGENT.enable_tracepoint
79
75
  Contrast::Agent::AtExitHook.exit_hook
80
76
  end
81
77
 
82
- def settings
83
- Contrast::Agent::FeatureState.instance
84
- end
85
-
86
- LOG_DEBUG_MIDDLEWARE_START_CALL = 'middleware: startup agent (call)'
87
- # def _call env
78
+ # This is where we're hooked into the middleware stack. If the agent is enabled, we're ready
79
+ # to do some processing on a per request basis. If not, we just pass the request along to the
80
+ # next middleware in the stack.
81
+ #
82
+ # @param env [Hash] the various variables stored by this and other Middlewares to know the state
83
+ # and values of this Request
84
+ # @return [Array,Rack::Response] the Response of this and subsequent Middlewares to be passed back
85
+ # to the user up the Rack framework.
88
86
  def call env
89
87
  Contrast::Utils::HeapDumpUtil.run
90
88
 
91
89
  if AGENT.enabled?
92
- response = call_with_agent(env)
93
- with_contrast_scope { do_static_analysis_catchup }
94
- response
90
+ Contrast::Agent::StaticAnalysis.catchup
91
+ call_with_agent(env)
95
92
  else
96
- call_without_agent(env)
93
+ app.call(env)
97
94
  end
98
95
  end
99
96
 
100
- def call_without_agent env
101
- app.call(env)
102
- end
97
+ private
103
98
 
104
- REQUEST_PATH = 'REQUEST_PATH'
105
- LOG_DEBUG_REQUEST = 'HTTP request cycle'
99
+ # This is where we process each request we intercept as a middleware. We make the request context
100
+ # available globally so that it can be accessed from anywhere. A RequestHandler object is made
101
+ # for each request, which handles prefilter and postfilter operations.
106
102
  def call_with_agent env
107
- rack_request = generate_request(env)
103
+ framework_request = Contrast::Agent.framework_manager.retrieve_request(env)
104
+ context = Contrast::Agent::RequestContext.new(framework_request)
105
+ response = nil
108
106
 
109
- context = Contrast::Agent::RequestContext.new(rack_request, true) # 'true' here is legacy, by the time we're here, we're ready
110
-
111
- # default response
112
- streaming = false
113
107
  # make the context available for the lifecycle of this request
114
108
  Contrast::Agent::REQUEST_TRACKER.lifespan(context) do
115
- # record entire time
116
- logger.debug_with_time(LOG_DEBUG_REQUEST) do
117
- # process filters that can short circuit application processing
109
+ request_handler = Contrast::Agent::RequestHandler.new(context)
110
+
111
+ logger.debug_with_time('HTTP request cycle') do
112
+ # prefilter sequence
118
113
  with_contrast_scope do
119
114
  context.service_extract_request
120
- prefilter(context)
115
+ request_handler.ruleset.prefilter
121
116
  end
122
117
 
123
- # run application by passing request down the Rack chain using
124
- # the original env
125
- response = application_code(env)
118
+ response = application_code(env) # pass request down the Rack chain with original env
126
119
 
127
- # if streaming, allow for early return with application response
128
- streaming = possibly_streaming?(env)
129
- if streaming
130
- with_contrast_scope { postfilter(context, streaming) }
131
- return response
120
+ # postfilter sequence
121
+ with_contrast_scope do
122
+ context.extract_after(response) # update context with final response information
123
+
124
+ if Contrast::Agent.framework_manager.streaming?(env)
125
+ context.reset_activity
126
+ request_handler.stream_safe_postfilter
127
+ else
128
+ request_handler.ruleset.postfilter
129
+ # return response stored in the context in case any postfilter rules updated the response data
130
+ response = context.response&.rack_response || response
131
+ request_handler.send_activity_messages
132
+ end
132
133
  end
133
-
134
- # update context with final response information
135
- context.extract_after(response)
136
-
137
- # process filters that look at response headers and body
138
- with_contrast_scope { postfilter(context) }
139
134
  end
140
135
  end
141
136
 
142
- # return the response stored in the context in case any postfilter rules
143
- # updated the response data
144
- context&.response&.rack_response || response
145
-
146
- # handle security exception
137
+ response
147
138
  rescue StandardError => e
148
139
  handle_exception(e)
149
- ensure
150
- begin
151
- handle_ensure(context, streaming)
152
- rescue Exception => e # rubocop:disable Lint/RescueException
153
- logger.error(e, 'Exception raised while flushing messages to Contrast service!')
154
- raise
155
- end
156
140
  end
157
141
 
158
- LOG_WARN_FRAMEWORK_PARSE = 'Unable to generate framework specific request - falling back to Rack'
159
- # Given the rack environment of this call, generate a framework specific
160
- # request object to bind to this context. In the event that multiple
161
- # supported frameworks are defined OR we cannot determine the framework
162
- # currently in use or there is an exception during request generation, we
163
- # will fall back on Rack::Request object
164
- def generate_request env
165
- rails_defined = defined?(Rails)
166
- sinatra_defined = defined?(Sinatra) && defined?(Sinatra::Request)
167
-
168
- if rails_defined && !sinatra_defined
169
- # code from /lib/action_cable/connection/base
170
- environment = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
171
- ActionDispatch::Request.new(environment || env)
172
- # !defined? currently redundant, won't be if we have more frameworks
173
- elsif sinatra_defined && !rails_defined
174
- Sinatra::Request.new(env)
175
- else # many OR none
176
- Rack::Request.new(env)
177
- end
178
- rescue StandardError => e
179
- logger.warn(e, LOG_WARN_FRAMEWORK_PARSE)
180
- Rack::Request.new(env)
181
- end
182
-
183
- LOG_ERROR_STREAM_CHECK = 'Unable to check for streaming'
184
- ACTION_CONTROLLER_INSTANCE = 'action_controller.instance'
185
- # First check to see if an action could potentially be streaming a response
186
- def possibly_streaming? env
187
- return false unless defined?(ActionController::Live)
188
-
189
- env[ACTION_CONTROLLER_INSTANCE].cs__class.included_modules.include?(ActionController::Live)
190
- rescue StandardError => e
191
- logger.warn(LOG_ERROR_STREAM_CHECK, e)
192
- end
193
-
194
- LOG_ERROR_ENSURE = 'Context not defined in middleware ensure.'
195
- # Send a server activity message and an application activity message
196
- # and return response
197
- def handle_ensure context, streaming
198
- if context
199
- logger.debug('Middleware request lifecycle complete; flushing context activity to Contrast service.')
200
- Contrast::Utils::GemfileReader.instance.generate_library_usage(context.activity)
201
- [context.server_activity, context.activity, context.observed_route].each do |message|
202
- CONTRAST_SERVICE.send_message message
203
- end
204
- else
205
- logger.error(LOG_ERROR_ENSURE)
142
+ def application_code env
143
+ logger.trace_with_time('application') do
144
+ app.call(env)
206
145
  end
207
- return unless streaming
208
-
209
- context.reset_activity
146
+ rescue Contrast::SecurityException => e
147
+ logger.trace('Security Exception raised during application lifecycle to prevent an attack', e)
148
+ raise e
210
149
  end
211
150
 
212
151
  SECURITY_EXCEPTION_MARKER = 'Contrast::SecurityException'
213
- LOG_RETHROW_ERROR = 'Re-throwing original error'
214
152
  # We're only going to suppress SecurityExceptions indicating a blocked attack.
215
153
  # And, only if the config.agent.ruby.exceptions.capture? is set
216
154
  def handle_exception exception
217
155
  if exception.is_a?(Contrast::SecurityException) ||
218
156
  exception.message&.include?(SECURITY_EXCEPTION_MARKER)
219
157
 
220
- exception_control = Contrast::Agent::FeatureState.instance.exception_control
158
+ exception_control = settings.exception_control
221
159
  raise exception unless exception_control[:enable]
222
160
 
223
161
  [exception_control[:status], {}, [exception_control[:message]]]
224
162
  else
225
- # Log original re-raise
226
- logger.debug(exception, LOG_RETHROW_ERROR)
163
+ logger.debug('Re-throwing original error', exception)
227
164
  raise exception
228
165
  end
229
166
  end
230
167
 
231
- LOG_DEBUG_PREFILTER = 'prefilter'
232
- LOG_ERROR_PREFILTER = 'Unexpected exception during prefilter'
233
- # Iterate through rules that only depend upon the request object.
234
- def prefilter context
235
- return unless context.app_loaded?
236
-
237
- logger.debug_with_time(LOG_DEBUG_PREFILTER) do
238
- prefilter_assess(context) if ASSESS.enabled? && context.analyze_request?
239
- prefilter_protect(context) if PROTECT.enabled?
240
- end
241
- rescue Contrast::SecurityException => e
242
- logger.warn("RASP threw security exception in prefilter: exception=#{ e.message }")
243
- raise e
244
- rescue StandardError => e
245
- logger.error(LOG_ERROR_PREFILTER, e)
246
- end
247
-
248
- def prefilter_assess context
249
- rules = ASSESS.rules
250
- logger.debug("Assess: Running #{ rules.length } rules in prefilter.")
251
- prefilter_rules(rules, context)
252
- end
253
-
254
- def prefilter_protect context
255
- rules = PROTECT.rules
256
- logger.debug("Protect: Running #{ rules.length } rules in prefilter.")
257
- prefilter_rules(rules, context)
258
- end
259
-
260
- def prefilter_rules rules, context
261
- rules.each do |_, rule|
262
- rule.prefilter(context)
263
- end
264
- end
265
-
266
- LOG_DEBUG_APPLICATION = 'application'
267
- # Run the next level of the Rack stack as normal
268
- def application_code env
269
- logger.debug_with_time(LOG_DEBUG_APPLICATION) do
270
- app.call(env)
271
- end
272
- rescue Contrast::SecurityException => e
273
- logger.info("RASP threw security exception in application code: exception=#{ e.message }")
274
- raise e
275
- end
276
-
277
- LOG_DEBUG_POSTFILTER = 'postfilter'
278
- LOG_ERROR_POSTFILTER = 'Unexpected exception during postfilter'
279
- # Iterate through rules that depend on the full response object
280
- def postfilter context, streaming = false
281
- return unless context.app_loaded?
282
-
283
- logger.debug_with_time(LOG_DEBUG_POSTFILTER) do
284
- if ASSESS.enabled? && context.analyze_response?
285
- logger.debug("Assess:\tRunning #{ ASSESS.rules.length } rules in postfilter.")
286
- postfilter_rules(ASSESS.rules, context, streaming)
287
- end
288
-
289
- if PROTECT.enabled?
290
- logger.debug("Protect:\tRunning #{ PROTECT.rules.length } rules in postfilter.")
291
- postfilter_rules(PROTECT.rules, context, streaming)
292
- end
293
- end
294
- rescue Contrast::SecurityException => e
295
- logger.warn("RASP threw security exception: exception=#{ e.message }")
296
- raise e
297
- rescue StandardError => e
298
- logger.error(LOG_ERROR_POSTFILTER, e)
299
- end
300
-
301
- # Iterate through a list of rules with the current context and the full response body
302
- def postfilter_rules rules, context, streaming
303
- rules.each do |_, rule|
304
- if !streaming || rule.stream_safe?
305
- rule.postfilter(context)
306
- else
307
- logger.debug("Skipping rule: #{ rule.name } in streamed response.")
308
- end
309
- end
310
- end
311
-
312
- def run_service_heartbeat_thread
313
- # Rspec stubs over this method for simplicity's sake in testing.
314
- # Take care if you refactor this back into #initialize.
315
- Contrast::Agent::ServiceHeartbeat.new.start
168
+ def settings
169
+ Contrast::Agent::FeatureState.instance
316
170
  end
317
171
 
318
- def run_service_sender_thread
319
- # Rspec stubs over this method for simplicity's sake in testing.
320
- # Take care if you refactor this back into #initialize.
172
+ # Rspec stubs over these methods for simplicity's sake in testing
173
+ def run_service_threads
321
174
  Contrast::Utils::ServiceSenderUtil.start
175
+ Contrast::Agent::ServiceHeartbeat.new.start
322
176
  end
323
177
 
324
- LOG_DEBUG_MW_INV = 'middleware: send inventory'
325
- LOG_WARN_STATIC_ANALYSIS = 'Unable to run post-initialization static analysis'
326
- # this is memoized, should only be meaningful after the first agented
327
- # HTTP request
328
- def do_static_analysis_catchup
329
- @_do_static_analysis_catchup ||= begin
330
- # Everything in here should be asynchronous, as we need to return
331
- # the HTTP response from middleware ASAP.
332
-
333
- # Review already-loaded inventory
334
- logger.debug_with_time('initializer: report loaded gemset') do
335
- Contrast::Utils::GemfileReader.instance.map_loaded_classes
336
- end
337
-
338
- # Report already-loaded inventory
339
- logger.debug_with_time(LOG_DEBUG_MW_INV) do
340
- settings.send_inventory_message
341
- end
342
-
343
- true
344
- end
345
- rescue StandardError => e
346
- logger.warn(LOG_WARN_STATIC_ANALYSIS, e)
178
+ # All this method chain does anymore is load the Thread patch that
179
+ # propagates request contexts. That can go away RUBY-700.
180
+ SHARED_LIBRARIES = %w[contrast/extensions/ruby_core/thread].cs__freeze
181
+ def instrument_and_patch
182
+ SHARED_LIBRARIES.each { |lib| settings.instrument(lib) }
183
+ Contrast::Agent::Patching::Policy::Patcher.patch
347
184
  end
348
185
  end
349
186
  end