contrast-agent 6.9.0 → 6.10.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (94) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +1 -1
  3. data/lib/contrast/agent/assess/rule/response/body_rule.rb +1 -1
  4. data/lib/contrast/agent/middleware.rb +4 -2
  5. data/lib/contrast/agent/protect/input_analyzer/input_analyzer.rb +76 -83
  6. data/lib/contrast/agent/protect/input_analyzer/worth_watching_analyzer.rb +40 -35
  7. data/lib/contrast/agent/protect/policy/applies_command_injection_rule.rb +2 -0
  8. data/lib/contrast/agent/protect/policy/applies_no_sqli_rule.rb +6 -3
  9. data/lib/contrast/agent/protect/policy/applies_path_traversal_rule.rb +3 -0
  10. data/lib/contrast/agent/protect/policy/applies_sqli_rule.rb +3 -0
  11. data/lib/contrast/agent/protect/policy/rule_applicator.rb +12 -0
  12. data/lib/contrast/agent/protect/rule/base.rb +19 -5
  13. data/lib/contrast/agent/protect/rule/base_service.rb +6 -0
  14. data/lib/contrast/agent/protect/rule/bot_blocker/bot_blocker_input_classification.rb +1 -1
  15. data/lib/contrast/agent/protect/rule/bot_blocker.rb +8 -0
  16. data/lib/contrast/agent/protect/rule/cmdi/cmdi_base_rule.rb +8 -0
  17. data/lib/contrast/agent/protect/rule/deserialization.rb +2 -2
  18. data/lib/contrast/agent/protect/rule/no_sqli.rb +24 -2
  19. data/lib/contrast/agent/protect/rule/path_traversal/path_traversal_input_classification.rb +1 -1
  20. data/lib/contrast/agent/protect/rule/path_traversal.rb +8 -0
  21. data/lib/contrast/agent/protect/rule/sqli/sqli_input_classification.rb +0 -1
  22. data/lib/contrast/agent/protect/rule/sqli.rb +6 -10
  23. data/lib/contrast/agent/protect/rule/unsafe_file_upload/unsafe_file_upload_input_classification.rb +6 -2
  24. data/lib/contrast/agent/protect/rule/unsafe_file_upload.rb +20 -0
  25. data/lib/contrast/agent/protect/rule/xss/reflected_xss_input_classification.rb +1 -1
  26. data/lib/contrast/agent/protect/rule/xss.rb +8 -0
  27. data/lib/contrast/agent/protect/rule/xxe.rb +2 -2
  28. data/lib/contrast/agent/protect/rule.rb +0 -3
  29. data/lib/contrast/agent/reporting/attack_result/user_input.rb +0 -1
  30. data/lib/contrast/agent/reporting/details/details.rb +0 -1
  31. data/lib/contrast/agent/reporting/input_analysis/input_analysis.rb +12 -0
  32. data/lib/contrast/agent/reporting/report.rb +1 -0
  33. data/lib/contrast/agent/reporting/reporter.rb +11 -10
  34. data/lib/contrast/agent/reporting/reporting_events/application_activity.rb +4 -5
  35. data/lib/contrast/agent/reporting/reporting_events/application_defend_activity.rb +13 -1
  36. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_activity.rb +20 -5
  37. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_sample.rb +0 -1
  38. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_sample_activity.rb +5 -0
  39. data/lib/contrast/agent/reporting/reporting_events/application_defend_attacker_activity.rb +10 -1
  40. data/lib/contrast/agent/reporting/reporting_events/application_inventory.rb +2 -1
  41. data/lib/contrast/agent/reporting/reporting_events/application_reporting_event.rb +10 -0
  42. data/lib/contrast/agent/reporting/reporting_events/application_settings.rb +40 -0
  43. data/lib/contrast/agent/reporting/reporting_utilities/ng_response_extractor.rb +137 -0
  44. data/lib/contrast/agent/reporting/reporting_utilities/reporter_client.rb +12 -4
  45. data/lib/contrast/agent/reporting/reporting_utilities/response_extractor.rb +100 -107
  46. data/lib/contrast/agent/reporting/reporting_utilities/response_handler.rb +5 -4
  47. data/lib/contrast/agent/reporting/reporting_utilities/response_handler_utils.rb +97 -63
  48. data/lib/contrast/agent/reporting/reporting_workers/application_server_worker.rb +46 -0
  49. data/lib/contrast/agent/reporting/reporting_workers/reporter_heartbeat.rb +51 -0
  50. data/lib/contrast/agent/reporting/reporting_workers/reporting_workers.rb +14 -0
  51. data/lib/contrast/agent/reporting/reporting_workers/server_settings_worker.rb +46 -0
  52. data/lib/contrast/agent/reporting/settings/assess.rb +14 -1
  53. data/lib/contrast/agent/reporting/settings/assess_rule.rb +18 -0
  54. data/lib/contrast/agent/reporting/settings/helpers.rb +4 -2
  55. data/lib/contrast/agent/reporting/settings/protect.rb +17 -12
  56. data/lib/contrast/agent/reporting/settings/protect_rule.rb +18 -0
  57. data/lib/contrast/agent/reporting/settings/protect_server_feature.rb +1 -1
  58. data/lib/contrast/agent/reporting/settings/sensitive_data_masking.rb +1 -1
  59. data/lib/contrast/agent/reporting/settings/virtual_patch.rb +56 -0
  60. data/lib/contrast/agent/reporting/settings/virtual_patch_condition.rb +47 -0
  61. data/lib/contrast/agent/request_context_extend.rb +20 -0
  62. data/lib/contrast/agent/telemetry/base.rb +11 -10
  63. data/lib/contrast/agent/telemetry/events/exceptions/obfuscate.rb +108 -103
  64. data/lib/contrast/agent/telemetry/events/startup_metrics_event.rb +1 -1
  65. data/lib/contrast/agent/thread_watcher.rb +16 -10
  66. data/lib/contrast/agent/version.rb +1 -1
  67. data/lib/contrast/agent.rb +12 -0
  68. data/lib/contrast/agent_lib/api/init.rb +1 -7
  69. data/lib/contrast/agent_lib/api/input_tracing.rb +2 -4
  70. data/lib/contrast/agent_lib/interface.rb +1 -16
  71. data/lib/contrast/agent_lib/interface_base.rb +52 -39
  72. data/lib/contrast/agent_lib/return_types/eval_result.rb +2 -2
  73. data/lib/contrast/components/assess.rb +26 -4
  74. data/lib/contrast/components/polling.rb +4 -1
  75. data/lib/contrast/components/settings.rb +46 -3
  76. data/lib/contrast/config/config.rb +2 -2
  77. data/lib/contrast/config/protect_rule_configuration.rb +1 -1
  78. data/lib/contrast/config/protect_rules_configuration.rb +1 -1
  79. data/lib/contrast/extension/assess/array.rb +3 -3
  80. data/lib/contrast/extension/assess/regexp.rb +2 -2
  81. data/lib/contrast/logger/aliased_logging.rb +48 -15
  82. data/lib/contrast/utils/input_classification_base.rb +21 -4
  83. data/lib/contrast/utils/routes_sent.rb +2 -2
  84. data/lib/contrast/utils/telemetry.rb +1 -1
  85. data/lib/contrast/utils/telemetry_client.rb +1 -1
  86. data/resources/protect/policy.json +8 -0
  87. data/ruby-agent.gemspec +1 -1
  88. metadata +28 -18
  89. data/lib/contrast/agent/protect/rule/http_method_tampering/http_method_tampering_input_classification.rb +0 -96
  90. data/lib/contrast/agent/protect/rule/http_method_tampering.rb +0 -83
  91. data/lib/contrast/agent/reporting/details/http_method_tempering_details.rb +0 -27
  92. data/lib/contrast/agent/reporting/reporter_heartbeat.rb +0 -47
  93. data/lib/contrast/agent/reporting/server_settings_worker.rb +0 -44
  94. data/lib/contrast/agent_lib/api/method_tempering.rb +0 -29
