contrast-agent 6.7.0 → 6.8.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (221) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +0 -2
  3. data/.simplecov +0 -1
  4. data/Rakefile +0 -1
  5. data/ext/cs__assess_array/cs__assess_array.c +41 -10
  6. data/ext/cs__assess_array/cs__assess_array.h +4 -1
  7. data/lib/contrast/agent/assess/policy/trigger_method.rb +2 -2
  8. data/lib/contrast/agent/assess/policy/trigger_validation/redos_validator.rb +1 -1
  9. data/lib/contrast/agent/assess/policy/trigger_validation/ssrf_validator.rb +1 -1
  10. data/lib/contrast/agent/assess/policy/trigger_validation/xss_validator.rb +1 -1
  11. data/lib/contrast/agent/excluder.rb +52 -34
  12. data/lib/contrast/agent/exclusion_matcher.rb +21 -9
  13. data/lib/contrast/agent/middleware.rb +4 -4
  14. data/lib/contrast/agent/patching/policy/after_load_patcher.rb +6 -0
  15. data/lib/contrast/agent/protect/input_analyzer/input_analyzer.rb +146 -127
  16. data/lib/contrast/agent/protect/policy/applies_path_traversal_rule.rb +20 -0
  17. data/lib/contrast/agent/protect/policy/rule_applicator.rb +1 -1
  18. data/lib/contrast/agent/protect/rule/base.rb +45 -53
  19. data/lib/contrast/agent/protect/rule/base_service.rb +48 -24
  20. data/lib/contrast/agent/protect/rule/bot_blocker/bot_blocker_input_classification.rb +98 -0
  21. data/lib/contrast/agent/protect/rule/bot_blocker.rb +81 -0
  22. data/lib/contrast/agent/protect/rule/cmd_injection.rb +18 -1
  23. data/lib/contrast/agent/protect/rule/cmdi/cmdi_backdoors.rb +8 -5
  24. data/lib/contrast/agent/protect/rule/cmdi/cmdi_base_rule.rb +22 -22
  25. data/lib/contrast/agent/protect/rule/cmdi/cmdi_chained_command.rb +69 -0
  26. data/lib/contrast/agent/protect/rule/cmdi/cmdi_dangerous_path.rb +68 -0
  27. data/lib/contrast/agent/protect/rule/cmdi/cmdi_input_classification.rb +2 -58
  28. data/lib/contrast/agent/protect/rule/default_scanner.rb +1 -1
  29. data/lib/contrast/agent/protect/rule/deserialization.rb +3 -14
  30. data/lib/contrast/agent/protect/rule/http_method_tampering/http_method_tampering_input_classification.rb +2 -2
  31. data/lib/contrast/agent/protect/rule/http_method_tampering.rb +0 -11
  32. data/lib/contrast/agent/protect/rule/no_sqli/no_sqli_input_classification.rb +29 -34
  33. data/lib/contrast/agent/protect/rule/no_sqli.rb +25 -18
  34. data/lib/contrast/agent/protect/rule/path_traversal/path_traversal_input_classification.rb +61 -0
  35. data/lib/contrast/agent/protect/rule/path_traversal/path_traversal_semantic_security_bypass.rb +114 -0
  36. data/lib/contrast/agent/protect/rule/path_traversal.rb +38 -12
  37. data/lib/contrast/agent/protect/rule/sql_sample_builder.rb +33 -15
  38. data/lib/contrast/agent/protect/rule/sqli/sqli_base_rule.rb +0 -14
  39. data/lib/contrast/agent/protect/rule/sqli/sqli_input_classification.rb +2 -62
  40. data/lib/contrast/agent/protect/rule/sqli.rb +70 -0
  41. data/lib/contrast/agent/protect/rule/unsafe_file_upload/unsafe_file_upload_input_classification.rb +39 -63
  42. data/lib/contrast/agent/protect/rule/unsafe_file_upload.rb +6 -33
  43. data/lib/contrast/agent/protect/rule/xss/reflected_xss_input_classification.rb +58 -0
  44. data/lib/contrast/agent/protect/rule/xss.rb +14 -20
  45. data/lib/contrast/agent/protect/rule/xxe.rb +4 -24
  46. data/lib/contrast/agent/reporting/attack_result/rasp_rule_sample.rb +18 -39
  47. data/lib/contrast/agent/reporting/attack_result/response_type.rb +9 -9
  48. data/lib/contrast/agent/reporting/details/ip_denylist_details.rb +10 -2
  49. data/lib/contrast/agent/reporting/details/virtual_patch_details.rb +8 -2
  50. data/lib/contrast/agent/reporting/input_analysis/details/bot_blocker_details.rb +27 -0
  51. data/lib/contrast/agent/reporting/input_analysis/details/protect_rule_details.rb +15 -0
  52. data/lib/contrast/agent/reporting/input_analysis/input_analysis.rb +1 -2
  53. data/lib/contrast/agent/reporting/input_analysis/input_analysis_result.rb +16 -2
  54. data/lib/contrast/agent/reporting/masker/masker.rb +2 -0
  55. data/lib/contrast/agent/reporting/reporter.rb +1 -14
  56. data/lib/contrast/agent/reporting/reporting_events/application_activity.rb +15 -12
  57. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_activity.rb +3 -3
  58. data/lib/contrast/agent/reporting/reporting_events/application_defend_attack_sample.rb +1 -2
  59. data/lib/contrast/agent/reporting/reporting_events/application_update.rb +0 -2
  60. data/lib/contrast/agent/reporting/reporting_events/architecture_component.rb +0 -1
  61. data/lib/contrast/agent/reporting/reporting_events/finding.rb +4 -4
  62. data/lib/contrast/agent/reporting/reporting_events/finding_request.rb +0 -5
  63. data/lib/contrast/agent/reporting/reporting_events/library_discovery.rb +0 -1
  64. data/lib/contrast/agent/reporting/reporting_events/poll.rb +1 -11
  65. data/lib/contrast/agent/reporting/reporting_events/route_discovery.rb +0 -1
  66. data/lib/contrast/agent/reporting/reporting_events/route_discovery_observation.rb +0 -1
  67. data/lib/contrast/agent/reporting/reporting_utilities/audit.rb +2 -2
  68. data/lib/contrast/agent/reporting/reporting_utilities/response.rb +1 -1
  69. data/lib/contrast/agent/reporting/reporting_utilities/response_handler.rb +0 -3
  70. data/lib/contrast/agent/reporting/reporting_utilities/response_handler_utils.rb +1 -0
  71. data/lib/contrast/agent/reporting/settings/code_exclusion.rb +6 -1
  72. data/lib/contrast/agent/reporting/settings/exclusion_base.rb +18 -0
  73. data/lib/contrast/agent/reporting/settings/exclusions.rb +2 -1
  74. data/lib/contrast/agent/reporting/settings/input_exclusion.rb +9 -3
  75. data/lib/contrast/agent/reporting/settings/protect.rb +15 -15
  76. data/lib/contrast/agent/request.rb +2 -14
  77. data/lib/contrast/agent/request_context.rb +6 -9
  78. data/lib/contrast/agent/request_context_extend.rb +9 -148
  79. data/lib/contrast/agent/thread_watcher.rb +3 -18
  80. data/lib/contrast/agent/version.rb +1 -1
  81. data/lib/contrast/agent.rb +0 -11
  82. data/lib/contrast/agent_lib/api/command_injection.rb +46 -0
  83. data/lib/contrast/agent_lib/api/init.rb +101 -0
  84. data/lib/contrast/agent_lib/api/input_tracing.rb +267 -0
  85. data/lib/contrast/agent_lib/api/method_tempering.rb +29 -0
  86. data/lib/contrast/agent_lib/api/panic.rb +87 -0
  87. data/lib/contrast/agent_lib/api/path_semantic_file_security_bypass.rb +40 -0
  88. data/lib/contrast/agent_lib/interface.rb +260 -0
  89. data/lib/contrast/agent_lib/interface_base.rb +118 -0
  90. data/lib/contrast/agent_lib/return_types/eval_result.rb +44 -0
  91. data/lib/contrast/agent_lib/test.rb +29 -0
  92. data/lib/contrast/api/communication/connection_status.rb +5 -5
  93. data/lib/contrast/components/agent.rb +0 -14
  94. data/lib/contrast/components/app_context.rb +0 -2
  95. data/lib/contrast/components/app_context_extend.rb +0 -25
  96. data/lib/contrast/components/config.rb +1 -18
  97. data/lib/contrast/components/protect.rb +4 -1
  98. data/lib/contrast/components/ruby_component.rb +1 -1
  99. data/lib/contrast/components/settings.rb +37 -89
  100. data/lib/contrast/config/protect_rule_configuration.rb +7 -7
  101. data/lib/contrast/config/protect_rules_configuration.rb +20 -58
  102. data/lib/contrast/configuration.rb +1 -10
  103. data/lib/contrast/extension/assess/array.rb +9 -0
  104. data/lib/contrast/extension/delegator.rb +2 -0
  105. data/lib/contrast/framework/manager.rb +3 -1
  106. data/lib/contrast/framework/rails/railtie.rb +0 -1
  107. data/lib/contrast/framework/rails/support.rb +0 -1
  108. data/lib/contrast/tasks/config.rb +1 -8
  109. data/lib/contrast/utils/duck_utils.rb +1 -0
  110. data/lib/contrast/utils/input_classification_base.rb +156 -0
  111. data/lib/contrast/utils/os.rb +0 -20
  112. data/lib/contrast/utils/response_utils.rb +0 -16
  113. data/lib/contrast/utils/stack_trace_utils.rb +3 -15
  114. data/lib/contrast/utils/string_utils.rb +10 -7
  115. data/lib/contrast.rb +2 -3
  116. data/resources/protect/policy.json +1 -2
  117. data/ruby-agent.gemspec +2 -5
  118. metadata +42 -112
  119. data/exe/contrast_service +0 -23
  120. data/lib/contrast/agent/protect/rule/cmdi/cmdi_worth_watching.rb +0 -64
  121. data/lib/contrast/agent/protect/rule/sqli/sqli_worth_watching.rb +0 -118
  122. data/lib/contrast/agent/protect/rule/unsafe_file_upload/unsafe_file_upload_matcher.rb +0 -45
  123. data/lib/contrast/agent/reaction_processor.rb +0 -47
  124. data/lib/contrast/agent/service_heartbeat.rb +0 -35
  125. data/lib/contrast/api/communication/messaging_queue.rb +0 -128
  126. data/lib/contrast/api/communication/response_processor.rb +0 -90
  127. data/lib/contrast/api/communication/service_lifecycle.rb +0 -77
  128. data/lib/contrast/api/communication/socket.rb +0 -44
  129. data/lib/contrast/api/communication/socket_client.rb +0 -130
  130. data/lib/contrast/api/communication/speedracer.rb +0 -138
  131. data/lib/contrast/api/communication/tcp_socket.rb +0 -32
  132. data/lib/contrast/api/communication/unix_socket.rb +0 -28
  133. data/lib/contrast/api/communication.rb +0 -20
  134. data/lib/contrast/api/decorators/address.rb +0 -59
  135. data/lib/contrast/api/decorators/agent_startup.rb +0 -56
  136. data/lib/contrast/api/decorators/application_settings.rb +0 -43
  137. data/lib/contrast/api/decorators/application_startup.rb +0 -56
  138. data/lib/contrast/api/decorators/bot_blocker.rb +0 -37
  139. data/lib/contrast/api/decorators/http_request.rb +0 -137
  140. data/lib/contrast/api/decorators/input_analysis.rb +0 -18
  141. data/lib/contrast/api/decorators/instrumentation_mode.rb +0 -35
  142. data/lib/contrast/api/decorators/ip_denylist.rb +0 -37
  143. data/lib/contrast/api/decorators/message.rb +0 -67
  144. data/lib/contrast/api/decorators/rasp_rule_sample.rb +0 -52
  145. data/lib/contrast/api/decorators/response_type.rb +0 -17
  146. data/lib/contrast/api/decorators/server_features.rb +0 -25
  147. data/lib/contrast/api/decorators/user_input.rb +0 -51
  148. data/lib/contrast/api/decorators/virtual_patch.rb +0 -34
  149. data/lib/contrast/api/decorators.rb +0 -22
  150. data/lib/contrast/api/dtm.pb.rb +0 -363
  151. data/lib/contrast/api/settings.pb.rb +0 -500
  152. data/lib/contrast/api.rb +0 -16
  153. data/lib/contrast/components/contrast_service.rb +0 -88
  154. data/lib/contrast/components/service.rb +0 -55
  155. data/lib/contrast/tasks/service.rb +0 -84
  156. data/lib/contrast/utils/input_classification.rb +0 -73
  157. data/lib/protobuf/code_generator.rb +0 -129
  158. data/lib/protobuf/decoder.rb +0 -28
  159. data/lib/protobuf/deprecation.rb +0 -117
  160. data/lib/protobuf/descriptors/google/protobuf/compiler/plugin.pb.rb +0 -79
  161. data/lib/protobuf/descriptors/google/protobuf/descriptor.pb.rb +0 -360
  162. data/lib/protobuf/descriptors.rb +0 -3
  163. data/lib/protobuf/encoder.rb +0 -11
  164. data/lib/protobuf/enum.rb +0 -365
  165. data/lib/protobuf/exceptions.rb +0 -9
  166. data/lib/protobuf/field/base_field.rb +0 -380
  167. data/lib/protobuf/field/base_field_object_definitions.rb +0 -504
  168. data/lib/protobuf/field/bool_field.rb +0 -64
  169. data/lib/protobuf/field/bytes_field.rb +0 -67
  170. data/lib/protobuf/field/double_field.rb +0 -25
  171. data/lib/protobuf/field/enum_field.rb +0 -56
  172. data/lib/protobuf/field/field_array.rb +0 -102
  173. data/lib/protobuf/field/field_hash.rb +0 -122
  174. data/lib/protobuf/field/fixed32_field.rb +0 -25
  175. data/lib/protobuf/field/fixed64_field.rb +0 -28
  176. data/lib/protobuf/field/float_field.rb +0 -43
  177. data/lib/protobuf/field/int32_field.rb +0 -21
  178. data/lib/protobuf/field/int64_field.rb +0 -34
  179. data/lib/protobuf/field/integer_field.rb +0 -23
  180. data/lib/protobuf/field/message_field.rb +0 -51
  181. data/lib/protobuf/field/sfixed32_field.rb +0 -27
  182. data/lib/protobuf/field/sfixed64_field.rb +0 -28
  183. data/lib/protobuf/field/signed_integer_field.rb +0 -29
  184. data/lib/protobuf/field/sint32_field.rb +0 -21
  185. data/lib/protobuf/field/sint64_field.rb +0 -21
  186. data/lib/protobuf/field/string_field.rb +0 -51
  187. data/lib/protobuf/field/uint32_field.rb +0 -21
  188. data/lib/protobuf/field/uint64_field.rb +0 -21
  189. data/lib/protobuf/field/varint_field.rb +0 -77
  190. data/lib/protobuf/field.rb +0 -74
  191. data/lib/protobuf/generators/base.rb +0 -85
  192. data/lib/protobuf/generators/enum_generator.rb +0 -39
  193. data/lib/protobuf/generators/extension_generator.rb +0 -27
  194. data/lib/protobuf/generators/field_generator.rb +0 -193
  195. data/lib/protobuf/generators/file_generator.rb +0 -262
  196. data/lib/protobuf/generators/group_generator.rb +0 -122
  197. data/lib/protobuf/generators/message_generator.rb +0 -104
  198. data/lib/protobuf/generators/option_generator.rb +0 -17
  199. data/lib/protobuf/generators/printable.rb +0 -160
  200. data/lib/protobuf/generators/service_generator.rb +0 -50
  201. data/lib/protobuf/lifecycle.rb +0 -33
  202. data/lib/protobuf/logging.rb +0 -39
  203. data/lib/protobuf/message/fields.rb +0 -233
  204. data/lib/protobuf/message/serialization.rb +0 -85
  205. data/lib/protobuf/message.rb +0 -241
  206. data/lib/protobuf/optionable.rb +0 -72
  207. data/lib/protobuf/tasks/compile.rake +0 -80
  208. data/lib/protobuf/tasks.rb +0 -1
  209. data/lib/protobuf/varint.rb +0 -20
  210. data/lib/protobuf/varint_pure.rb +0 -31
  211. data/lib/protobuf/version.rb +0 -3
  212. data/lib/protobuf/wire_type.rb +0 -10
  213. data/lib/protobuf.rb +0 -91
  214. data/proto/dynamic_discovery.proto +0 -46
  215. data/proto/google/protobuf/compiler/plugin.proto +0 -183
  216. data/proto/google/protobuf/descriptor.proto +0 -911
  217. data/proto/rpc.proto +0 -71
  218. data/service_executables/.gitkeep +0 -0
  219. data/service_executables/VERSION +0 -1
  220. data/service_executables/linux/contrast-service +0 -0
  221. data/service_executables/mac/contrast-service +0 -0
