# Copyright (c) 2022 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details. # frozen_string_literal: true require 'contrast/agent/assess/events/event_factory' require 'contrast/agent/assess/policy/trigger_validation/trigger_validation' require 'contrast/components/logger' require 'contrast/utils/object_share' require 'contrast/utils/sha256_builder' require 'contrast/utils/assess/trigger_method_utils' require 'contrast/agent/assess/events/event_data' require 'contrast/agent/reporting/reporting_events/preflight' require 'contrast/agent/reporting/reporting_events/preflight_message' require 'contrast/agent/reporting/reporting_events/route_discovery' require 'contrast/agent/reporting/reporting_utilities/reporting_storage' module Contrast module Agent module Assess module Policy # A trigger method is one which can perform a dangerous action, as described by the # Contrast::Agent::Assess::Policy::TriggerNode class. Each such method will call to this module just after # invocation in order to determine if the call was done safely. In those cases where it was not, a Finding # report is issued to the Service. module TriggerMethod # rubocop:disable Metrics/ModuleLength extend Contrast::Components::Logger::InstanceMethods extend Contrast::Utils::Assess::TriggerMethodUtils # The level of TeamServer compliance our traces meet when in the abnormal condition of being dataflow rules # without routes. MINIMUM_FINDING_VERSION = 3 # The level of TeamServer compliance our traces meet. CURRENT_FINDING_VERSION = 4 # Rules that always exists outside of Request Context NON_REQUEST_RULES = [ 'hardcoded-password', # Contrast::Agent::Assess::Rule::Provider::HardcodedPassword.NAME, 'hardcoded-key' # Contrast::Agent::Assess::Rule::Provider::HardcodedKey.NAME ].cs__freeze class << self # This is called from within our woven proc. It will be called as if it were inline in the Rack # application. # # @param trigger_node [Contrast::Agent::Assess::Policy::TriggerNode] the node that applies to the method # being called # @param object [Object] the Object on which the method was invoked # @param ret [Object] the Return of the invoked method # @param args [Array] the Arguments with which the method was invoked def apply_trigger_rule trigger_node, object, ret, args return if trigger_node.nil? context = Contrast::Agent::REQUEST_TRACKER.current # return if there is no context and the flag is set to default => false # we need to have request if the flag is default # else proceed, if the flag is true we don't need to check for context we # go as currently. # When outside of a request, only track when the feature is enabled return unless Contrast::ASSESS.non_request_tracking? || context if trigger_node.sources&.any? trigger_node.sources.each do |marker| source = determine_source(marker, object, ret, args) apply_trigger(trigger_node, source, object, ret, *args) end else apply_trigger(trigger_node, nil, object, ret, *args) end end def apply_eval_trigger trigger_node, source, object, ret, *args apply_trigger(trigger_node, source, object, ret, *args) end def append_to_finding finding, event_data, request finding.rule_id = Contrast::Utils::StringUtils.protobuf_safe_string(event_data.policy_node.rule_id) finding.version = determine_compliance_version(finding) append_events(finding, event_data) append_route(finding, request) append_hash(finding, event_data.tagged, request) end # This converts the source of the finding, and the events leading up to it into a Finding # # @param trigger_node [Contrast::Agent::Assess::Policy::TriggerNode] the node to direct applying this # trigger event # @param source [Object] the source of the Trigger Event # @param object [Object] the Object on which the method was invoked # @param ret [Object] the Return of the invoked method # @param args [Array] the Arguments with which the method was invoked # @return [Contrast::Api::Dtm::Finding, nil] the Contrast::Api::Dtm::Finding to send to TeamServer or # nil if conditions were not met def build_finding trigger_node, source, object, ret, *args content_type = Contrast::Agent::REQUEST_TRACKER.current&.response&.content_type if content_type.nil? && trigger_node.collectable? Contrast::Agent::FINDINGS.collect_finding trigger_node, source, object, ret, *args return end return unless Contrast::Agent::Assess::Policy::TriggerValidation.valid?(trigger_node, object, ret, args) request = find_request(source) return unless reportable?(request&.env) if Contrast::Agent::Reporter.enabled? handle_new_finding(trigger_node, source, object, ret, request, *args) else # TODO: RUBY-1438 -- remove finding = Contrast::Api::Dtm::Finding.new event_data = Contrast::Agent::Assess::Events::EventData.new trigger_node, source, object, ret, args append_to_finding finding, event_data, request logger.trace('Finding created', node_id: trigger_node.id, source_id: source.__id__, rule: trigger_node.rule_id) report_finding(finding, request) end rescue StandardError => e logger.error('Unable to build a finding', e, rule: trigger_node.rule_id, node_id: trigger_node.id) end # Given a finding, append it to an activity message and send it to the Service for processing. If an # activity message does not exist, b/c we're invoked outside of a request context, build an activity and # immediately report it with the finding. # # TODO: RUBY-1351 # # @param finding [Contrast::Api::Dtm::Finding] the Finding to report. # @param request [Contrast::Agent::Request] our wrapper around the Rack::Request. def report_finding finding, request = nil context = Contrast::Agent::REQUEST_TRACKER.current if context context.activity.findings << finding return end return unless ::Contrast::ASSESS.non_request_tracking? || NON_REQUEST_RULES.include?(finding.rule_id) activity = Contrast::Api::Dtm::Activity.new activity.findings << finding if request activity.http_request = request.dtm else logger.debug('Attempted to report finding without request', finding: finding) end # If we're out of request context, then we need to report this finding ourselves, # so we'll send it in the one-off activity we created. Contrast::Agent.messaging_queue.send_event_eventually(activity) end def handle_new_finding trigger_node, source, object, ret, request, *args # sent to reporter # here we will generate new type of finding ruby_finding = Contrast::Agent::Reporting::Finding.new trigger_node.rule_id ruby_finding.attach_data trigger_node, source, object, ret, request, *args hash_code = Contrast::Utils::HashDigest.generate_event_hash(ruby_finding, source, request) ruby_finding.hash_code = hash_code # save the current finding Contrast::Agent::Reporting::ReportingStorage[hash_code] = ruby_finding new_preflight = Contrast::Agent::Reporting::Preflight.new new_preflight_message = Contrast::Agent::Reporting::PreflightMessage.new new_preflight_message.routes << Contrast::Agent::Reporting::RouteDiscovery.convert(request.route) new_preflight_message.hash_code = hash_code new_preflight_message.data = "#{ trigger_node.rule_id },#{ hash_code }" new_preflight.messages << new_preflight_message Contrast::Agent.reporter&.send_event_immediately(new_preflight) end private def settings Contrast::Agent::FeatureState.instance end # Given the marker from the trigger_node (the pointer indicating the entity from which the taint # originated), return the entity on which this trigger needs to operate. # # In an effort to speed up this lookup, we've changed the marker for parameters to be implicit - if it is # not a return or an object, it must be a parameter, which we can reference by index. # # @param marker [String] the source marker that indicates which Object # @param object [Object] the Object on which the method was invoked # @param ret [Object] the Return of the invoked method # @param args [Array] the Arguments with which the method was invoked # @return [Object] the literal object that this Trigger Event verifies def determine_source marker, object, ret, args case marker when Contrast::Utils::ObjectShare::RETURN_KEY ret when Contrast::Utils::ObjectShare::OBJECT_KEY object else # 'P' if marker.is_a?(Integer) args[marker] else arg = nil args.each do |search| next unless search.is_a?(Hash) arg = search[marker] break if arg end arg end end end def append_events finding, event_data append_from_source(finding, event_data.tagged) finding.events << Contrast::Agent::Assess::Events::EventFactory.build(event_data).to_dtm_event end def append_from_source finding, source return unless source return unless Contrast::Agent::Assess::Tracker.trackable?(source) properties = Contrast::Agent::Assess::Tracker.properties(source) return unless properties build_events finding, properties.event if properties.event # Google::Protobuf::Map doesn't support merge!, so we have to do this long form source_props = properties.properties return unless source_props source_props.each_pair do |key, value| key = Contrast::Utils::StringUtils.force_utf8(key) finding.properties[key] = Contrast::Utils::StringUtils.force_utf8(value) end end def build_events finding, event return unless event event.parent_events&.each do |parent_event| build_events(finding, parent_event) end # events could technically be nil, but we would have failed the rule check before getting here. not # worth the nil check finding.events << event.to_dtm_event end def append_route finding, request context = Contrast::Agent::REQUEST_TRACKER.current if context finding.routes << context.route if context.route elsif request&.route finding.routes << request.route end end def append_hash finding, source, request hash_code = Contrast::Utils::HashDigest.generate_event_hash(finding, source, request) finding.hash_code = Contrast::Utils::StringUtils.force_utf8(hash_code) finding.preflight = Contrast::Utils::PreflightUtil.create_preflight(finding) end # Because our APIs are not versioned, TeamServer relies on a field, version, to tell it what, if any, # validation it can preform on the findings we send it. Examine the finding and determine the level to # which it conforms. # # @param finding [Contrast::Api::Dtm::Finding] # @return [int] the version of compliance def determine_compliance_version finding return MINIMUM_FINDING_VERSION unless finding # as routes are the only variable between findings, in the case where we couldn't determine one, any # finding with a route is at maximum compliance return CURRENT_FINDING_VERSION if finding.routes.any? # any finding without events is not of a dataflow type and therefore at maximum compliance return CURRENT_FINDING_VERSION unless finding.events.any? MINIMUM_FINDING_VERSION end end end end end end end