@@ -0,0 +1,47 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: true
3
+
4
+ require 'contrast/utils/object_share'
5
+ require 'contrast/agent/reporting/settings/protect_rule'
6
+
7
+ module Contrast
8
+ module Agent
9
+ module Reporting
10
+ module Settings
11
+ # The settings for each virtual patch condition in the agent.
12
+ class VirtualPatchCondition
13
+ # @return [String]
14
+ attr_reader :name
15
+ # @return [String]
16
+ attr_reader :value
17
+ # @return [String]
18
+ attr_reader :input_type
19
+ # @return [String]
20
+ attr_reader :evaluation
21
+
22
+ def initialize hash
23
+ @name = hash[:name]
24
+ @value = hash[:value]
25
+ @input_type = hash[:input_type]
26
+ @evaluation = hash[:evaluation]
27
+ end
28
+
29
+ # @return [Array<Contrast::Agent::Reporting::Settings::VirtualPatchCondition>]
30
+ def headers
31
+ @_headers ||= []
32
+ end
33
+
34
+ # @return [Array<Contrast::Agent::Reporting::Settings::VirtualPatchCondition>]
35
+ def parameters
36
+ @_parameters ||= []
37
+ end
38
+
39
+ # @return [Array<Contrast::Agent::Reporting::Settings::VirtualPatchCondition>]
40
+ def urls
41
+ @_urls ||= []
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -50,6 +50,10 @@ module Contrast
50
50
  return false if @do_not_track
51
51
 
52
52
  if (ia = Contrast::Agent::Protect::InputAnalyzer.analyse(request))