@@ -0,0 +1,267 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: false
3
+
4
+ require 'ffi'
5
+ # require the gem
6
+ require 'contrast-agent-lib'
7
+ require 'contrast/components/logger'
8
+
9
+ module Contrast
10
+ module AgentLib
11
+ # This module is defined in Rust as external, we used it here.
12
+ # Initializes the AgentLib. Here will be all methods from
13
+ # the C bindings contrast_c::input_tracing module.
14
+ module InputTracing
15
+ # Struct could be used as parameter to C functions,
16
+ # and also to save the return data. This is like
17
+ # specifying a type for pointer.
18
+ #
19
+ # Expected struct:
20
+ # pub struct CCheckQuerySinkResult {
21
+ # pub start_index: u64,
22
+ # pub end_index: u64,
23
+ # pub boundary_overrun_index: u64,
24
+ # pub input_boundary_index: u64,
25
+ # }
26
+ #
27
+ class QuerySinkResult < FFI::ManagedStruct
28
+ layout :start_index, :ulong_long,
29
+ :end_index, :ulong_long,
30
+ :boundary_overrun_index, :ulong_long,
31
+ :input_boundary_index, :ulong_long
32
+
33
+ # when QuerySinkResult object gets out of scope it will be GCed.
34
+ def self.release ptr
35
+ Contrast::AgentLib::InputTracing.dl__free_check(ptr)
36
+ end
37
+ end
38
+
39
+ # This class will be used to hold the return type from input tracings
40
+ # done with the AgentLib. Using the ManagedStruct will automatically
41
+ # call the release function, and since the memory is allocated by the
42
+ # AgentLib is should be GC also there.
43
+ class CEvalResult < FFI::ManagedStruct
44
+ layout :rule_id, :ulong_long, :input_type, :ulong_long, :score, :double
45
+
46
+ def self.release ptr
47
+ Contrast::AgentLib::InputTracing.dl__free_eval(ptr)
48
+ end
49
+ end
50
+
51
+ extend FFI::Library
52
+ include Contrast::Components::Logger::InstanceMethods
53
+ ffi_lib ContrastAgentLib::CONTRAST_C
54
+ ffi_convention :stdcall
55
+
56
+ DbType = enum(:DB2, :MySQL, :Oracle, :Postgres, :Sqlite, :SqlServer, :Unknown)
57
+
58
+ # Returns 0 if evaluation was successful, -1 if there was an unexpected error.
59
+ attach_function :check_cmd_injection_query, %i[int int string pointer], :int
60
+ # 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
62
+ # Free function for all input tracing results pass to check functions.
63
+ attach_function :free_check_query_sink_result, [:pointer], :int
64
+ # Evaluate header input:
65
+ attach_function :evaluate_header_input, %i[string string uint64 uint64 pointer pointer], :int
66
+ # Evaluate input:
67
+ attach_function :evaluate_input, %i[string uint64 uint64 uint64 pointer pointer], :int
68
+ # Free input evaluation:
69
+ attach_function :free_eval_result, [:pointer], :int
70
+ # function init
71
+ attach_function :init, [], :int
72
+
73
+ # Once we have pointer or returned data the lib
74
+ # expect us to free it, so it could GCd.
75
+ # Most of the time we would receive result pointer.
76
+ # Used with dl__check_cmdi_query and dl__check_sqli_query.
77
+ #
78
+ # @param result [Pointer]
79
+ def self.dl__free_check result
80
+ free_check_query_sink_result(result)
81
+ end
82
+
83
+ # Free the input evaluation result received from
84
+ # dl__eval_input, and dl__eval_header_input
85
+ #
86
+ # @param result [Pointer]
87
+ def self.dl__free_eval result
88
+ free_eval_result(result)
89
+ end
90
+
91
+ private
92
+
93
+ # Evaluate a subset of executing shell command for token boundaries being crossed.
94
+ # This is used by the cmd-injection rule during sink time. If a previously
95
+ # worth-watching input is contained in the shell command it crosses token
96
+ # boundaries then an injection should be raised.
97
+ #
98
+ # @param input_index [Integer] index in the cmdText string where user input was found.
99
+ # @param input_length [Integer] length of the user input.
100
+ # @return result [Hash, nil] output parameter which will contain the result of the evaluation.
101
+ def dl__check_cmdi_query input_index, input_length, input_cmd
102
+ # The memory for the result is allocated by AgentLib/Rust. So we need to create just an empty pointer
103
+ # This pointer will be populated by the output parameter of check_cmd_injection_query#
104
+ result_ptr = FFI::MemoryPointer.new(:pointer)
105
+ result_code = check_cmd_injection_query(input_index, input_length, input_cmd, result_ptr)
106
+
107
+ unless result_code == -1
108
+ struct = QuerySinkResult.new(result_ptr.read_pointer)
109
+ result_hash = dl__struct_to_result(struct)
110
+
111
+ return result_hash
112
+ end
113
+
114
+ nil
115
+ end
116
+
117
+ # This function will call the check sql injection query
118
+ # SAFETY DISCLAIMER
119
+ # The sql_query parameter must point to an allocated C-string in UTF-8 encoding
120
+ # The result MUST be free'd using free_check_query_sink_result as soon as result has been processed.
121
+ #
122
+ # @param input_index[Integer] index in the sqlQuery string where user input was found
123
+ # @param input_length[Integer] length of the user input
124
+ # @param sql_query[String] full SQL query being evaluated
125
+ # @param db_type[Integer] database engine being evaluated. Must be one of the DbType enum values
126
+ # @return [Hash, nil] Returns 0 if evaluation was successful, -1 if there was an unexpected error.
127
+ def dl__check_sql_injection_query input_index, input_length, db_type, sql_query
128
+ db_type = :Sqlite if db_type.to_s.casecmp('sqlite3').zero?
129
+ dbtype = DbType[db_type]
130
+ pointer = FFI::MemoryPointer.new(:pointer)
131
+ check = check_sql_injection_query(input_index, input_length, dbtype, sql_query, pointer)
132
+
133
+ return if check == -1
134
+
135
+ struct = QuerySinkResult.new(pointer.read_pointer)
136
+ dl__struct_to_result(struct)
137
+ rescue RuntimeError => e
138
+ # silence the runtime error from the agent lib
139
+ logger.debug('Following RuntimeError was recording during input tracing: ', e: e)
140
+ nil
141
+ ensure
142
+ pointer.free unless pointer.nil? && pointer.address
143
+ end
144
+
145
+ # Evaluates a header for input tracing rules.
146
+ #
147
+ # @param header_name [String] key/name of the header to be evaluated.
148
+ # NOTE: the only header names used are "custom", "accept", and "user-agent".
149
+ # Header-name-used is part of the output because the accept and user-agent
150
+ # headers get special handling by agent-lib, so they are evaluated twice -
151
+ # once exactly like all other headers and once with the specific header that
152
+ # gets special handling.
153
+ # @param header_value [String] header value
154
+ # @param rule_set [Integer] one or more bit flag of input tracing rules to be evaluated.
155
+ # The bit flags must match the RuleType enum. Currently supported types:
156
+ # [RuleType::CmdInjection, RuleType::PathTraversal, RuleType::SqlInjection,
157
+ # RuleType::UnsafeFileUpload, RuleType::ReflectedXss, RuleType::BotBlocker]
158
+ # public enum RuleType : ulong
159
+ # {
160
+ # UnsafeFileUpload = 1 << 0,
161
+ # PathTraversal = 1 << 1,
162
+ # ReflectedXss = 1 << 2,
163
+ # SqlInjection = 1 << 3,
164
+ # CmdInjection = 1 << 4,
165
+ # NosqlInjectionMongo = 1 << 5,
166
+ # BotBlocker = 1 << 6
167
+ # }
168
+ # @param eval_options [Integer] u64 representation of the EvalOptions enum.
169
+ # public enum EvalOptions : ulong
170
+ # {
171
+ # None = 0,
172
+ # PreferWorthWatching = 1 << 0,
173
+ # }
174
+ def dl__eval_header_input header_name, header_value, rule_set, eval_options
175
+ # The memory for the result is allocated by AgentLib/Rust. So we need to create just an empty pointer
176
+ # This pointer will be populated by the output parameter of check_cmd_injection_query#
177
+ result_ptr = FFI::MemoryPointer.new(:pointer)
178
+ result_size = FFI::MemoryPointer.new(:uint32)
179
+ # @param result_size [Integer] output parameter which will contain the number of Results after evaluation:
180
+ # 0 if no result.
181
+ evaluate_header_input(header_name, header_value, rule_set, eval_options, result_size, result_ptr)
182
+
183
+ size = result_size.read_int
184
+ result_size&.free
185
+
186
+ unless size.zero?
187
+ struct = CEvalResult.new(result_ptr.read_pointer)
188
+ return dl__eval_struct_to_result(struct)
189
+ end
190
+ nil
191
+ end
192
+
193
+ # Evaluates an input part for input tracing rules. This should be used for all input parts except headers.
194
+ #
195
+ # @param input [String] input value to be evaluated.
196
+ # @param input_type [Symbol] type of the input. This needs to be a u64 representation of the
197
+ # supported InputType enum values:
198
+ # {
199
+ # CookieName = 1,
200
+ # CookieValue = 2,
201
+ # HeaderKey = 3,
202
+ # HeaderValue = 4,
203
+ # JsonKey = 5,
204
+ # JsonValue = 6,
205
+ # Method = 7,
206
+ # ParameterKey = 8,
207
+ # ParameterValue = 9,
208
+ # UriPath = 10,
209
+ # UrlParameter = 11,
210
+ # MultipartName = 12,
211
+ # XmlValue = 13
212
+ # }
213
+ # @param rule_set [Integer] one or more bit flag of input tracing rules to be evaluated.
214
+ # The bit flags must match the RuleType enum. Currently supported types:
215
+ # [RuleType::CmdInjection, RuleType::PathTraversal, RuleType::SqlInjection,
216
+ # RuleType::UnsafeFileUpload, RuleType::ReflectedXss, RuleType::BotBlocker]
217
+ # @param eval_options [Integer] u64 representation of the EvalOptions enum.
218
+ # public enum EvalOptions : ulong
219
+ # {
220
+ # None = 0,
221
+ # PreferWorthWatching = 1 << 0,
222
+ # }
223
+ def dl__eval_input input, input_type, rule_set, eval_options
224
+ # The memory for the result is allocated by AgentLib/Rust. So we need to create just an empty pointer
225
+ # This pointer will be populated by the output parameter of check_cmd_injection_query#
226
+ result_ptr = FFI::MemoryPointer.new(:pointer)
227
+ result_size = FFI::MemoryPointer.new(:uint32)
228
+ # @param result_size [Integer] output parameter which will contain the number of Results after evaluation:
229
+ # 0 if no result.
230
+ evaluate_input(input, input_type, rule_set, eval_options, result_size, result_ptr)
231
+ size = result_size.read_int
232
+ result_size&.free
233
+
234
+ unless size.zero?
235
+ struct = CEvalResult.new(result_ptr.read_pointer)
236
+ return dl__eval_struct_to_result(struct)
237
+ end
238
+ nil
239
+ end
240
+
241
+ # Convert c_struct cmdi result to ruby hash
242
+ #
243
+ # @param struct [Contrast::AgentLib::QuerySinkResult]
244
+ # @return hash [Hash]
245
+ def dl__struct_to_result struct
246
+ hash = {}
247
+ hash[:start_index] = struct[:start_index]
248
+ hash[:end_index] = struct[:end_index]
249
+ hash[:boundary_overrun_index] = struct[:boundary_overrun_index]
250
+ hash[:input_boundary_index] = struct[:input_boundary_index]
251
+ hash
252
+ end
253
+
254
+ # Convert c_struct evaluated input to ruby hash
255
+ #
256
+ # @param struct [Contrast::AgentLib::QuerySinkResult]
257
+ # @return hash [Hash]
258
+ def dl__eval_struct_to_result struct
259
+ hash = {}
260
+ hash[:rule_id] = struct[:rule_id]
261
+ hash[:input_type] = struct[:input_type]
262
+ hash[:score] = struct[:score]
263
+ hash
264
+ end
265
+ end
266
+ end
267
+ end
@@ -0,0 +1,29 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: false
3
+
4
+ require 'ffi'
5
+ # require the gem
6
+ require 'contrast-agent-lib'
7
+
8
+ module Contrast
9
+ module AgentLib
10
+ # This module is for method tempering bindings: contrast_c::method_tampering
11
+ module MethodTempering
12
+ # TODO: RUBY-1632
13
+ # extend FFI::Library
14
+ # ffi_lib ContrastAgentLib::CONTRAST_C
15
+ #
16
+ # # returns 1 => true, 0 => false
17
+ # attach_function :is_method_tampering, [:string], :int32
18
+ #
19
+ # # Check to see if method is being tempered or not.
20
+ # # Used with Protect method-tampering rule.
21
+ # #
22
+ # # @param method [String] method to check
23
+ # # @return [Boolean]
24
+ # def dl__method_tempered? method
25
+ # is_method_tampering(method).positive?
26
+ # end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,87 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: false
3
+
4
+ require 'ffi'
5
+ # require the gem
6
+ require 'contrast-agent-lib'
7
+ require 'contrast/utils/object_share'
8
+
9
+ module Contrast
10
+ module AgentLib
11
+ # This module is defined in Rust as external, we used it here.
12
+ # Initializes the AgentLib. Here will be all methods from
13
+ # the C bindings contrast_c::panic_error module.
14
+ module Panic
15
+ extend FFI::Library
16
+ ffi_lib ContrastAgentLib::CONTRAST_C
17
+
18
+ attach_function :last_error_message, %i[pointer int32 pointer int32], :int32
19
+ attach_function :last_error_message_length, [], :int32
20
+ attach_function :last_error_stack_length, [], :int32
21
+
22
+ private
23
+
24
+ # Returns the last Error message saved for the thread.
25
+ # If there is no message it will return empty string.
26
+ #
27
+ # @return [String] Empty string if no errors, or a
28
+ # message + stack trace concat String.
29
+ def dl__get_error
30
+ message_length = last_error_message_length
31
+ stack_length = last_error_stack_length
32
+ return Contrast::Utils::ObjectShare::EMPTY_STRING if message_length.zero?
33
+
34
+ # If the buffer size is retrieved as 0 we need to add 1 byte for it
35
+ # else the Agent-Lib check for allocated memory would fail.
36
+ stack_length += 1 if stack_length.zero?
37
+ message_buffer = FFI::MemoryPointer.new(:char, message_length)
38
+ stack_buffer = FFI::MemoryPointer.new(:char, stack_length)
39
+ return dl__parse_error(message_buffer, stack_buffer) if last_error_message(message_buffer,
40
+ message_length,
41
+ stack_buffer,
42
+ stack_length).positive?
43
+
44
+ Contrast::Utils::ObjectShare::EMPTY_STRING
45
+ ensure
46
+ # The free methods are auto called form the FFI::MemoryPointer
47
+ # when the variable is out of scope. Making sure it's all free,
48
+ # and call with safe navigation if is been already cleaned.
49
+ message_buffer&.free
50
+ stack_buffer&.free
51
+ end
52
+
53
+ # Retrieves the buffer bytecode and transforms it into String.
54
+ #
55
+ # @param buffer [FFI::MemoryPointer, nil] of type char (String)
56
+ # @return [String] the received message.
57
+ def dl__read_buffer buffer
58
+ return Contrast::Utils::ObjectShare::EMPTY_STRING unless buffer
59
+
60
+ string = buffer.read_string
61
+ return string unless string.empty?
62
+
63
+ # If there is a incorrect buffer size or the message can't be read
64
+ # from the FFI::MemoryPointer#read_string method we can still try
65
+ # and get the partial message:
66
+ bytes = buffer.get_array_of_int8(0, buffer.size)&.map { |byte| byte.zero? ? nil : byte }
67
+ bytes.compact.pack('C*').force_encoding('UTF-8') if bytes&.cs__is_a?(Array)
68
+ end
69
+
70
+ # The stack_message is still not integrated in the AgentLib.
71
+ # It always returns "". For now we are returning the message,
72
+ # but keeping the functionality for feature use.
73
+ #
74
+ # @param message_buffer [FFI::MemoryPointer, nil] of type char (String)
75
+ # @param stack_buffer [FFI::MemoryPointer, nil] of type char (String)
76
+ # @return [String] the received error message with stack.
77
+ def dl__parse_error message_buffer, stack_buffer
78
+ message = dl__read_buffer(message_buffer)
79
+ stack = dl__read_buffer(stack_buffer)
80
+
81
+ error_message = "Message: #{ message }"
82
+ error_message + " Stack Trace: #{ stack }" unless stack.empty?
83
+ error_message
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,40 @@
1
+ # Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
2
+ # frozen_string_literal: false
3
+
4
+ require 'ffi'
5
+ require 'contrast-agent-lib'
6
+ require 'contrast/utils/object_share'
7
+
8
+ module Contrast
9
+ module AgentLib
10
+ # This module is defined in Rust as external, we used it here.
11
+ # Initializes the AgentLib. Here will be all methods from
12
+ # the C bindings contrast_c::path_semantic_file_security_bypass module.
13
+ module PathSemanticFileSecurityBypass
14
+ extend FFI::Library
15
+ ffi_lib ContrastAgentLib::CONTRAST_C
16
+
17
+ # Attach all the needed functions
18
+ # @param file_path[String] This is the full path of the file, being accessed
19
+ # @param is_custom_code[Integer] whether the file is being accessed by custom (user) code,
20
+ # rather than framework code.
21
+ attach_function :does_file_path_bypass_security, %i[string int], :int
22
+
23
+ private
24
+
25
+ # do we need to get the full path before we invoke it or here I need to extract the full path?
26
+
27
+ # This is the function from the agent lib, that checks if
28
+ # a given file_path is attempting to access system files
29
+ # or bypass file security
30
+ # This is used for the `path-traversal-semantic-file-security-bypass` rule.
31
+ #
32
+ # @param file_path[String] This is the full path of the file, being accessed
33
+ # @param is_custom_code[Integer] whether the file is being accessed by custom (user) code,
34
+ # rather than framework code.
35
+ def dl__does_file_bypass_security file_path, is_custom_code
36
+ does_file_path_bypass_security(file_path, is_custom_code)
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,260 @@
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/agent_lib/api/init'
5
+ require 'contrast/agent_lib/api/command_injection'
6
+ require 'contrast/agent_lib/api/input_tracing'
7
+ require 'contrast/agent_lib/api/panic'
8
+ require 'contrast/agent_lib/api/method_tempering'
9
+ require 'contrast/agent_lib/api/path_semantic_file_security_bypass'
10
+ require 'contrast/components/logger'
11
+ require 'contrast/utils/object_share'
12
+ require 'fileutils'
13
+ require 'ffi'
14
+ require 'contrast/agent_lib/return_types/eval_result'
15
+ require 'contrast/agent_lib/interface_base'
16
+
17
+ module Contrast
18
+ module AgentLib
19
+ # The interface to react with the AgentLib. This will be the one place of
20
+ # contact with the DynamicLib, synchronized and loaded with modules to use.
21
+ class Interface < InterfaceBase
22
+ # Include the modules to use from the FFI wrappers of the AgentLib.
23
+ include Contrast::AgentLib::Init
24
+ include Contrast::AgentLib::Panic
25
+ include Contrast::AgentLib::InputTracing
26
+ include Contrast::AgentLib::CommandInjection
27
+ # TODO: RUBY-1632
28
+ # include Contrast::AgentLib::MethodTempering
29
+ include Contrast::AgentLib::PathSemanticFileSecurityBypass
30
+ include Contrast::Components::Logger::InstanceMethods
31
+
32
+ # Attached methods are always public. We need to make them private
33
+ # so that this interface is the only mean to call native functions.
34
+ # The dl__ (dynamic lib) wrapper methods are used to transfer and
35
+ # convert data to required by the AgentLib types. If native method
36
+ # is called with wrong arguments a panic is raised. Public instance
37
+ # methods in this module are used to safe guard and set state by
38
+ # instance variables. Add any newly attached native functions
39
+ # included above here:
40
+ private :init, :init_with_options, :change_log_settings, :check_cmd_injection_query,
41
+ :free_check_query_sink_result, :get_index_of_chained_command, :last_error_message,
42
+ :does_command_contain_dangerous_path, :last_error_message_length, :last_error_stack_length,
43
+ :evaluate_header_input, :evaluate_input, :free_eval_result, :check_sql_injection_query,
44
+ :free_check_query_sink_result
45
+
46
+ # @return enable_log [Boolean] flag to enable or disable logging.
47
+ attr_reader :enable_log
48
+ # @return log_dir [String] path to existing log directory.
49
+ attr_reader :log_dir
50
+ # @return log_level [String] OFF, ERROR, WARN, INFO, DEBUG or TRACE.
51
+ attr_reader :log_level
52
+ # @return enable_log_change [Boolean] flag set during initialization.
53
+ # If true the log level and enable status could be change during
54
+ # runtime.
55
+ attr_reader :enable_log_change
56
+ # Initialization status
57
+ # @return [Boolean]
58
+ attr_reader :init_status
59
+ # We need to synchronize all calls to the AgentLib vie mutex or monitor.
60
+ #
61
+ # @return mutex [Mutex] to synchronize calls, also to prevent situations
62
+ # such as calling a re_init on not init lib:
63
+ # This is not the thread you are looking for.
64
+ attr_reader :mutex
65
+ # retrieves last error message.
66
+ # note: last_error_message is the name of the attached function and will
67
+ # override the agent_lib native method if renamed.
68
+ #
69
+ # @return last_error_message [String]
70
+ attr_reader :last_error
71
+
72
+ # Initializes the Agent lib.
73
+ #
74
+ # @param enable_logging [Boolean, nil] flag to enable or disable logging.
75
+ # @param set_log_level [Integer, nil]
76
+ # @param set_log_dir [String, nil] dir to write log files.
77
+ # @return [Boolean] true if success.
78
+ # @raise [StandardError] Any Errors raised in the init process are most
79
+ # likely to be a C segfaults and termination, probably redundant but safe.
80
+ def initialize enable_logging = nil, set_log_level = nil, set_log_dir = nil
81
+ super
82
+ @mutex = Mutex.new
83
+ @enable_log = !!enable_logging
84
+ self.log_level = set_log_level
85
+ @log_dir = create_log_dir(set_log_dir)
86
+ @init_status = if enable_log && log_dir && log_level
87
+ # Preferred as we will be able to to set the log level at run time.
88
+ @enable_log_change = true
89
+ with_mutex { dl__init_with_options(enable_log, log_dir, log_level) }
90
+ else
91
+ # Initialize the lib without logging.
92
+ # The log level could not be changed during runtime.
93
+ @enable_log_change = false
94
+ with_mutex { dl__init }
95
+ end
96
+ rescue StandardError => e
97
+ logger.error('Could not start АgentLib', error: e, backtrace: e.backtrace)
98
+ end
99
+
100
+ # Changes the logs level in runtime.
101
+ #
102
+ # @param new_enable_log [Boolean] flag to enable or disable logging this sets the inner flag.
103
+ # @param new_log_level [Integer]
104
+ def change_log_options new_enable_log, new_log_level
105
+ return unless @enable_log_change
106
+
107
+ update_logging(new_log_level, new_enable_log)
108
+ with_mutex { dl__change_log_settings(enable_log, log_level) }
109
+ end
110
+
111
+ # Set the log_level of the Interface.
112
+ #
113
+ # @param level [Integer, nil] one of:
114
+ # [-1...4]
115
+ def log_level= level = nil
116
+ set_level = level.nil? ? 3 : level
117
+ update_log_level(set_level)
118
+ end
119
+
120
+ # Execute calls to Native methods with mutex.
121
+ # If Error is raised from the AgentLib it will
122
+ # be logged. If C error occurs there will be a
123
+ # segfault and termination.
124
+ #
125
+ # @raise [StandardError] Capture any unforeseen errors.
126
+ # @return [String, Boolean, Integer, nil] Wrapper method's
127
+ # return types, or nil if something terrible happens.
128
+ def with_mutex &block
129
+ return_value = mutex.synchronize(&block)
130
+ rescue StandardError => e
131
+ logger.error('AgentLib runtime error', error: e, backtrace: e.backtrace)
132
+ handle_error
133
+ ensure
134
+ # Since every method is called with_mutex this is
135
+ # the natural candidate for handling any errors
136
+ # from the AgentLib.
137
+ handle_error
138
+ # The return value is used to set some instance
139
+ # variable state depending on the original return
140
+ # of the wrapper methods.
141
+ return_value
142
+ end
143
+
144
+ # Method to extract last error if any and log it.
145
+ def handle_error
146
+ @last_error = mutex.synchronize { dl__get_error }
147
+ logger.error('AgentLib encountered exception: ', error: @last_error) unless @last_error.empty?
148
+ end
149
+
150
+ # Checks that a given shell command contained a chained command.
151
+ # This is used for the cmd-injection-semantic-chained-commands rule.
152
+ #
153
+ # @param cmd [String] command to check.
154
+ # @return index[Integer, nil] Returns the index of the command chaining if found.
155
+ # If the chaining index is >= 0, an injection is detected. Returns -1 when no
156
+ # command chaining is found.
157
+ def chained_cmdi_index cmd
158
+ return unless cmd
159
+
160
+ with_mutex { dl__index_of_chained_command(cmd) }
161
+ end
162
+
163
+ # Checks if a given shell command is trying to access a dangerous path.
164
+ # This is used for the cmd-injection-semantic-dangerous-paths rule.
165
+ #
166
+ # @param path [String] path to check.
167
+ # @return index[Boolean] Returns true if a dangerous path is found.
168
+ # Returns false if no dangerous paths are found.
169
+ def dangerous_path? path
170
+ return unless path
171
+
172
+ with_mutex { dl__dangerous_path?(path) }
173
+ end
174
+
175
+ # Evaluate a subset of executing shell command for token boundaries being crossed.
176
+ # This is used by the cmd-injection rule during sink time. If a previously
177
+ # worth-watching input is contained in the shell command it crosses token
178
+ # boundaries then an injection should be raised.
179
+ #
180
+ # @param input_index [Integer] index in the cmdText string where user input was found.
181
+ # @param input_length [Integer] length of the user input.
182
+ # @param input_cmd [String] full text of the command being executed.
183
+ # @return result [Hash, nil] output parameter which will contain the result of the evaluation.
184
+ def check_cmdi_query input_index, input_length, input_cmd
185
+ return unless input_index && input_length && input_cmd
186
+
187
+ with_mutex { dl__check_cmdi_query(input_index, input_length, input_cmd) }
188
+ end
189
+
190
+ # Evaluates a header for input tracing rules.
191
+ #
192
+ # @param header_name [String] key/name of the header to be evaluated.
193
+ # NOTE: the only header names used are "custom", "accept", and "user-agent".
194
+ # Header-name-used is part of the output because the accept and user-agent
195
+ # headers get special handling by agent-lib, so they are evaluated twice -
196
+ # once exactly like all other headers and once with the specific header that
197
+ # gets special handling.
198
+ # @param header_value [String] header value
199
+ # @param rule_set [Integer] One of Contrast::AgentLib::Interface::RULE_SET
200
+ # @param eval_options [Integer] 0 or 1 from Contrast::AgentLib::Interface::EVAL_OPTIONS
201
+ # @return [Contrast::AgentLib::EvalResult, nil]
202
+ def eval_header header_name, header_value, rule_set, eval_options
203
+ return unless header_name && header_value && rule_set && eval_options
204
+
205
+ result = with_mutex { dl__eval_header_input(header_name, header_value, rule_set, eval_options) }
206
+ return EvalResult.new(result) if result
207
+
208
+ nil
209
+ end
210
+
211
+ # Evaluates an input part for input tracing rules. This should be used for all input parts except headers.
212
+ #
213
+ # @param input [String] input value to be evaluated.
214
+ # @param input_type [Integer] type of the input one of Contrast::AgentLib::Interface::INPUT_SET
215
+ # @param rule_set [Integer] One of Contrast::AgentLib::Interface::RULE_SET
216
+ # @param eval_options [Integer] 0 or 1 from Contrast::AgentLib::Interface::EVAL_OPTIONS
217
+ # @return [Contrast::AgentLib::EvalResult, nil]
218
+ def eval_input input, input_type, rule_set, eval_options
219
+ return unless input && input_type && rule_set && eval_options
220
+
221
+ result = with_mutex { dl__eval_input(input, input_type, rule_set, eval_options) }
222
+ return EvalResult.new(result) if result
223
+
224
+ nil
225
+ end
226
+
227
+ def check_sql_query input_index, input_length, db_type, sql_query
228
+ return unless input_index && input_length && db_type && sql_query
229
+
230
+ with_mutex { dl__check_sql_injection_query(input_index, input_length, db_type, sql_query) }
231
+ end
232
+
233
+ # Invoke Path Semantic File Security Bypass
234
+ #
235
+ # @param file_path[String] the absolute file path
236
+ # @param is_custom_code[Integer] is this is being called from customer (user) code
237
+ # or the framework
238
+ # @return result[Integer, nil] returns:
239
+ # 1 => security bypass is detected.
240
+ # 0 => no security bypass is detected.
241
+ def check_path_semantic_security_bypass file_path, is_custom_code
242
+ return unless file_path || is_custom_code
243
+
244
+ with_mutex { dl__does_file_bypass_security(file_path, is_custom_code) }
245
+ 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
+ end
259
+ end
260
+ end