stelligent / cfn_nag

Linting tool for CloudFormation templates
MIT License
1.25k stars 209 forks source link

Custom rule flagging every policy #577

Open nasirvahmed opened 2 years ago

nasirvahmed commented 2 years ago

Hello,

I am trying to implement a custom rule that takes policy actions as txt file and it seems to work fine with a handful of policies however one of the repo's which has 12 policies the custom rule consistently flags all policies. I have verified and found them all to be false positives.

When I tried to debug by adding print statements to print policy actions the rule worked as expected. I am not a ruby developer I basically followed the examples on custom rule creation so hoping someone can guide me as to why adding even a blank print statement makes this rule work?

# frozen_string_literal: true

require 'cfn-nag/violation'
require 'cfn-nag/custom_rules/base'

class IAMPolicyActionDenyRule < BaseRule
  def rule_text
    'One or more denied IAM policy actions. Please review https://.....'
  end

  def rule_type
    Violation::FAILING_VIOLATION
  end

  def rule_id
    'C1'
  end

  def audit_impl(cfn_model)
    policies = cfn_model.resources_by_type('AWS::IAM::Policy')

    violating_policies = policies.select do |policy|
      violating_statements = policy.policy_document.statements.select do |statement|
        policy_action?(statement) && policy_effect?(statement)
        #print ''
      end
      !violating_statements.empty?
    end
    violating_policies.map(&:logical_resource_id)
  end

  private

  def policy_action?(statement)
    denied_policy_actions = File.read("/app/cfn_nag/custom_rules/denied_policy_actions.txt").split
    statement.actions.find { |action| (wildcard_patterns(statement.actions).map { |pattern| "iam:#{pattern}" } + ['*']).to_s.downcase.include? action.downcase }
  end

  def policy_effect?(statement)
    statement.effect.include? "Allow"
  end
end

Note the #print '' in def audit_impl if I uncomment the rule works as expected on the repo in question.

Thanks, Nasir