53
+ # Handle prefilter
54
+ Contrast::Agent::Protect::InputAnalyzer.input_classification(ia, prefilter: true)
55
+ # Reflected xss infilter
56
+ Contrast::Agent::Protect::InputAnalyzer.input_classification_for('reflected-xss', ia)
53
57
  @agent_input_analysis = ia
54
58
  else
55
59
  logger.trace('Analysis from Agent was empty.')
@@ -60,6 +64,22 @@ module Contrast
60
64
  logger.warn('Unable to extract protect information from request', e)
61
65
  end
62
66
 
67
+ # Builds IA only for postfilter rules. If rules during infilter were not triggered there will be
68
+ # no IA for them later to use it in postfilter.
69
+ #
70
+ # @raise [Contrast::SecurityException]
71
+ def protect_postfilter_ia
72
+ return false unless ::Contrast::AGENT.enabled?
73
+ return false unless ::Contrast::PROTECT.enabled?
74
+
75
+ # Handle postfilter
76
+ Contrast::Agent::Protect::InputAnalyzer.input_classification(@agent_input_analysis, postfilter: true)
77
+ rescue Contrast::SecurityException => e
78
+ raise(e)
79
+ rescue StandardError => e
80
+ logger.warn('Unable to extract protect information from request - postfilter', e)
81
+ end
82
+
63
83
  # append anything we've learned to the request seen message this is the sum-total of all inventory information
64
84
  # that has been accumulated since the last request
65
85
  def extract_after rack_response
@@ -48,7 +48,8 @@ module Contrast
48
48
  @_client = Contrast::Utils::TelemetryClient.new
49
49
  ip_opt_out_telemetry = @_client.initialize_connection(URL)
50
50
  if ip_opt_out_telemetry.nil?
51
- logger.warn("Connection was not established properly!!! \n Telemetry reporting will be disabled!")
51
+ logger.warn("[Telemetry] Connection was not established properly!!! \n
52
+ Telemetry reporting will be disabled!")
52
53
  return false
53
54
  end
54
55
 
@@ -66,30 +67,30 @@ module Contrast
66
67
 
67
68
  def attempt_to_start?
68
69
  unless cs__class.enabled?
69
- logger.warn('Telemetry service is disabled!')
70
+ logger.info('[Telemetry] Telemetry service is disabled!')
70
71
  return false
71
72
  end
72
73
 
73
- logger.debug('Attempting to start telemetry thread') unless running?
74
+ logger.debug('[Telemetry] Attempting to start telemetry thread') unless running?
74
75
  true
75
76
  end
76
77
 
77
78
  def start_thread!
78
79
  return if running?
79
80
 
80
- logger.debug('Starting background telemetry thread.')
81
+ logger.debug('[Telemetry] Starting background telemetry thread.')
81
82
  @_thread = create_thread
82
83
  end
83
84
 
84
85
  def send_event event
85
86
  if ::Contrast::AGENT.disabled?
86
- logger.warn('Attempted to queue event with Agent disabled', caller: caller, event: event)
87
+ logger.warn('[Telemetry] Attempted to queue event with Agent disabled', caller: caller, event: event)
87
88
  return
88
89
  end
89
90
 
90
91
  return unless cs__class.enabled?
91
92
 
92
- logger.debug('Enqueued event for sending', event_type: event.cs__class)
93
+ logger.debug('[Telemetry] Enqueued event for sending', event_type: event.cs__class)
93
94
  queue << event if event
94
95
  end
95
96
 
@@ -120,7 +121,7 @@ module Contrast
120
121
  # It is recommended that implementations send a single payload of general metrics every 3 hours, starting from
121
122
  # implementation startup. This returns a thread configured to do so.
122
123
  #
123
- # @return [Contrast::Agent::Thread]
124
+ # @return [::Thread] Contrast::Agent::Thread
124
125
  def create_thread
125
126
  Contrast::Agent::Thread.new do
126
127
  loop do
@@ -132,16 +133,16 @@ module Contrast
132
133
  until queue.empty?
133
134
  event = queue.pop
134
135
  begin
135
- logger.debug('This is the current processed event', event)
136
+ logger.debug('[Telemetry] This is the current processed event', event)
136
137
  sleep_time = request_with_response(event)
137
138
  if sleep_time
138
139
  sleep(sleep_time)
139
- logger.debug('Retrying to process event', event)
140
+ logger.debug('[Telemetry] Retrying to process event', event)
140
141
  retry_sleep_time = request_with_response(event)
141
142
  sleep(retry_sleep_time) unless retry_sleep_time.nil?
142
143
  end
143
144
  rescue StandardError => e
144
- logger.error('Could not send message to service from telemetry queue.', e)
145
+ logger.error('[Telemetry] Could not send message to service from telemetry queue.', e)
145
146
  stop!
146
147
  end
147
148
  end
@@ -7,111 +7,116 @@ module Contrast
7
7
  module TelemetryException
8
8
  # Here will be all known gems to obfuscate during the building of TelemetryExceptions
9
9
  module Obfuscate
10
+ # TODO: RUBY-1984 Re-enable/Remove Telemetry Obfuscation.
11
+ #
10
12
  # List of known gems to be third parties not containing any
11
13
  # user sensitive data.
12
- KNOWN_GEMS = %w[
13
- activesupport redis-activesupport redis builder dry-types rails rails-html-sanitizer rails-observers sinatra
14
- benchmark-ips bundler climate_control execjs factory_bot debride fake_ftp fasterer flay openssl
15
- parallel_tests contrast contrast-agent ruby pry-byebug byebug pry resolv ougai protobuf async nokogiri
16
- benchmark grape-order grape-activerecord newrelic newrelic-grape grape-rails-cache grape-msgpack
17
- grape-batch rspec rake rubocop grape-jbuilder rack-test rack-protection minitest grape-instrumentation
18
- minitest-global_expectations rack-proxy rack-attack rack-ssl grape-cancan grape-attack grape-rake-tasks
19
- grape-route-helpers benchmark-memory grape-rabl grape-kaminari grape-path-helpers grape-swagger-entity
20
- grape-swagger-rails grape-roar newrelic-rake grapes-wagger-representative grape-forgery_protection
21
- grape-papertrail grape-app grape-middleware-logger rack-protection rake-compile rhino rspec-benchmark
22
- rspec_junit_formatter rspec-rails rake-performance rubocop-rails rubocop-rake rubocop-rspec
23
- ruby-debug-ide simplecov sqlite steep tilt tzinfo-data warning xpath sinatra-activerecord sinatra-param
24
- sinatra-partial sinatra-flash sinatra-reloader sinatra-sinatra rake_fly rack rack-accept grape grape-entity
25
- sinatra-advanced-routes sinatra-warden grape_logging grape-swagger sinatra-namespace sinatra-resource
26
- sinatra-hashfix sinatra-instrumentation sinatra-helpers redis-rack sinatra-support sinatra-assetpack
27
- sinatra-router sinatra-cross_origin sinatra_more sinatra-jsonp faraday-rack zlib mustermann mustermann-grape
28
- rspec-expectations rspec-core rspec-mocks rspec-sidekiq
29
- ].cs__freeze
30
- KNOWN_ERRORS = %w[
31
- ActiveModel Error Errors Resolv Rspec ActiveRecord nil NilClass NoMemoryError ScriptError
32
- LoadError NotImplementedError SyntaxError SecurityError SignalException Interrupt
33
- StandardError ArgumentError UncaughtThrowError FiberError IOError EOFError IndexError KeyError
34
- StopIteration LocalJumpError NameError NoMethodError RangeError FloatDomainError RegexpError
35
- RuntimeError FrozenError SystemCallError ThreadError TypeError ZeroDivisionError SystemExit
36
- SystemStackError fatal Warning buffer OpenSSL SSL SSLError Errno Timeout Exception EOFError
37
- ECONNRESET ECONNREFUSED ETIMEDOUT EINVAL ESHUTDOWN EHOSTDOWN EHOSTUNREACH EISCONN
38
- ECONNABORTED ENETRESET ENETUNREACH Net HTTPBadResponse HTTPHeaderSyntaxError ProtocolError
39
- Faraday BadRequestError UnauthorizedError ForbiddenError ResourceNotFound ProxyAuthError
40
- ConflictError UnprocessableEntityError ClientError
41
- ].cs__freeze
42
- CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.cs__freeze
43
- # This will generate different chars for each agent startup but will be constant
44
- # for current run and will make identical obfuscation to be compared if given type
45
- # is the same.
46
- CYPHER = CHARS.chars.shuffle.join
47
-
48
- class << self
49
- # Returns paths for known gems.
50
- #
51
- # @return [Array<Regexp>] known paths
52
- def known_gem_paths
53
- @_known_gem_paths ||= KNOWN_GEMS.map do |gem_name|
54
- to_regexp(File.join(
55
- 'gems', gem_name.tr('-', ''), 'lib'))
56
- end
57
- end
58
-
59
- # Returns known modules names.
60
- #
61
- # @return [Array<Regexp>] known modules
62
- def known_modules
63
- @_known_modules ||= KNOWN_ERRORS.map { |module_name| to_regexp(module_name) }
64
- end
65
-
66
- # Obfuscate a type and replace it with random characters.
67
- #
68
- # @param type [String] the StackFrame type to obfuscate
69
- # @return [String] obfuscated type
70
- def obfuscate_type type
71
- return unless type
72
-
73
- check = type.tr('[^0-9].-', '')
74
- type = cypher(type) unless match_known(known_gem_paths, check)
75
- type
76
- end
77
-
78
- # Obfuscate a type and replace it with random characters.
79
- #
80
- # @param exception_type [String] the exception type to obfuscate
81
- # @return [String] obfuscated exception type
82
- def obfuscate_exception_type exception_type
83
- return unless exception_type
84
-
85
- exceptions = exception_type.split('::').each do |exception|
86
- cypher(exception) unless match_known(known_modules, exception)
87
- end
88
- exceptions.join('::')
89
- end
90
-
91
- private
92
-
93
- # Transforms string to regexp
94
- #
95
- # @param string [String]
96
- def to_regexp string
97
- /#{ string }/
98
- end
99
-
100
- # Add cypher to path to make it obscure, but unique enough for
101
- # comparisons. Mutates original or duplicate if frozen string.
102
- #
103
- # @param string [String] string to be transformed.
104
- def cypher string
105
- string = string.dup if string.cs__frozen?
106
- string.to_s.tr!(CHARS, CYPHER)
107
- end
108
-
109
- # @param known [Array<Regexp>] Array of regexp to match againts
110
- # @param type [String] type to check
111
- def match_known known, type
112
- known.any? { |regexp| type =~ regexp }
113
- end
114
- end
14
+ # KNOWN_GEMS = %w[
15
+ # activesupport redis-activesupport redis builder dry-types rails rails-html-sanitizer rails-observers
16
+ # sinatra
17
+ # benchmark-ips bundler climate_control execjs factory_bot debride fake_ftp fasterer flay openssl
18
+ # parallel_tests contrast contrast-agent ruby pry-byebug byebug pry resolv ougai protobuf async nokogiri
19
+ # benchmark grape-order grape-activerecord newrelic newrelic-grape grape-rails-cache grape-msgpack
20
+ # grape-batch rspec rake rubocop grape-jbuilder rack-test rack-protection minitest grape-instrumentation
21
+ # minitest-global_expectations rack-proxy rack-attack rack-ssl grape-cancan grape-attack grape-rake-tasks
22
+ # grape-route-helpers benchmark-memory grape-rabl grape-kaminari grape-path-helpers grape-swagger-entity
23
+ # grape-swagger-rails grape-roar newrelic-rake grapes-wagger-representative grape-forgery_protection
24
+ # grape-papertrail grape-app grape-middleware-logger rack-protection rake-compile rhino rspec-benchmark
25
+ # rspec_junit_formatter rspec-rails rake-performance rubocop-rails rubocop-rake rubocop-rspec
26
+ # ruby-debug-ide simplecov sqlite steep tilt tzinfo-data warning xpath sinatra-activerecord sinatra-param
27
+ # sinatra-partial sinatra-flash sinatra-reloader sinatra-sinatra rake_fly rack rack-accept grape
28
+ # grape-entity
29
+ # sinatra-advanced-routes sinatra-warden grape_logging grape-swagger sinatra-namespace sinatra-resource
30
+ # sinatra-hashfix sinatra-instrumentation sinatra-helpers redis-rack sinatra-support sinatra-assetpack
31
+ # sinatra-router sinatra-cross_origin sinatra_more sinatra-jsonp faraday-rack zlib mustermann
32
+ # mustermann-grape
33
+ # rspec-expectations rspec-core rspec-mocks rspec-sidekiq
34
+ # ].cs__freeze
35
+ # KNOWN_ERRORS = %w[
36
+ # ActiveModel Error Errors Resolv Rspec ActiveRecord nil NilClass NoMemoryError ScriptError
37
+ # LoadError NotImplementedError SyntaxError SecurityError SignalException Interrupt
38
+ # StandardError ArgumentError UncaughtThrowError FiberError IOError EOFError IndexError KeyError
39
+ # StopIteration LocalJumpError NameError NoMethodError RangeError FloatDomainError RegexpError
40
+ # RuntimeError FrozenError SystemCallError ThreadError TypeError ZeroDivisionError SystemExit
41
+ # SystemStackError fatal Warning buffer OpenSSL SSL SSLError Errno Timeout Exception EOFError
42
+ # ECONNRESET ECONNREFUSED ETIMEDOUT EINVAL ESHUTDOWN EHOSTDOWN EHOSTUNREACH EISCONN
43
+ # ECONNABORTED ENETRESET ENETUNREACH Net HTTPBadResponse HTTPHeaderSyntaxError ProtocolError
44
+ # Faraday BadRequestError UnauthorizedError ForbiddenError ResourceNotFound ProxyAuthError
45
+ # ConflictError UnprocessableEntityError ClientError
46
+ # ].cs__freeze
47
+ # CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.cs__freeze
48
+ # # This will generate different chars for each agent startup but will be constant
49
+ # # for current run and will make identical obfuscation to be compared if given type
50
+ # # is the same.
51
+ # CYPHER = CHARS.chars.shuffle.join
52
+ #
53
+ # class << self
54
+ # # Returns paths for known gems.
55
+ # #
56
+ # # @return [Array<Regexp>] known paths
57
+ # def known_gem_paths
58
+ # @_known_gem_paths ||= KNOWN_GEMS.map do |gem_name|
59
+ # to_regexp(File.join(
60
+ # 'gems', gem_name.tr('-', ''), 'lib'))
61
+ # end
62
+ # end
63
+ #
64
+ # # Returns known modules names.
65
+ # #
66
+ # # @return [Array<Regexp>] known modules
67
+ # def known_modules
68
+ # @_known_modules ||= KNOWN_ERRORS.map { |module_name| to_regexp(module_name) }
69
+ # end
70
+ #
71
+ # # Obfuscate a type and replace it with random characters.
72
+ # #
73
+ # # @param type [String] the StackFrame type to obfuscate
74
+ # # @return [String] obfuscated type
75
+ # def obfuscate_type type
76
+ # return unless type
77
+ #
78
+ # check = type.tr('[^0-9].-', '')
79
+ # type = cypher(type) unless match_known(known_gem_paths, check)
80
+ # type
81
+ # end
82
+ #
83
+ # # Obfuscate a type and replace it with random characters.
84
+ # #
85
+ # # @param exception_type [String] the exception type to obfuscate
86
+ # # @return [String] obfuscated exception type
87
+ # def obfuscate_exception_type exception_type
88
+ # return unless exception_type
89
+ #
90
+ # exceptions = exception_type.split('::').each do |exception|
91
+ # cypher(exception) unless match_known(known_modules, exception)
92
+ # end
93
+ # exceptions.join('::')
94
+ # end
95
+ #
96
+ # private
97
+ #
98
+ # # Transforms string to regexp
99
+ # #
100
+ # # @param string [String]
101
+ # def to_regexp string
102
+ # /#{ string }/
103
+ # end
104
+ #
105
+ # # Add cypher to path to make it obscure, but unique enough for
106
+ # # comparisons. Mutates original or duplicate if frozen string.
107
+ # #
108
+ # # @param string [String] string to be transformed.
109
+ # def cypher string
110
+ # string = string.dup if string.cs__frozen?
111
+ # string.to_s.tr!(CHARS, CYPHER)
112
+ # end
113
+ #
114
+ # # @param known [Array<Regexp>] Array of regexp to match against
115
+ # # @param type [String] type to check
116
+ # def match_known known, type
117
+ # known.any? { |regexp| type =~ regexp }
118
+ # end
119
+ # end
115
120
  end
116
121
  end
117
122
  end
@@ -51,7 +51,7 @@ module Contrast
51
51
  super
52
52
  @settings = []
53
53
  add_config_keys(::Contrast::CONFIG.config, 'root')
54
- @settings << ENV.keys.select { |v| v.starts_with?('CONTRAST') }
54
+ @settings << ENV.keys.select { |v| v.start_with?('CONTRAST') }
55
55
  @settings.flatten
56
56
  add_tags
57
57
  end
@@ -3,8 +3,7 @@
3
3
 
4
4
  require 'contrast/components/logger'
5
5
  require 'contrast/agent/reporting/report'
6
- require 'contrast/agent/reporting/reporter_heartbeat'
7
- require 'contrast/agent/reporting/server_settings_worker'
6
+ require 'contrast/agent/reporting/reporting_workers/reporting_workers'
8
7
  require 'contrast/agent/telemetry/base'
9
8
  require 'contrast/agent/protect/input_analyzer/worth_watching_analyzer'
10
9
  require 'contrast/config/diagnostics'
@@ -19,19 +18,22 @@ module Contrast
19
18
  attr_reader :heapdump_util
20
19
  # @return [Contrast::Agent::Reporter]
21
20
  attr_reader :reporter
22
- # @return [Contrast::Agent::ReporterHeartbeat]
21
+ # @return [Contrast::Agent::ReportingWorkers::ReporterHeartbeat]
23
22
  attr_reader :reporter_heartbeat
24
23
  # @return [Contrast::Agent::Protect::WorthWatchingInputAnalyzer]
25
24
  attr_reader :worth_watching_analyzer
26
- # @return [Contrast::Agent::ServerSettingsWorker]
25
+ # @return [Contrast::Agent::ReportingWorkers::ServerSettingsWorker]
27
26
  attr_reader :reporter_settings_worker
27
+ # @return [Contrast::Agent::ReportingWorkers::ApplicationServerWorker]
28
+ attr_reader :reporter_app_settings_worker
28
29
 
29
30
  def initialize
30
31
  @pids = {}
31
32
  @heapdump_util = Contrast::Utils::HeapDumpUtil.new
32
33
  @reporter = Contrast::Agent::Reporter.new
33
- @reporter_heartbeat = Contrast::Agent::ReporterHeartbeat.new
34
- @reporter_settings_worker = Contrast::Agent::ServerSettingsWorker.new
34
+ @reporter_heartbeat = Contrast::Agent::ReportingWorkers::ReporterHeartbeat.new
35
+ @reporter_settings_worker = Contrast::Agent::ReportingWorkers::ServerSettingsWorker.new
36
+ @reporter_app_settings_worker = Contrast::Agent::ReportingWorkers::ApplicationServerWorker.new
35
37
  @telemetry = Contrast::Agent::Telemetry::Base.new if Contrast::Agent::Telemetry::Base.enabled?
36
38
  @worth_watching_analyzer = Contrast::Agent::Protect::WorthWatchingInputAnalyzer.new unless protect_disabled?
37
39
  end
@@ -41,10 +43,8 @@ module Contrast
41
43
  return unless ::Contrast::AGENT.enabled?
42
44
 
43
45
  logger.debug('ThreadWatcher started threads')
44
- reporter_status = init_thread(reporter)
45
- reporter_heartbeat_status = init_thread(reporter_heartbeat)
46
- reporter_settings_worker_status = init_thread(reporter_settings_worker)
47
- @pids[Process.pid] = reporter_status && reporter_heartbeat_status && reporter_settings_worker_status
46
+
47
+ @pids[Process.pid] = reporter_threads
48
48
  if Contrast::Agent::Telemetry::Base.enabled?
49
49
  telemetry_status = init_thread(telemetry_queue)
50
50
  @pids[Process.pid] = @pids[Process.pid] && telemetry_status
@@ -56,6 +56,11 @@ module Contrast
56
56
  @pids
57
57
  end
58
58
 
59
+ def reporter_threads
60
+ init_thread(reporter) && init_thread(reporter_heartbeat) &&
61
+ init_thread(reporter_settings_worker) && init_thread(reporter_app_settings_worker)
62
+ end
63
+
59
64
  def ensure_running?
60
65
  return if @pids[Process.pid] == true
61
66
 
@@ -84,6 +89,7 @@ module Contrast
84
89
  reporter_heartbeat&.stop!
85
90
  worth_watching_analyzer&.stop!
86
91
  reporter_settings_worker&.stop!
92
+ reporter_app_settings_worker&.stop!
87
93
  end
88
94
 
89
95
  # @return [Contrast::Agent::Telemetry::Base]
@@ -3,6 +3,6 @@
3
3
 
4
4
  module Contrast
5
5
  module Agent
6
- VERSION = '6.9.0'
6
+ VERSION = '6.10.0'
7
7
  end
8
8
  end
@@ -55,6 +55,7 @@ module Contrast
55
55
 
56
56
  # @return [Contrast::Framework::Manager]
57
57
  def self.framework_manager
58
+ reinitialize_with_log
58
59
  @_framework_manager ||= Contrast::Framework::Manager.new
59
60
  end
60
61
 
@@ -82,6 +83,17 @@ module Contrast
82
83
  def self.thread_watcher
83
84
  @_thread_watcher ||= Contrast::Agent::ThreadWatcher.new
84
85
  end
86
+
87
+ # Apparently by some unknown reason - if we have already some instance for the AgentLib - we can set the
88
+ # logger with options. That's why in rspec it started passing - because when we set the const in
89
+ # protect_spec_helper in the with AgentLib context - we've already set the AGENT_LIB constant.
90
+ #
91
+ # So that leads to this methods logic here, which somehow works
92
+ def self.reinitialize_with_log
93
+ return if Contrast::AGENT_LIB.enable_log
94
+
95
+ Contrast.cs__const_set(:AGENT_LIB, Contrast::AgentLib::Interface.new(true, 2, nil))
96
+ end
85
97
  end
86
98
  end
87
99
 
@@ -30,7 +30,6 @@ module Contrast
30
30
  # @return [Integer] Return type of the function.
31
31
  attach_function :init, [], :int
32
32
 
33
- # TODO: RUBY-1693
34
33
  # Initialize agent lib without any optional settings. To set optional settings consider using
35
34
  # `init_with_options` instead If you want to enable logging, it must be set using environment variables
36
35
  # `CONTRAST_AGENTLIB_LOG_LEVEL` - set to log level. Must of one of ERROR, WARN, INFO, DEBUG or TRACE
@@ -45,7 +44,6 @@ module Contrast
45
44
  # @return [Integer] Return type of the function.
46
45
  attach_function :init_with_options, %i[bool string string], :int
47
46
 
48
- # TODO: RUBY-1693
49
47
  # Change log settings for agent lib after it's been initialized. This api must be used after init
50
48
  #
51
49
  # Safety
@@ -55,7 +53,6 @@ module Contrast
55
53
  # if logging is enabled
56
54
  attach_function :change_log_settings, %i[bool string], :int
57
55
 
58
- # TODO: RUBY-1693
59
56
  # Initialize AgentLib with options.
60
57
  # If init returns 0 = successful setup with options
61
58
  # if init returns 1 = unsuccessful setup with options
@@ -83,16 +80,13 @@ module Contrast
83
80
  init.zero?
84
81
  end
85
82
 
86
- # TODO: RUBY-1693
87
83
  # Change the log settings. This api must be called after the dl__init_with_options.
88
84
  #
89
85
  # @param enable_log [Boolean] flag to enable or disable logging this sets the inner flag.
90
86
  # @param log_level [String] OFF, ERROR, WARN, INFO, DEBUG or TRACE.
91
87
  # @return [Boolean] true if initialized false if not.
92
88
  def dl__change_log_settings enable_log, log_level
93
- # transform to C strings pointers here and pass to function.
94
- log_dir_pointer = FFI::MemoryPointer.from_string(log_level.dup.force_encoding('UTF-8'))
95
- return true if change_log_settings(enable_log, log_dir_pointer).zero?
89
+ return true if change_log_settings(enable_log, log_level).zero?
96
90
 
97
91
  false
98
92
  end
@@ -53,12 +53,10 @@ module Contrast
53
53
  ffi_lib ContrastAgentLib::CONTRAST_C
54
54
  ffi_convention :stdcall
55
55
 
56
- DbType = enum(:DB2, :MySQL, :Oracle, :Postgres, :Sqlite, :SqlServer, :Unknown)
57
-
58
56
  # Returns 0 if evaluation was successful, -1 if there was an unexpected error.
59
57
  attach_function :check_cmd_injection_query, %i[int int string pointer], :int
60
58
  # Return 0 if evaluation was successful, -1 iif there was an unexpected error.
61
- attach_function :check_sql_injection_query, [:int, :int, DbType, :string, :pointer], :int
59
+ attach_function :check_sql_injection_query, %i[int int int string pointer], :int
62
60
  # Free function for all input tracing results pass to check functions.
63
61
  attach_function :free_check_query_sink_result, [:pointer], :int
64
62
  # Evaluate header input:
@@ -126,7 +124,7 @@ module Contrast
126
124
  # @return [Hash, nil] Returns 0 if evaluation was successful, -1 if there was an unexpected error.
127
125
  def dl__check_sql_injection_query input_index, input_length, db_type, sql_query
128
126
  db_type = :Sqlite if db_type.to_s.casecmp('sqlite3').zero?
129
- dbtype = DbType[db_type]
127
+ dbtype = Contrast::AGENT_LIB.db_set[db_type.to_s.upcase.to_sym]
130
128
  pointer = FFI::MemoryPointer.new(:pointer)
131
129
  check = check_sql_injection_query(input_index, input_length, dbtype, sql_query, pointer)
132
130
 
@@ -5,7 +5,6 @@ require 'contrast/agent_lib/api/init'
5
5
  require 'contrast/agent_lib/api/command_injection'
6
6
  require 'contrast/agent_lib/api/input_tracing'
7
7
  require 'contrast/agent_lib/api/panic'
8
- require 'contrast/agent_lib/api/method_tempering'
9
8
  require 'contrast/agent_lib/api/path_semantic_file_security_bypass'
10
9
  require 'contrast/components/logger'
11
10
  require 'contrast/utils/object_share'
@@ -24,8 +23,6 @@ module Contrast
24
23
  include Contrast::AgentLib::Panic
25
24
  include Contrast::AgentLib::InputTracing
26
25
  include Contrast::AgentLib::CommandInjection
27
- # TODO: RUBY-1632
28
- # include Contrast::AgentLib::MethodTempering
29
26
  include Contrast::AgentLib::PathSemanticFileSecurityBypass
30
27
  include Contrast::Components::Logger::InstanceMethods
31
28
 
@@ -113,7 +110,7 @@ module Contrast
113
110
  # @param level [Integer, nil] one of:
114
111
  # [-1...4]
115
112
  def log_level= level = nil
116
- set_level = level.nil? ? 3 : level
113
+ set_level = level.nil? ? 4 : level
117
114
  update_log_level(set_level)
118
115
  end
119
116
 
@@ -243,18 +240,6 @@ module Contrast
243
240
 
244
241
  with_mutex { dl__does_file_bypass_security(file_path, is_custom_code) }
245
242
  end
246
-
247
- # TODO: RUBY-1632 Test after integration and if method-tempering is covered
248
- # # Check to see if method is being tempered or not.
249
- # # Used with Protect method-tampering rule.
250
- # #
251
- # # @param method [String] method to check
252
- # # @return [Boolean]
253
- # def method_tempered? method
254
- # return false unless method
255
- #
256
- # with_mutex { dl__method_tempered?(method) }
257
- # end
258
243
  end
259
244
  end
260
245
  end